From 0da89957f7ba6b08e5caae9de95dcf116009802d Mon Sep 17 00:00:00 2001 From: Jonas Bushart Date: Tue, 14 Feb 2017 11:05:53 +0100 Subject: [PATCH 01/15] Export attributes in save-analysis data Some annotations like the "test" annotations might be of interest for other projects, especially rls. Export all attributes in a new attributes item. --- src/librustc_save_analysis/data.rs | 12 +- src/librustc_save_analysis/dump_visitor.rs | 14 ++- src/librustc_save_analysis/external_data.rs | 118 +++++++++++++++++++- src/librustc_save_analysis/json_dumper.rs | 12 ++ src/librustc_save_analysis/lib.rs | 21 +++- 5 files changed, 171 insertions(+), 6 deletions(-) diff --git a/src/librustc_save_analysis/data.rs b/src/librustc_save_analysis/data.rs index 0a6281bf8c54c..6caf81380e40d 100644 --- a/src/librustc_save_analysis/data.rs +++ b/src/librustc_save_analysis/data.rs @@ -15,7 +15,7 @@ use rustc::hir; use rustc::hir::def_id::{CrateNum, DefId}; -use syntax::ast::{self, NodeId}; +use syntax::ast::{self, Attribute, NodeId}; use syntax_pos::Span; pub struct CrateData { @@ -136,6 +136,7 @@ pub struct EnumData { pub visibility: Visibility, pub docs: String, pub sig: Signature, + pub attributes: Vec, } /// Data for extern crates. @@ -171,6 +172,7 @@ pub struct FunctionData { pub parent: Option, pub docs: String, pub sig: Signature, + pub attributes: Vec, } /// Data about a function call. @@ -256,6 +258,7 @@ pub struct MethodData { pub visibility: Visibility, pub docs: String, pub sig: Signature, + pub attributes: Vec, } /// Data for modules. @@ -271,6 +274,7 @@ pub struct ModData { pub visibility: Visibility, pub docs: String, pub sig: Signature, + pub attributes: Vec, } /// Data for a reference to a module. @@ -295,6 +299,7 @@ pub struct StructData { pub visibility: Visibility, pub docs: String, pub sig: Signature, + pub attributes: Vec, } #[derive(Debug, RustcEncodable)] @@ -309,6 +314,7 @@ pub struct StructVariantData { pub parent: Option, pub docs: String, pub sig: Signature, + pub attributes: Vec, } #[derive(Debug, RustcEncodable)] @@ -323,6 +329,7 @@ pub struct TraitData { pub visibility: Visibility, pub docs: String, pub sig: Signature, + pub attributes: Vec, } #[derive(Debug, RustcEncodable)] @@ -337,6 +344,7 @@ pub struct TupleVariantData { pub parent: Option, pub docs: String, pub sig: Signature, + pub attributes: Vec, } /// Data for a typedef. @@ -351,6 +359,7 @@ pub struct TypeDefData { pub parent: Option, pub docs: String, pub sig: Option, + pub attributes: Vec, } /// Data for a reference to a type or trait. @@ -396,6 +405,7 @@ pub struct VariableData { pub visibility: Visibility, pub docs: String, pub sig: Option, + pub attributes: Vec, } #[derive(Debug, RustcEncodable)] diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 41f91a1d2acc1..a4b1d774be7df 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -47,7 +47,8 @@ use syntax::ptr::P; use syntax::codemap::Spanned; use syntax_pos::*; -use super::{escape, generated_code, SaveContext, PathCollector, docs_for_attrs}; +use super::{escape, generated_code, SaveContext, PathCollector, docs_for_attrs, + remove_docs_from_attrs}; use super::data::*; use super::dump::Dump; use super::external_data::{Lower, make_def_id}; @@ -373,6 +374,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { visibility: Visibility::Inherited, docs: String::new(), sig: None, + attributes: vec![], }.lower(self.tcx)); } } @@ -448,6 +450,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { visibility: vis, docs: docs_for_attrs(attrs), sig: method_data.sig, + attributes: remove_docs_from_attrs(attrs), }.lower(self.tcx)); } @@ -519,6 +522,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { parent: None, docs: String::new(), sig: None, + attributes: vec![], }.lower(self.tcx)); } } @@ -592,6 +596,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { visibility: vis, docs: docs_for_attrs(attrs), sig: None, + attributes: remove_docs_from_attrs(attrs), }.lower(self.tcx)); } @@ -636,6 +641,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { visibility: From::from(&item.vis), docs: docs_for_attrs(&item.attrs), sig: self.save_ctxt.sig_base(item), + attributes: remove_docs_from_attrs(&item.attrs), }.lower(self.tcx)); } @@ -701,6 +707,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { parent: Some(make_def_id(item.id, &self.tcx.hir)), docs: docs_for_attrs(&variant.node.attrs), sig: sig, + attributes: remove_docs_from_attrs(&variant.node.attrs), }.lower(self.tcx)); } } @@ -727,6 +734,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { parent: Some(make_def_id(item.id, &self.tcx.hir)), docs: docs_for_attrs(&variant.node.attrs), sig: sig, + attributes: remove_docs_from_attrs(&variant.node.attrs), }.lower(self.tcx)); } } @@ -813,6 +821,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { visibility: From::from(&item.vis), docs: docs_for_attrs(&item.attrs), sig: self.save_ctxt.sig_base(item), + attributes: remove_docs_from_attrs(&item.attrs), }.lower(self.tcx)); } @@ -1079,6 +1088,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { visibility: Visibility::Inherited, docs: String::new(), sig: None, + attributes: vec![], }.lower(self.tcx)); } } @@ -1320,6 +1330,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, parent: None, docs: docs_for_attrs(&item.attrs), sig: Some(self.save_ctxt.sig_base(item)), + attributes: remove_docs_from_attrs(&item.attrs), }.lower(self.tcx)); } @@ -1542,6 +1553,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, visibility: Visibility::Inherited, docs: String::new(), sig: None, + attributes: vec![], }.lower(self.tcx)); } } diff --git a/src/librustc_save_analysis/external_data.rs b/src/librustc_save_analysis/external_data.rs index fccb56e88b3de..0cfa71a349916 100644 --- a/src/librustc_save_analysis/external_data.rs +++ b/src/librustc_save_analysis/external_data.rs @@ -11,7 +11,7 @@ use rustc::hir::def_id::{CrateNum, DefId, DefIndex}; use rustc::hir::map::Map; use rustc::ty::TyCtxt; -use syntax::ast::NodeId; +use syntax::ast::{self, LitKind, NodeId, StrStyle}; use syntax::codemap::CodeMap; use syntax_pos::Span; @@ -64,6 +64,102 @@ impl SpanData { } } +/// Represent an arbitrary attribute on a code element +#[derive(Clone, Debug, RustcEncodable)] +pub struct Attribute { + value: AttributeItem, + span: SpanData, +} + +impl Lower for ast::Attribute { + type Target = Attribute; + + fn lower(self, tcx: TyCtxt) -> Attribute { + Attribute { + value: self.value.lower(tcx), + span: SpanData::from_span(self.span, tcx.sess.codemap()), + } + } +} + +impl Lower for Vec { + type Target = Vec; + + fn lower(self, tcx: TyCtxt) -> Vec { + self.into_iter().map(|x| x.lower(tcx)).collect() + } +} + +/// A single item as part of an attribute +#[derive(Clone, Debug, RustcEncodable)] +pub struct AttributeItem { + name: LitKind, + kind: AttributeItemKind, + span: SpanData, +} + +impl Lower for ast::MetaItem { + type Target = AttributeItem; + + fn lower(self, tcx: TyCtxt) -> AttributeItem { + AttributeItem { + name: LitKind::Str(self.name, StrStyle::Cooked), + kind: self.node.lower(tcx), + span: SpanData::from_span(self.span, tcx.sess.codemap()), + } + } +} + +impl Lower for ast::NestedMetaItem { + type Target = AttributeItem; + + fn lower(self, tcx: TyCtxt) -> AttributeItem { + match self.node { + ast::NestedMetaItemKind::MetaItem(item) => item.lower(tcx), + ast::NestedMetaItemKind::Literal(lit) => { + AttributeItem { + name: lit.node, + kind: AttributeItemKind::Literal, + span: SpanData::from_span(lit.span, tcx.sess.codemap()), + } + } + } + } +} + +#[derive(Clone, Debug, RustcEncodable)] +pub enum AttributeItemKind { + /// Word meta item. + /// + /// E.g. `test` as in `#[test]` + Literal, + /// Name value meta item. + /// + /// E.g. `feature = "foo"` as in `#[feature = "foo"]` + NameValue(LitKind, SpanData), + /// List meta item. + /// + /// E.g. the `derive(..)` as in `#[derive(..)]` + List(Vec), +} + +impl Lower for ast::MetaItemKind { + type Target = AttributeItemKind; + + fn lower(self, tcx: TyCtxt) -> AttributeItemKind { + match self { + ast::MetaItemKind::Word => AttributeItemKind::Literal, + ast::MetaItemKind::List(items) => { + AttributeItemKind::List(items.into_iter().map(|x| x.lower(tcx)).collect()) + } + ast::MetaItemKind::NameValue(lit) => { + let span = SpanData::from_span(lit.span, tcx.sess.codemap()); + AttributeItemKind::NameValue(lit.node, span) + } + } + } +} + #[derive(Debug, RustcEncodable)] pub struct CratePreludeData { pub crate_name: String, @@ -98,6 +194,7 @@ pub struct EnumData { pub visibility: Visibility, pub docs: String, pub sig: Signature, + pub attributes: Vec, } impl Lower for data::EnumData { @@ -115,6 +212,7 @@ impl Lower for data::EnumData { visibility: self.visibility, docs: self.docs, sig: self.sig.lower(tcx), + attributes: self.attributes.lower(tcx), } } } @@ -179,6 +277,7 @@ pub struct FunctionData { pub parent: Option, pub docs: String, pub sig: Signature, + pub attributes: Vec, } impl Lower for data::FunctionData { @@ -197,6 +296,7 @@ impl Lower for data::FunctionData { parent: self.parent, docs: self.docs, sig: self.sig.lower(tcx), + attributes: self.attributes.lower(tcx), } } } @@ -346,6 +446,7 @@ pub struct MethodData { pub parent: Option, pub docs: String, pub sig: Signature, + pub attributes: Vec, } impl Lower for data::MethodData { @@ -364,6 +465,7 @@ impl Lower for data::MethodData { parent: self.parent, docs: self.docs, sig: self.sig.lower(tcx), + attributes: self.attributes.lower(tcx), } } } @@ -381,6 +483,7 @@ pub struct ModData { pub visibility: Visibility, pub docs: String, pub sig: Signature, + pub attributes: Vec, } impl Lower for data::ModData { @@ -398,6 +501,7 @@ impl Lower for data::ModData { visibility: self.visibility, docs: self.docs, sig: self.sig.lower(tcx), + attributes: self.attributes.lower(tcx), } } } @@ -437,6 +541,7 @@ pub struct StructData { pub visibility: Visibility, pub docs: String, pub sig: Signature, + pub attributes: Vec, } impl Lower for data::StructData { @@ -455,6 +560,7 @@ impl Lower for data::StructData { visibility: self.visibility, docs: self.docs, sig: self.sig.lower(tcx), + attributes: self.attributes.lower(tcx), } } } @@ -471,6 +577,7 @@ pub struct StructVariantData { pub parent: Option, pub docs: String, pub sig: Signature, + pub attributes: Vec, } impl Lower for data::StructVariantData { @@ -488,6 +595,7 @@ impl Lower for data::StructVariantData { parent: self.parent, docs: self.docs, sig: self.sig.lower(tcx), + attributes: self.attributes.lower(tcx), } } } @@ -504,6 +612,7 @@ pub struct TraitData { pub visibility: Visibility, pub docs: String, pub sig: Signature, + pub attributes: Vec, } impl Lower for data::TraitData { @@ -521,6 +630,7 @@ impl Lower for data::TraitData { visibility: self.visibility, docs: self.docs, sig: self.sig.lower(tcx), + attributes: self.attributes.lower(tcx), } } } @@ -537,6 +647,7 @@ pub struct TupleVariantData { pub parent: Option, pub docs: String, pub sig: Signature, + pub attributes: Vec, } impl Lower for data::TupleVariantData { @@ -554,6 +665,7 @@ impl Lower for data::TupleVariantData { parent: self.parent, docs: self.docs, sig: self.sig.lower(tcx), + attributes: self.attributes.lower(tcx), } } } @@ -570,6 +682,7 @@ pub struct TypeDefData { pub parent: Option, pub docs: String, pub sig: Option, + pub attributes: Vec, } impl Lower for data::TypeDefData { @@ -586,6 +699,7 @@ impl Lower for data::TypeDefData { parent: self.parent, docs: self.docs, sig: self.sig.map(|s| s.lower(tcx)), + attributes: self.attributes.lower(tcx), } } } @@ -675,6 +789,7 @@ pub struct VariableData { pub visibility: Visibility, pub docs: String, pub sig: Option, + pub attributes: Vec, } impl Lower for data::VariableData { @@ -694,6 +809,7 @@ impl Lower for data::VariableData { visibility: self.visibility, docs: self.docs, sig: self.sig.map(|s| s.lower(tcx)), + attributes: self.attributes.lower(tcx), } } } diff --git a/src/librustc_save_analysis/json_dumper.rs b/src/librustc_save_analysis/json_dumper.rs index 16c06a556df0e..03b34f8e5e461 100644 --- a/src/librustc_save_analysis/json_dumper.rs +++ b/src/librustc_save_analysis/json_dumper.rs @@ -87,6 +87,7 @@ impl<'b, W: Write + 'b> Dump for JsonDumper<'b, W> { decl_id: None, docs: data.docs, sig: Some(From::from(data.sig)), + attributes: data.attributes, }; if def.span.file_name != def.value { // If the module is an out-of-line defintion, then we'll make the @@ -225,6 +226,7 @@ struct Def { decl_id: Option, docs: String, sig: Option, + attributes: Vec, } #[derive(Debug, RustcEncodable)] @@ -267,6 +269,7 @@ impl From for Def { decl_id: None, docs: data.docs, sig: Some(From::from(data.sig)), + attributes: data.attributes, } } } @@ -284,6 +287,7 @@ impl From for Def { decl_id: None, docs: data.docs, sig: Some(From::from(data.sig)), + attributes: data.attributes, } } } @@ -300,6 +304,7 @@ impl From for Def { decl_id: None, docs: data.docs, sig: Some(From::from(data.sig)), + attributes: data.attributes, } } } @@ -316,6 +321,7 @@ impl From for Def { decl_id: None, docs: data.docs, sig: Some(From::from(data.sig)), + attributes: data.attributes, } } } @@ -332,6 +338,7 @@ impl From for Def { decl_id: None, docs: data.docs, sig: Some(From::from(data.sig)), + attributes: data.attributes, } } } @@ -348,6 +355,7 @@ impl From for Def { decl_id: None, docs: data.docs, sig: Some(From::from(data.sig)), + attributes: data.attributes, } } } @@ -364,6 +372,7 @@ impl From for Def { decl_id: data.decl_id.map(|id| From::from(id)), docs: data.docs, sig: Some(From::from(data.sig)), + attributes: data.attributes, } } } @@ -380,6 +389,7 @@ impl From for Def { decl_id: None, docs: data.docs, sig: None, + attributes: vec![], } } } @@ -396,6 +406,7 @@ impl From for Def { decl_id: None, docs: String::new(), sig: data.sig.map(|s| From::from(s)), + attributes: data.attributes, } } } @@ -417,6 +428,7 @@ impl From for Def { decl_id: None, docs: data.docs, sig: None, + attributes: data.attributes, } } } diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index ebb33a12c8703..4fd0b443f3084 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -136,6 +136,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { parent: None, docs: docs_for_attrs(&item.attrs), sig: self.sig_base(item), + attributes: remove_docs_from_attrs(&item.attrs), })) } ast::ItemKind::Static(ref typ, mt, ref expr) => { @@ -164,6 +165,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { visibility: From::from(&item.vis), docs: docs_for_attrs(&item.attrs), sig: Some(self.sig_base(item)), + attributes: remove_docs_from_attrs(&item.attrs), })) } ast::ItemKind::Const(ref typ, ref expr) => { @@ -183,6 +185,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { visibility: From::from(&item.vis), docs: docs_for_attrs(&item.attrs), sig: Some(self.sig_base(item)), + attributes: remove_docs_from_attrs(&item.attrs), })) } ast::ItemKind::Mod(ref m) => { @@ -205,6 +208,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { visibility: From::from(&item.vis), docs: docs_for_attrs(&item.attrs), sig: self.sig_base(item), + attributes: remove_docs_from_attrs(&item.attrs), })) } ast::ItemKind::Enum(ref def, _) => { @@ -228,6 +232,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { visibility: From::from(&item.vis), docs: docs_for_attrs(&item.attrs), sig: self.sig_base(item), + attributes: remove_docs_from_attrs(&item.attrs), })) } ast::ItemKind::Impl(.., ref trait_ref, ref typ, _) => { @@ -313,6 +318,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { visibility: From::from(&field.vis), docs: docs_for_attrs(&field.attrs), sig: Some(sig), + attributes: remove_docs_from_attrs(&field.attrs), }) } else { None @@ -325,7 +331,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { name: ast::Name, span: Span) -> Option { // The qualname for a method is the trait name or name of the struct in an impl in // which the method is declared in, followed by the method's name. - let (qualname, parent_scope, decl_id, vis, docs) = + let (qualname, parent_scope, decl_id, vis, docs, attributes) = match self.tcx.impl_of_method(self.tcx.hir.local_def_id(id)) { Some(impl_id) => match self.tcx.hir.get_if_local(impl_id) { Some(Node::NodeItem(item)) => { @@ -347,7 +353,8 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { (result, trait_id, decl_id, From::from(&item.vis), - docs_for_attrs(&item.attrs)) + docs_for_attrs(&item.attrs), + remove_docs_from_attrs(&item.attrs)) } _ => { span_bug!(span, @@ -372,7 +379,8 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { (format!("::{}", self.tcx.item_path_str(def_id)), Some(def_id), None, From::from(&item.vis), - docs_for_attrs(&item.attrs)) + docs_for_attrs(&item.attrs), + remove_docs_from_attrs(&item.attrs)) } r => { span_bug!(span, @@ -421,6 +429,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { parent: parent_scope, docs: docs, sig: sig, + attributes: attributes, }) } @@ -834,6 +843,12 @@ fn docs_for_attrs(attrs: &[Attribute]) -> String { result } +/// Remove all attributes which are docs +fn remove_docs_from_attrs(attrs: &[Attribute]) -> Vec { + let doc = Symbol::intern("doc"); + attrs.iter().cloned().filter(|attr| attr.name() != doc).collect() +} + #[derive(Clone, Copy, Debug, RustcEncodable)] pub enum Format { Csv, From 346aed2edc146851374640555a886e610db0852f Mon Sep 17 00:00:00 2001 From: Jonas Bushart Date: Thu, 23 Feb 2017 23:24:12 +0100 Subject: [PATCH 02/15] Store attributes as strings Remove the AST structure --- src/librustc_save_analysis/external_data.rs | 85 +++------------------ 1 file changed, 11 insertions(+), 74 deletions(-) diff --git a/src/librustc_save_analysis/external_data.rs b/src/librustc_save_analysis/external_data.rs index 0cfa71a349916..38d1df2abb888 100644 --- a/src/librustc_save_analysis/external_data.rs +++ b/src/librustc_save_analysis/external_data.rs @@ -11,8 +11,9 @@ use rustc::hir::def_id::{CrateNum, DefId, DefIndex}; use rustc::hir::map::Map; use rustc::ty::TyCtxt; -use syntax::ast::{self, LitKind, NodeId, StrStyle}; +use syntax::ast::{self, NodeId}; use syntax::codemap::CodeMap; +use syntax::print::pprust; use syntax_pos::Span; use data::{self, Visibility, SigElement}; @@ -67,16 +68,22 @@ impl SpanData { /// Represent an arbitrary attribute on a code element #[derive(Clone, Debug, RustcEncodable)] pub struct Attribute { - value: AttributeItem, + value: String, span: SpanData, } impl Lower for ast::Attribute { type Target = Attribute; - fn lower(self, tcx: TyCtxt) -> Attribute { + fn lower(mut self, tcx: TyCtxt) -> Attribute { + // strip #[] and #![] from the original attributes + self.style = ast::AttrStyle::Outer; + let value = pprust::attribute_to_string(&self); + // #[] are all ASCII which makes this slice save + let value = value[2..value.len()-1].to_string(); + Attribute { - value: self.value.lower(tcx), + value: value, span: SpanData::from_span(self.span, tcx.sess.codemap()), } } @@ -90,76 +97,6 @@ impl Lower for Vec { } } -/// A single item as part of an attribute -#[derive(Clone, Debug, RustcEncodable)] -pub struct AttributeItem { - name: LitKind, - kind: AttributeItemKind, - span: SpanData, -} - -impl Lower for ast::MetaItem { - type Target = AttributeItem; - - fn lower(self, tcx: TyCtxt) -> AttributeItem { - AttributeItem { - name: LitKind::Str(self.name, StrStyle::Cooked), - kind: self.node.lower(tcx), - span: SpanData::from_span(self.span, tcx.sess.codemap()), - } - } -} - -impl Lower for ast::NestedMetaItem { - type Target = AttributeItem; - - fn lower(self, tcx: TyCtxt) -> AttributeItem { - match self.node { - ast::NestedMetaItemKind::MetaItem(item) => item.lower(tcx), - ast::NestedMetaItemKind::Literal(lit) => { - AttributeItem { - name: lit.node, - kind: AttributeItemKind::Literal, - span: SpanData::from_span(lit.span, tcx.sess.codemap()), - } - } - } - } -} - -#[derive(Clone, Debug, RustcEncodable)] -pub enum AttributeItemKind { - /// Word meta item. - /// - /// E.g. `test` as in `#[test]` - Literal, - /// Name value meta item. - /// - /// E.g. `feature = "foo"` as in `#[feature = "foo"]` - NameValue(LitKind, SpanData), - /// List meta item. - /// - /// E.g. the `derive(..)` as in `#[derive(..)]` - List(Vec), -} - -impl Lower for ast::MetaItemKind { - type Target = AttributeItemKind; - - fn lower(self, tcx: TyCtxt) -> AttributeItemKind { - match self { - ast::MetaItemKind::Word => AttributeItemKind::Literal, - ast::MetaItemKind::List(items) => { - AttributeItemKind::List(items.into_iter().map(|x| x.lower(tcx)).collect()) - } - ast::MetaItemKind::NameValue(lit) => { - let span = SpanData::from_span(lit.span, tcx.sess.codemap()); - AttributeItemKind::NameValue(lit.node, span) - } - } - } -} - #[derive(Debug, RustcEncodable)] pub struct CratePreludeData { pub crate_name: String, From 5bfa0f3585a91a79519dec590c2343100dbe91e7 Mon Sep 17 00:00:00 2001 From: Jonas Bushart Date: Thu, 2 Mar 2017 22:38:57 +0100 Subject: [PATCH 03/15] Move remove_docs_from_attrs into lowering step --- src/librustc_save_analysis/dump_visitor.rs | 17 +++++---- src/librustc_save_analysis/external_data.rs | 38 +++++++++++---------- src/librustc_save_analysis/lib.rs | 22 +++++------- 3 files changed, 36 insertions(+), 41 deletions(-) diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index a4b1d774be7df..b9c82b8a28be9 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -47,8 +47,7 @@ use syntax::ptr::P; use syntax::codemap::Spanned; use syntax_pos::*; -use super::{escape, generated_code, SaveContext, PathCollector, docs_for_attrs, - remove_docs_from_attrs}; +use super::{escape, generated_code, SaveContext, PathCollector, docs_for_attrs}; use super::data::*; use super::dump::Dump; use super::external_data::{Lower, make_def_id}; @@ -450,7 +449,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { visibility: vis, docs: docs_for_attrs(attrs), sig: method_data.sig, - attributes: remove_docs_from_attrs(attrs), + attributes: attrs.to_vec(), }.lower(self.tcx)); } @@ -596,7 +595,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { visibility: vis, docs: docs_for_attrs(attrs), sig: None, - attributes: remove_docs_from_attrs(attrs), + attributes: attrs.to_vec(), }.lower(self.tcx)); } @@ -641,7 +640,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { visibility: From::from(&item.vis), docs: docs_for_attrs(&item.attrs), sig: self.save_ctxt.sig_base(item), - attributes: remove_docs_from_attrs(&item.attrs), + attributes: item.attrs.clone(), }.lower(self.tcx)); } @@ -707,7 +706,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { parent: Some(make_def_id(item.id, &self.tcx.hir)), docs: docs_for_attrs(&variant.node.attrs), sig: sig, - attributes: remove_docs_from_attrs(&variant.node.attrs), + attributes: variant.node.attrs.clone(), }.lower(self.tcx)); } } @@ -734,7 +733,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { parent: Some(make_def_id(item.id, &self.tcx.hir)), docs: docs_for_attrs(&variant.node.attrs), sig: sig, - attributes: remove_docs_from_attrs(&variant.node.attrs), + attributes: variant.node.attrs.clone(), }.lower(self.tcx)); } } @@ -821,7 +820,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump + 'll> DumpVisitor<'l, 'tcx, 'll, D> { visibility: From::from(&item.vis), docs: docs_for_attrs(&item.attrs), sig: self.save_ctxt.sig_base(item), - attributes: remove_docs_from_attrs(&item.attrs), + attributes: item.attrs.clone(), }.lower(self.tcx)); } @@ -1330,7 +1329,7 @@ impl<'l, 'tcx: 'l, 'll, D: Dump +'ll> Visitor<'l> for DumpVisitor<'l, 'tcx, 'll, parent: None, docs: docs_for_attrs(&item.attrs), sig: Some(self.save_ctxt.sig_base(item)), - attributes: remove_docs_from_attrs(&item.attrs), + attributes: item.attrs.clone(), }.lower(self.tcx)); } diff --git a/src/librustc_save_analysis/external_data.rs b/src/librustc_save_analysis/external_data.rs index 38d1df2abb888..41658dc5b1b48 100644 --- a/src/librustc_save_analysis/external_data.rs +++ b/src/librustc_save_analysis/external_data.rs @@ -14,6 +14,7 @@ use rustc::ty::TyCtxt; use syntax::ast::{self, NodeId}; use syntax::codemap::CodeMap; use syntax::print::pprust; +use syntax::symbol::Symbol; use syntax_pos::Span; use data::{self, Visibility, SigElement}; @@ -72,28 +73,29 @@ pub struct Attribute { span: SpanData, } -impl Lower for ast::Attribute { - type Target = Attribute; - - fn lower(mut self, tcx: TyCtxt) -> Attribute { - // strip #[] and #![] from the original attributes - self.style = ast::AttrStyle::Outer; - let value = pprust::attribute_to_string(&self); - // #[] are all ASCII which makes this slice save - let value = value[2..value.len()-1].to_string(); - - Attribute { - value: value, - span: SpanData::from_span(self.span, tcx.sess.codemap()), - } - } -} - impl Lower for Vec { type Target = Vec; fn lower(self, tcx: TyCtxt) -> Vec { - self.into_iter().map(|x| x.lower(tcx)).collect() + let doc = Symbol::intern("doc"); + self.into_iter() + // Only retain real attributes. Doc comments are lowered separately. + .filter(|attr| attr.name() != doc) + .map(|mut attr| { + // Remove the surrounding '#[..]' or '#![..]' of the pretty printed + // attribute. First normalize all inner attribute (#![..]) to outer + // ones (#[..]), then remove the two leading and the one trailing character. + attr.style = ast::AttrStyle::Outer; + let value = pprust::attribute_to_string(&attr); + // This str slicing works correctly, because the leading and trailing characters + // are in the ASCII range and thus exactly one byte each. + let value = value[2..value.len()-1].to_string(); + + Attribute { + value: value, + span: SpanData::from_span(attr.span, tcx.sess.codemap()), + } + }).collect() } } diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index 4fd0b443f3084..b224ed923daf8 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -136,7 +136,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { parent: None, docs: docs_for_attrs(&item.attrs), sig: self.sig_base(item), - attributes: remove_docs_from_attrs(&item.attrs), + attributes: item.attrs.clone(), })) } ast::ItemKind::Static(ref typ, mt, ref expr) => { @@ -165,7 +165,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { visibility: From::from(&item.vis), docs: docs_for_attrs(&item.attrs), sig: Some(self.sig_base(item)), - attributes: remove_docs_from_attrs(&item.attrs), + attributes: item.attrs.clone(), })) } ast::ItemKind::Const(ref typ, ref expr) => { @@ -185,7 +185,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { visibility: From::from(&item.vis), docs: docs_for_attrs(&item.attrs), sig: Some(self.sig_base(item)), - attributes: remove_docs_from_attrs(&item.attrs), + attributes: item.attrs.clone(), })) } ast::ItemKind::Mod(ref m) => { @@ -208,7 +208,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { visibility: From::from(&item.vis), docs: docs_for_attrs(&item.attrs), sig: self.sig_base(item), - attributes: remove_docs_from_attrs(&item.attrs), + attributes: item.attrs.clone(), })) } ast::ItemKind::Enum(ref def, _) => { @@ -232,7 +232,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { visibility: From::from(&item.vis), docs: docs_for_attrs(&item.attrs), sig: self.sig_base(item), - attributes: remove_docs_from_attrs(&item.attrs), + attributes: item.attrs.clone(), })) } ast::ItemKind::Impl(.., ref trait_ref, ref typ, _) => { @@ -318,7 +318,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { visibility: From::from(&field.vis), docs: docs_for_attrs(&field.attrs), sig: Some(sig), - attributes: remove_docs_from_attrs(&field.attrs), + attributes: field.attrs.clone(), }) } else { None @@ -354,7 +354,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { (result, trait_id, decl_id, From::from(&item.vis), docs_for_attrs(&item.attrs), - remove_docs_from_attrs(&item.attrs)) + item.attrs.to_vec()) } _ => { span_bug!(span, @@ -380,7 +380,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { Some(def_id), None, From::from(&item.vis), docs_for_attrs(&item.attrs), - remove_docs_from_attrs(&item.attrs)) + item.attrs.to_vec()) } r => { span_bug!(span, @@ -843,12 +843,6 @@ fn docs_for_attrs(attrs: &[Attribute]) -> String { result } -/// Remove all attributes which are docs -fn remove_docs_from_attrs(attrs: &[Attribute]) -> Vec { - let doc = Symbol::intern("doc"); - attrs.iter().cloned().filter(|attr| attr.name() != doc).collect() -} - #[derive(Clone, Copy, Debug, RustcEncodable)] pub enum Format { Csv, From 5945d1dffe79f04f7dbd5fe50ef0ac613557cc89 Mon Sep 17 00:00:00 2001 From: Simonas Kazlauskas Date: Fri, 3 Mar 2017 19:11:34 +0200 Subject: [PATCH 04/15] Remove ability for plugins to register a MIR pass MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In recent months there have been a few different people investigating how to make a plugin that registers a MIR-pass – one that isn’t intended to be eventually merged into rustc proper. The interface to register MIR passes was added primarily for miri (& later was found to make prototyping of rustc-proper MIR passes a tiny bit faster). Since miri does not use this interface anymore it seems like a good time to remove this "feature". For prototyping purposes a similar interface can be added by developers themselves in their custom rustc build. --- src/librustc_driver/driver.rs | 3 +- src/librustc_plugin/registry.rs | 11 ---- .../auxiliary/dummy_mir_pass.rs | 55 ------------------- src/test/run-pass-fulldeps/mir-pass.rs | 23 -------- 4 files changed, 1 insertion(+), 91 deletions(-) delete mode 100644 src/test/run-pass-fulldeps/auxiliary/dummy_mir_pass.rs delete mode 100644 src/test/run-pass-fulldeps/mir-pass.rs diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index 9619ba8472404..dda118fb4408e 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -604,7 +604,7 @@ pub fn phase_2_configure_and_expand(sess: &Session, let whitelisted_legacy_custom_derives = registry.take_whitelisted_custom_derives(); let Registry { syntax_exts, early_lint_passes, late_lint_passes, lint_groups, - llvm_passes, attributes, mir_passes, .. } = registry; + llvm_passes, attributes, .. } = registry; sess.track_errors(|| { let mut ls = sess.lint_store.borrow_mut(); @@ -620,7 +620,6 @@ pub fn phase_2_configure_and_expand(sess: &Session, } *sess.plugin_llvm_passes.borrow_mut() = llvm_passes; - sess.mir_passes.borrow_mut().extend(mir_passes); *sess.plugin_attributes.borrow_mut() = attributes.clone(); })?; diff --git a/src/librustc_plugin/registry.rs b/src/librustc_plugin/registry.rs index 3700d0295e963..cdde56f5f634b 100644 --- a/src/librustc_plugin/registry.rs +++ b/src/librustc_plugin/registry.rs @@ -13,8 +13,6 @@ use rustc::lint::{EarlyLintPassObject, LateLintPassObject, LintId, Lint}; use rustc::session::Session; -use rustc::mir::transform::MirMapPass; - use syntax::ext::base::{SyntaxExtension, NamedSyntaxExtension, NormalTT, IdentTT}; use syntax::ext::base::MacroExpanderFn; use syntax::symbol::Symbol; @@ -53,9 +51,6 @@ pub struct Registry<'a> { #[doc(hidden)] pub late_lint_passes: Vec, - #[doc(hidden)] - pub mir_passes: Vec MirMapPass<'pcx>>>, - #[doc(hidden)] pub lint_groups: HashMap<&'static str, Vec>, @@ -81,7 +76,6 @@ impl<'a> Registry<'a> { lint_groups: HashMap::new(), llvm_passes: vec![], attributes: vec![], - mir_passes: Vec::new(), whitelisted_custom_derives: Vec::new(), } } @@ -157,11 +151,6 @@ impl<'a> Registry<'a> { self.lint_groups.insert(name, to.into_iter().map(|x| LintId::of(x)).collect()); } - /// Register a MIR pass - pub fn register_mir_pass(&mut self, pass: Box MirMapPass<'pcx>>) { - self.mir_passes.push(pass); - } - /// Register an LLVM pass. /// /// Registration with LLVM itself is handled through static C++ objects with diff --git a/src/test/run-pass-fulldeps/auxiliary/dummy_mir_pass.rs b/src/test/run-pass-fulldeps/auxiliary/dummy_mir_pass.rs deleted file mode 100644 index 3bc4a40a39c99..0000000000000 --- a/src/test/run-pass-fulldeps/auxiliary/dummy_mir_pass.rs +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// force-host - -#![feature(plugin_registrar, rustc_private)] -#![feature(box_syntax)] - -#[macro_use] extern crate rustc; -extern crate rustc_plugin; -extern crate rustc_const_math; -extern crate syntax; - -use rustc::mir::transform::{self, MirPass, MirSource}; -use rustc::mir::{Mir, Literal, Location}; -use rustc::mir::visit::MutVisitor; -use rustc::ty::TyCtxt; -use rustc::middle::const_val::ConstVal; -use rustc_const_math::ConstInt; -use rustc_plugin::Registry; - -struct Pass; - -impl transform::Pass for Pass {} - -impl<'tcx> MirPass<'tcx> for Pass { - fn run_pass<'a>(&mut self, _: TyCtxt<'a, 'tcx, 'tcx>, - _: MirSource, mir: &mut Mir<'tcx>) { - Visitor.visit_mir(mir) - } -} - -struct Visitor; - -impl<'tcx> MutVisitor<'tcx> for Visitor { - fn visit_literal(&mut self, literal: &mut Literal<'tcx>, _: Location) { - if let Literal::Value { ref mut value } = *literal { - if let ConstVal::Integral(ConstInt::I32(ref mut i @ 11)) = *value { - *i = 42; - } - } - } -} - -#[plugin_registrar] -pub fn plugin_registrar(reg: &mut Registry) { - reg.register_mir_pass(box Pass); -} diff --git a/src/test/run-pass-fulldeps/mir-pass.rs b/src/test/run-pass-fulldeps/mir-pass.rs deleted file mode 100644 index 8ac4bf9733757..0000000000000 --- a/src/test/run-pass-fulldeps/mir-pass.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2015 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// aux-build:dummy_mir_pass.rs -// ignore-stage1 - -#![feature(plugin)] -#![plugin(dummy_mir_pass)] - -fn math() -> i32 { - 11 -} - -pub fn main() { - assert_eq!(math(), 42); -} From 6698fb6029d93b992e8f89b5a89bfee2b12a80c6 Mon Sep 17 00:00:00 2001 From: Taylor Cramer Date: Fri, 17 Feb 2017 15:12:47 -0800 Subject: [PATCH 05/15] Add catch expr to AST and disallow catch as a struct name --- src/librustc/hir/lowering.rs | 37 +++++++++++++++++-- src/libsyntax/ast.rs | 2 + src/libsyntax/feature_gate.rs | 6 +++ src/libsyntax/fold.rs | 1 + src/libsyntax/parse/parser.rs | 35 ++++++++++++++++++ src/libsyntax/print/pprust.rs | 5 +++ src/libsyntax/symbol.rs | 3 +- src/libsyntax/visit.rs | 3 ++ .../compile-fail/catch-empty-struct-name.rs | 15 ++++++++ src/test/compile-fail/catch-enum-variant.rs | 17 +++++++++ src/test/compile-fail/catch-struct-name.rs | 15 ++++++++ .../compile-fail/catch-tuple-struct-name.rs | 15 ++++++++ .../compile-fail/feature-gate-catch_expr.rs | 17 +++++++++ src/test/run-pass/catch-expr.rs | 30 +++++++++++++++ 14 files changed, 196 insertions(+), 5 deletions(-) create mode 100644 src/test/compile-fail/catch-empty-struct-name.rs create mode 100644 src/test/compile-fail/catch-enum-variant.rs create mode 100644 src/test/compile-fail/catch-struct-name.rs create mode 100644 src/test/compile-fail/catch-tuple-struct-name.rs create mode 100644 src/test/compile-fail/feature-gate-catch_expr.rs create mode 100644 src/test/run-pass/catch-expr.rs diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 257cdb960d529..3d51a64c22132 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -83,6 +83,7 @@ pub struct LoweringContext<'a> { trait_impls: BTreeMap>, trait_default_impl: BTreeMap, + catch_scopes: Vec, loop_scopes: Vec, is_in_loop_condition: bool, @@ -121,6 +122,7 @@ pub fn lower_crate(sess: &Session, bodies: BTreeMap::new(), trait_impls: BTreeMap::new(), trait_default_impl: BTreeMap::new(), + catch_scopes: Vec::new(), loop_scopes: Vec::new(), is_in_loop_condition: false, type_def_lifetime_params: DefIdMap(), @@ -259,6 +261,21 @@ impl<'a> LoweringContext<'a> { span } + fn with_catch_scope(&mut self, catch_id: NodeId, f: F) -> T + where F: FnOnce(&mut LoweringContext) -> T + { + let len = self.catch_scopes.len(); + self.catch_scopes.push(catch_id); + + let result = f(self); + assert_eq!(len + 1, self.catch_scopes.len(), + "catch scopes should be added and removed in stack order"); + + self.catch_scopes.pop().unwrap(); + + result + } + fn with_loop_scope(&mut self, loop_id: NodeId, f: F) -> T where F: FnOnce(&mut LoweringContext) -> T { @@ -293,15 +310,17 @@ impl<'a> LoweringContext<'a> { result } - fn with_new_loop_scopes(&mut self, f: F) -> T + fn with_new_scopes(&mut self, f: F) -> T where F: FnOnce(&mut LoweringContext) -> T { let was_in_loop_condition = self.is_in_loop_condition; self.is_in_loop_condition = false; + let catch_scopes = mem::replace(&mut self.catch_scopes, Vec::new()); let loop_scopes = mem::replace(&mut self.loop_scopes, Vec::new()); let result = f(self); - mem::replace(&mut self.loop_scopes, loop_scopes); + self.catch_scopes = catch_scopes; + self.loop_scopes = loop_scopes; self.is_in_loop_condition = was_in_loop_condition; @@ -1063,7 +1082,7 @@ impl<'a> LoweringContext<'a> { self.record_body(value, None)) } ItemKind::Fn(ref decl, unsafety, constness, abi, ref generics, ref body) => { - self.with_new_loop_scopes(|this| { + self.with_new_scopes(|this| { let body = this.lower_block(body); let body = this.expr_block(body, ThinVec::new()); let body_id = this.record_body(body, Some(decl)); @@ -1660,13 +1679,17 @@ impl<'a> LoweringContext<'a> { this.lower_opt_sp_ident(opt_ident), hir::LoopSource::Loop)) } + ExprKind::Catch(ref body) => { + // FIXME(cramertj): Add catch to HIR + self.with_catch_scope(e.id, |this| hir::ExprBlock(this.lower_block(body))) + } ExprKind::Match(ref expr, ref arms) => { hir::ExprMatch(P(self.lower_expr(expr)), arms.iter().map(|x| self.lower_arm(x)).collect(), hir::MatchSource::Normal) } ExprKind::Closure(capture_clause, ref decl, ref body, fn_decl_span) => { - self.with_new_loop_scopes(|this| { + self.with_new_scopes(|this| { this.with_parent_def(e.id, |this| { let expr = this.lower_expr(body); hir::ExprClosure(this.lower_capture_clause(capture_clause), @@ -2064,6 +2087,12 @@ impl<'a> LoweringContext<'a> { // Err(err) => #[allow(unreachable_code)] // return Carrier::from_error(From::from(err)), // } + + // FIXME(cramertj): implement breaking to catch + if !self.catch_scopes.is_empty() { + bug!("`?` in catch scopes is unimplemented") + } + let unstable_span = self.allow_internal_unstable("?", e.span); // Carrier::translate() diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 09fb369cd3568..bb0aa6e94b72a 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -936,6 +936,8 @@ pub enum ExprKind { Closure(CaptureBy, P, P, Span), /// A block (`{ ... }`) Block(P), + /// A catch block (`catch { ... }`) + Catch(P), /// An assignment (`a = foo()`) Assign(P, P), diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index 6eb7d449f2692..b776441079ef0 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -340,6 +340,9 @@ declare_features! ( // `extern "x86-interrupt" fn()` (active, abi_x86_interrupt, "1.17.0", Some(40180)), + + // Allows the `catch {...}` expression + (active, catch_expr, "1.17.0", Some(31436)), ); declare_features! ( @@ -1288,6 +1291,9 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { } } } + ast::ExprKind::Catch(_) => { + gate_feature_post!(&self, catch_expr, e.span, "`catch` expression is experimental"); + } _ => {} } visit::walk_expr(self, e); diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 257b7efba5c8e..3150ab0be0bea 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -1276,6 +1276,7 @@ pub fn noop_fold_expr(Expr {id, node, span, attrs}: Expr, folder: &mu }; } ExprKind::Try(ex) => ExprKind::Try(folder.fold_expr(ex)), + ExprKind::Catch(body) => ExprKind::Catch(folder.fold_block(body)), }, id: folder.new_id(id), span: folder.new_span(span), diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 71274c4fdaa4e..eef252319bcc2 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -515,6 +515,12 @@ impl<'a> Parser<'a> { } } + pub fn error_if_typename_is_catch(&mut self, ident: ast::Ident) { + if ident.name == keywords::Catch.name() { + self.span_err(self.span, "cannot use `catch` as the name of a type"); + } + } + /// Check if the next token is `tok`, and return `true` if so. /// /// This method will automatically add `tok` to `expected_tokens` if `tok` is not @@ -2196,6 +2202,11 @@ impl<'a> Parser<'a> { BlockCheckMode::Unsafe(ast::UserProvided), attrs); } + if self.is_catch_expr() { + assert!(self.eat_keyword(keywords::Catch)); + let lo = self.prev_span.lo; + return self.parse_catch_expr(lo, attrs); + } if self.eat_keyword(keywords::Return) { if self.token.can_begin_expr() { let e = self.parse_expr()?; @@ -3006,6 +3017,16 @@ impl<'a> Parser<'a> { Ok(self.mk_expr(span_lo, hi, ExprKind::Loop(body, opt_ident), attrs)) } + /// Parse a `catch {...}` expression (`catch` token already eaten) + pub fn parse_catch_expr(&mut self, span_lo: BytePos, mut attrs: ThinVec) + -> PResult<'a, P> + { + let (iattrs, body) = self.parse_inner_attrs_and_block()?; + attrs.extend(iattrs); + let hi = body.span.hi; + Ok(self.mk_expr(span_lo, hi, ExprKind::Catch(body), attrs)) + } + // `match` token already eaten fn parse_match_expr(&mut self, mut attrs: ThinVec) -> PResult<'a, P> { let match_span = self.prev_span; @@ -3613,6 +3634,14 @@ impl<'a> Parser<'a> { }) } + fn is_catch_expr(&mut self) -> bool { + self.token.is_keyword(keywords::Catch) && + self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) && + + // prevent `while catch {} {}`, `if catch {} {} else {}`, etc. + !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL) + } + fn is_union_item(&mut self) -> bool { self.token.is_keyword(keywords::Union) && self.look_ahead(1, |t| t.is_ident() && !t.is_any_keyword()) @@ -4753,6 +4782,8 @@ impl<'a> Parser<'a> { /// Parse struct Foo { ... } fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> { let class_name = self.parse_ident()?; + self.error_if_typename_is_catch(class_name); + let mut generics = self.parse_generics()?; // There is a special case worth noting here, as reported in issue #17904. @@ -4802,6 +4833,8 @@ impl<'a> Parser<'a> { /// Parse union Foo { ... } fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> { let class_name = self.parse_ident()?; + self.error_if_typename_is_catch(class_name); + let mut generics = self.parse_generics()?; let vdata = if self.token.is_keyword(keywords::Where) { @@ -5318,6 +5351,7 @@ impl<'a> Parser<'a> { let struct_def; let mut disr_expr = None; let ident = self.parse_ident()?; + self.error_if_typename_is_catch(ident); if self.check(&token::OpenDelim(token::Brace)) { // Parse a struct variant. all_nullary = false; @@ -5359,6 +5393,7 @@ impl<'a> Parser<'a> { /// Parse an "enum" declaration fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> { let id = self.parse_ident()?; + self.error_if_typename_is_catch(id); let mut generics = self.parse_generics()?; generics.where_clause = self.parse_where_clause()?; self.expect(&token::OpenDelim(token::Brace))?; diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index ec962d03458d1..a827d2c6bdbf2 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -2270,6 +2270,11 @@ impl<'a> State<'a> { self.print_expr(e)?; word(&mut self.s, "?")? } + ast::ExprKind::Catch(ref blk) => { + self.head("catch")?; + space(&mut self.s)?; + self.print_block_with_attrs(&blk, attrs)? + } } self.ann.post(self, NodeExpr(expr))?; self.end() diff --git a/src/libsyntax/symbol.rs b/src/libsyntax/symbol.rs index c278171aa109a..6642c60d256b3 100644 --- a/src/libsyntax/symbol.rs +++ b/src/libsyntax/symbol.rs @@ -221,9 +221,10 @@ declare_keywords! { (53, Default, "default") (54, StaticLifetime, "'static") (55, Union, "union") + (56, Catch, "catch") // A virtual keyword that resolves to the crate root when used in a lexical scope. - (56, CrateRoot, "{{root}}") + (57, CrateRoot, "{{root}}") } // If an interner exists in TLS, return it. Otherwise, prepare a fresh one. diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 013632141dee6..c76846cdf8e27 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -787,6 +787,9 @@ pub fn walk_expr<'a, V: Visitor<'a>>(visitor: &mut V, expression: &'a Expr) { ExprKind::Try(ref subexpression) => { visitor.visit_expr(subexpression) } + ExprKind::Catch(ref body) => { + visitor.visit_block(body) + } } visitor.visit_expr_post(expression) diff --git a/src/test/compile-fail/catch-empty-struct-name.rs b/src/test/compile-fail/catch-empty-struct-name.rs new file mode 100644 index 0000000000000..257cb802cc0f8 --- /dev/null +++ b/src/test/compile-fail/catch-empty-struct-name.rs @@ -0,0 +1,15 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(non_camel_case_types)] +#![allow(dead_code)] +#![feature(catch_expr)] + +struct catch; //~ ERROR cannot use `catch` as the name of a type diff --git a/src/test/compile-fail/catch-enum-variant.rs b/src/test/compile-fail/catch-enum-variant.rs new file mode 100644 index 0000000000000..7aa162750d189 --- /dev/null +++ b/src/test/compile-fail/catch-enum-variant.rs @@ -0,0 +1,17 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(non_camel_case_types)] +#![allow(dead_code)] +#![feature(catch_expr)] + +enum Enum { + catch {} //~ ERROR cannot use `catch` as the name of a type +} diff --git a/src/test/compile-fail/catch-struct-name.rs b/src/test/compile-fail/catch-struct-name.rs new file mode 100644 index 0000000000000..63661ccf607a0 --- /dev/null +++ b/src/test/compile-fail/catch-struct-name.rs @@ -0,0 +1,15 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(non_camel_case_types)] +#![allow(dead_code)] +#![feature(catch_expr)] + +struct catch {} //~ ERROR cannot use `catch` as the name of a type \ No newline at end of file diff --git a/src/test/compile-fail/catch-tuple-struct-name.rs b/src/test/compile-fail/catch-tuple-struct-name.rs new file mode 100644 index 0000000000000..1a8866d85430d --- /dev/null +++ b/src/test/compile-fail/catch-tuple-struct-name.rs @@ -0,0 +1,15 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![allow(non_camel_case_types)] +#![allow(dead_code)] +#![feature(catch_expr)] + +struct catch(); //~ ERROR cannot use `catch` as the name of a type diff --git a/src/test/compile-fail/feature-gate-catch_expr.rs b/src/test/compile-fail/feature-gate-catch_expr.rs new file mode 100644 index 0000000000000..8a1a5ceae89e0 --- /dev/null +++ b/src/test/compile-fail/feature-gate-catch_expr.rs @@ -0,0 +1,17 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +pub fn main() { + let catch_result = catch { //~ ERROR `catch` expression is experimental + let x = 5; + x + }; + assert_eq!(catch_result, 5); +} diff --git a/src/test/run-pass/catch-expr.rs b/src/test/run-pass/catch-expr.rs new file mode 100644 index 0000000000000..c70b6100efe4f --- /dev/null +++ b/src/test/run-pass/catch-expr.rs @@ -0,0 +1,30 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(catch_expr)] + +pub fn main() { + let catch_result = catch { + let x = 5; + x + }; + assert_eq!(catch_result, 5); + + let mut catch = true; + while catch { catch = false; } + assert_eq!(catch, false); + + catch = if catch { false } else { true }; + assert_eq!(catch, true); + + match catch { + _ => {} + }; +} From ace24bb653850e5955ec14cc6aef1af61022f85e Mon Sep 17 00:00:00 2001 From: Taylor Cramer Date: Fri, 3 Mar 2017 14:41:07 -0800 Subject: [PATCH 06/15] Temporarily prefix catch block with do keyword --- src/libsyntax/parse/parser.rs | 18 +++++------------- src/libsyntax/parse/token.rs | 1 + .../compile-fail/catch-empty-struct-name.rs | 15 --------------- src/test/compile-fail/catch-enum-variant.rs | 17 ----------------- src/test/compile-fail/catch-struct-name.rs | 15 --------------- .../compile-fail/catch-tuple-struct-name.rs | 15 --------------- .../compile-fail/feature-gate-catch_expr.rs | 2 +- src/test/run-pass/catch-expr.rs | 4 +++- 8 files changed, 10 insertions(+), 77 deletions(-) delete mode 100644 src/test/compile-fail/catch-empty-struct-name.rs delete mode 100644 src/test/compile-fail/catch-enum-variant.rs delete mode 100644 src/test/compile-fail/catch-struct-name.rs delete mode 100644 src/test/compile-fail/catch-tuple-struct-name.rs diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index eef252319bcc2..c654ad066c861 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -515,12 +515,6 @@ impl<'a> Parser<'a> { } } - pub fn error_if_typename_is_catch(&mut self, ident: ast::Ident) { - if ident.name == keywords::Catch.name() { - self.span_err(self.span, "cannot use `catch` as the name of a type"); - } - } - /// Check if the next token is `tok`, and return `true` if so. /// /// This method will automatically add `tok` to `expected_tokens` if `tok` is not @@ -2203,6 +2197,7 @@ impl<'a> Parser<'a> { attrs); } if self.is_catch_expr() { + assert!(self.eat_keyword(keywords::Do)); assert!(self.eat_keyword(keywords::Catch)); let lo = self.prev_span.lo; return self.parse_catch_expr(lo, attrs); @@ -3017,7 +3012,7 @@ impl<'a> Parser<'a> { Ok(self.mk_expr(span_lo, hi, ExprKind::Loop(body, opt_ident), attrs)) } - /// Parse a `catch {...}` expression (`catch` token already eaten) + /// Parse a `do catch {...}` expression (`do catch` token already eaten) pub fn parse_catch_expr(&mut self, span_lo: BytePos, mut attrs: ThinVec) -> PResult<'a, P> { @@ -3635,8 +3630,9 @@ impl<'a> Parser<'a> { } fn is_catch_expr(&mut self) -> bool { - self.token.is_keyword(keywords::Catch) && - self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) && + self.token.is_keyword(keywords::Do) && + self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) && + self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) && // prevent `while catch {} {}`, `if catch {} {} else {}`, etc. !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL) @@ -4782,7 +4778,6 @@ impl<'a> Parser<'a> { /// Parse struct Foo { ... } fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> { let class_name = self.parse_ident()?; - self.error_if_typename_is_catch(class_name); let mut generics = self.parse_generics()?; @@ -4833,7 +4828,6 @@ impl<'a> Parser<'a> { /// Parse union Foo { ... } fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> { let class_name = self.parse_ident()?; - self.error_if_typename_is_catch(class_name); let mut generics = self.parse_generics()?; @@ -5351,7 +5345,6 @@ impl<'a> Parser<'a> { let struct_def; let mut disr_expr = None; let ident = self.parse_ident()?; - self.error_if_typename_is_catch(ident); if self.check(&token::OpenDelim(token::Brace)) { // Parse a struct variant. all_nullary = false; @@ -5393,7 +5386,6 @@ impl<'a> Parser<'a> { /// Parse an "enum" declaration fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> { let id = self.parse_ident()?; - self.error_if_typename_is_catch(id); let mut generics = self.parse_generics()?; generics.where_clause = self.parse_where_clause()?; self.expect(&token::OpenDelim(token::Brace))?; diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index 5b65aac92b81c..25601f2420e8a 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -86,6 +86,7 @@ fn ident_can_begin_expr(ident: ast::Ident) -> bool { !ident_token.is_any_keyword() || ident_token.is_path_segment_keyword() || [ + keywords::Do.name(), keywords::Box.name(), keywords::Break.name(), keywords::Continue.name(), diff --git a/src/test/compile-fail/catch-empty-struct-name.rs b/src/test/compile-fail/catch-empty-struct-name.rs deleted file mode 100644 index 257cb802cc0f8..0000000000000 --- a/src/test/compile-fail/catch-empty-struct-name.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(non_camel_case_types)] -#![allow(dead_code)] -#![feature(catch_expr)] - -struct catch; //~ ERROR cannot use `catch` as the name of a type diff --git a/src/test/compile-fail/catch-enum-variant.rs b/src/test/compile-fail/catch-enum-variant.rs deleted file mode 100644 index 7aa162750d189..0000000000000 --- a/src/test/compile-fail/catch-enum-variant.rs +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(non_camel_case_types)] -#![allow(dead_code)] -#![feature(catch_expr)] - -enum Enum { - catch {} //~ ERROR cannot use `catch` as the name of a type -} diff --git a/src/test/compile-fail/catch-struct-name.rs b/src/test/compile-fail/catch-struct-name.rs deleted file mode 100644 index 63661ccf607a0..0000000000000 --- a/src/test/compile-fail/catch-struct-name.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(non_camel_case_types)] -#![allow(dead_code)] -#![feature(catch_expr)] - -struct catch {} //~ ERROR cannot use `catch` as the name of a type \ No newline at end of file diff --git a/src/test/compile-fail/catch-tuple-struct-name.rs b/src/test/compile-fail/catch-tuple-struct-name.rs deleted file mode 100644 index 1a8866d85430d..0000000000000 --- a/src/test/compile-fail/catch-tuple-struct-name.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![allow(non_camel_case_types)] -#![allow(dead_code)] -#![feature(catch_expr)] - -struct catch(); //~ ERROR cannot use `catch` as the name of a type diff --git a/src/test/compile-fail/feature-gate-catch_expr.rs b/src/test/compile-fail/feature-gate-catch_expr.rs index 8a1a5ceae89e0..5568a5cf0aac2 100644 --- a/src/test/compile-fail/feature-gate-catch_expr.rs +++ b/src/test/compile-fail/feature-gate-catch_expr.rs @@ -9,7 +9,7 @@ // except according to those terms. pub fn main() { - let catch_result = catch { //~ ERROR `catch` expression is experimental + let catch_result = do catch { //~ ERROR `catch` expression is experimental let x = 5; x }; diff --git a/src/test/run-pass/catch-expr.rs b/src/test/run-pass/catch-expr.rs index c70b6100efe4f..a9b28a534a348 100644 --- a/src/test/run-pass/catch-expr.rs +++ b/src/test/run-pass/catch-expr.rs @@ -10,8 +10,10 @@ #![feature(catch_expr)] +struct catch {} + pub fn main() { - let catch_result = catch { + let catch_result = do catch { let x = 5; x }; From cd7bde99b127e6d7476de047ba3a5bcb0c2c25df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Thu, 19 Jan 2017 23:17:48 -0800 Subject: [PATCH 07/15] Point to enclosing block/fn on nested unsafe When declaring nested unsafe blocks (`unsafe {unsafe {}}`) that trigger the "unnecessary `unsafe` block" error, point out the enclosing `unsafe block` or `unsafe fn` that makes it unnecessary. --- src/librustc_lint/unused.rs | 29 ++++- .../span}/lint-unused-unsafe.rs | 0 src/test/ui/span/lint-unused-unsafe.stderr | 116 ++++++++++++++++++ 3 files changed, 144 insertions(+), 1 deletion(-) rename src/test/{compile-fail => ui/span}/lint-unused-unsafe.rs (100%) create mode 100644 src/test/ui/span/lint-unused-unsafe.stderr diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index 28ce9126019eb..f9b7c68587678 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -189,11 +189,38 @@ impl LintPass for UnusedUnsafe { impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedUnsafe { fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) { + /// Return the NodeId for an enclosing scope that is also `unsafe` + fn is_enclosed(cx: &LateContext, id: ast::NodeId) -> Option<(String, ast::NodeId)> { + let parent_id = cx.tcx.hir.get_parent_node(id); + if parent_id != id { + if cx.tcx.used_unsafe.borrow().contains(&parent_id) { + Some(("block".to_string(), parent_id)) + } else if let Some(hir::map::NodeItem(&hir::Item { + node: hir::ItemFn(_, hir::Unsafety::Unsafe, _, _, _, _), + .. + })) = cx.tcx.hir.find(parent_id) { + Some(("fn".to_string(), parent_id)) + } else { + is_enclosed(cx, parent_id) + } + } else { + None + } + } if let hir::ExprBlock(ref blk) = e.node { // Don't warn about generated blocks, that'll just pollute the output. if blk.rules == hir::UnsafeBlock(hir::UserProvided) && !cx.tcx.used_unsafe.borrow().contains(&blk.id) { - cx.span_lint(UNUSED_UNSAFE, blk.span, "unnecessary `unsafe` block"); + + let mut db = cx.struct_span_lint(UNUSED_UNSAFE, blk.span, + "unnecessary `unsafe` block"); + + db.span_label(blk.span, &"unnecessary `unsafe` block"); + if let Some((kind, id)) = is_enclosed(cx, blk.id) { + db.span_note(cx.tcx.hir.span(id), + &format!("because it's nested under this `unsafe` {}", kind)); + } + db.emit(); } } } diff --git a/src/test/compile-fail/lint-unused-unsafe.rs b/src/test/ui/span/lint-unused-unsafe.rs similarity index 100% rename from src/test/compile-fail/lint-unused-unsafe.rs rename to src/test/ui/span/lint-unused-unsafe.rs diff --git a/src/test/ui/span/lint-unused-unsafe.stderr b/src/test/ui/span/lint-unused-unsafe.stderr new file mode 100644 index 0000000000000..0df3fa43022a4 --- /dev/null +++ b/src/test/ui/span/lint-unused-unsafe.stderr @@ -0,0 +1,116 @@ +error: unnecessary `unsafe` block + --> $DIR/lint-unused-unsafe.rs:26:13 + | +26 | fn bad1() { unsafe {} } //~ ERROR: unnecessary `unsafe` block + | ^^^^^^^^^ unnecessary `unsafe` block + | +note: lint level defined here + --> $DIR/lint-unused-unsafe.rs:14:9 + | +14 | #![deny(unused_unsafe)] + | ^^^^^^^^^^^^^ + +error: unnecessary `unsafe` block + --> $DIR/lint-unused-unsafe.rs:27:13 + | +27 | fn bad2() { unsafe { bad1() } } //~ ERROR: unnecessary `unsafe` block + | ^^^^^^^^^^^^^^^^^ unnecessary `unsafe` block + +error: unnecessary `unsafe` block + --> $DIR/lint-unused-unsafe.rs:28:20 + | +28 | unsafe fn bad3() { unsafe {} } //~ ERROR: unnecessary `unsafe` block + | ^^^^^^^^^ unnecessary `unsafe` block + | +note: because it's nested under this `unsafe` fn + --> $DIR/lint-unused-unsafe.rs:28:1 + | +28 | unsafe fn bad3() { unsafe {} } //~ ERROR: unnecessary `unsafe` block + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: unnecessary `unsafe` block + --> $DIR/lint-unused-unsafe.rs:29:13 + | +29 | fn bad4() { unsafe { callback(||{}) } } //~ ERROR: unnecessary `unsafe` block + | ^^^^^^^^^^^^^^^^^^^^^^^^^ unnecessary `unsafe` block + +error: unnecessary `unsafe` block + --> $DIR/lint-unused-unsafe.rs:30:20 + | +30 | unsafe fn bad5() { unsafe { unsf() } } //~ ERROR: unnecessary `unsafe` block + | ^^^^^^^^^^^^^^^^^ unnecessary `unsafe` block + | +note: because it's nested under this `unsafe` fn + --> $DIR/lint-unused-unsafe.rs:30:1 + | +30 | unsafe fn bad5() { unsafe { unsf() } } //~ ERROR: unnecessary `unsafe` block + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: unnecessary `unsafe` block + --> $DIR/lint-unused-unsafe.rs:33:9 + | +33 | unsafe { //~ ERROR: unnecessary `unsafe` block + | _________^ starting here... +34 | | unsf() +35 | | } + | |_________^ ...ending here: unnecessary `unsafe` block + | +note: because it's nested under this `unsafe` block + --> $DIR/lint-unused-unsafe.rs:32:5 + | +32 | unsafe { // don't put the warning here + | _____^ starting here... +33 | | unsafe { //~ ERROR: unnecessary `unsafe` block +34 | | unsf() +35 | | } +36 | | } + | |_____^ ...ending here + +error: unnecessary `unsafe` block + --> $DIR/lint-unused-unsafe.rs:39:5 + | +39 | unsafe { //~ ERROR: unnecessary `unsafe` block + | _____^ starting here... +40 | | unsafe { //~ ERROR: unnecessary `unsafe` block +41 | | unsf() +42 | | } +43 | | } + | |_____^ ...ending here: unnecessary `unsafe` block + | +note: because it's nested under this `unsafe` fn + --> $DIR/lint-unused-unsafe.rs:38:1 + | +38 | unsafe fn bad7() { + | _^ starting here... +39 | | unsafe { //~ ERROR: unnecessary `unsafe` block +40 | | unsafe { //~ ERROR: unnecessary `unsafe` block +41 | | unsf() +42 | | } +43 | | } +44 | | } + | |_^ ...ending here + +error: unnecessary `unsafe` block + --> $DIR/lint-unused-unsafe.rs:40:9 + | +40 | unsafe { //~ ERROR: unnecessary `unsafe` block + | _________^ starting here... +41 | | unsf() +42 | | } + | |_________^ ...ending here: unnecessary `unsafe` block + | +note: because it's nested under this `unsafe` fn + --> $DIR/lint-unused-unsafe.rs:38:1 + | +38 | unsafe fn bad7() { + | _^ starting here... +39 | | unsafe { //~ ERROR: unnecessary `unsafe` block +40 | | unsafe { //~ ERROR: unnecessary `unsafe` block +41 | | unsf() +42 | | } +43 | | } +44 | | } + | |_^ ...ending here + +error: aborting due to 8 previous errors + From eeb7af61164c6f7bf0d328f90793a3ad48d39529 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 1 Mar 2017 15:34:54 -0800 Subject: [PATCH 08/15] rustbuild: Build documentation for `proc_macro` This commit fixes #38749 by building documentation for the `proc_macro` crate by default for configured hosts. Unfortunately did not turn out to be a trivial fix. Currently rustbuild generates documentation into multiple locations: one for std, one for test, and one for rustc. The initial fix for this issue simply actually executed `cargo doc -p proc_macro` which was otherwise completely elided before. Unfortunately rustbuild was the left to merge two documentation trees together. One for the standard library and one for the rustc tree (which only had docs for the `proc_macro` crate). Rustdoc itself knows how to merge documentation files (specifically around search indexes, etc) but rustbuild was unaware of this, so an initial fix ended up destroying the sidebar and the search bar from the libstd docs. To solve this issue the method of documentation has been tweaked slightly in rustbuild. The build system will not use symlinks (or directory junctions on Windows) to generate all documentation into the same location initially. This'll rely on rustdoc's logic to weave together all the output and ensure that it ends up all consistent. Closes #38749 --- src/bootstrap/doc.rs | 63 +++++++++++++++--- src/bootstrap/lib.rs | 7 ++ src/bootstrap/step.rs | 2 +- src/bootstrap/util.rs | 139 +++++++++++++++++++++++++++++++++++++++ src/libproc_macro/lib.rs | 2 +- 5 files changed, 202 insertions(+), 11 deletions(-) diff --git a/src/bootstrap/doc.rs b/src/bootstrap/doc.rs index d19e5b1b88456..9c3f0ce62f349 100644 --- a/src/bootstrap/doc.rs +++ b/src/bootstrap/doc.rs @@ -19,10 +19,12 @@ use std::fs::{self, File}; use std::io::prelude::*; +use std::io; +use std::path::Path; use std::process::Command; use {Build, Compiler, Mode}; -use util::cp_r; +use util::{cp_r, symlink_dir}; use build_helper::up_to_date; /// Invoke `rustbook` as compiled in `stage` for `target` for the doc book @@ -141,7 +143,22 @@ pub fn std(build: &Build, stage: u32, target: &str) { .join(target).join("doc"); let rustdoc = build.rustdoc(&compiler); - build.clear_if_dirty(&out_dir, &rustdoc); + // Here what we're doing is creating a *symlink* (directory junction on + // Windows) to the final output location. This is not done as an + // optimization but rather for correctness. We've got three trees of + // documentation, one for std, one for test, and one for rustc. It's then + // our job to merge them all together. + // + // Unfortunately rustbuild doesn't know nearly as well how to merge doc + // trees as rustdoc does itself, so instead of actually having three + // separate trees we just have rustdoc output to the same location across + // all of them. + // + // This way rustdoc generates output directly into the output, and rustdoc + // will also directly handle merging. + let my_out = build.crate_doc_out(target); + build.clear_if_dirty(&my_out, &rustdoc); + t!(symlink_dir_force(&my_out, &out_dir)); let mut cargo = build.cargo(&compiler, Mode::Libstd, target, "doc"); cargo.arg("--manifest-path") @@ -166,7 +183,7 @@ pub fn std(build: &Build, stage: u32, target: &str) { build.run(&mut cargo); - cp_r(&out_dir, &out) + cp_r(&my_out, &out); } /// Compile all libtest documentation. @@ -187,13 +204,16 @@ pub fn test(build: &Build, stage: u32, target: &str) { .join(target).join("doc"); let rustdoc = build.rustdoc(&compiler); - build.clear_if_dirty(&out_dir, &rustdoc); + // See docs in std above for why we symlink + let my_out = build.crate_doc_out(target); + build.clear_if_dirty(&my_out, &rustdoc); + t!(symlink_dir_force(&my_out, &out_dir)); let mut cargo = build.cargo(&compiler, Mode::Libtest, target, "doc"); cargo.arg("--manifest-path") .arg(build.src.join("src/libtest/Cargo.toml")); build.run(&mut cargo); - cp_r(&out_dir, &out) + cp_r(&my_out, &out); } /// Generate all compiler documentation. @@ -213,15 +233,28 @@ pub fn rustc(build: &Build, stage: u32, target: &str) { let out_dir = build.stage_out(&compiler, Mode::Librustc) .join(target).join("doc"); let rustdoc = build.rustdoc(&compiler); - if !up_to_date(&rustdoc, &out_dir.join("rustc/index.html")) && out_dir.exists() { - t!(fs::remove_dir_all(&out_dir)); - } + + // See docs in std above for why we symlink + let my_out = build.crate_doc_out(target); + build.clear_if_dirty(&my_out, &rustdoc); + t!(symlink_dir_force(&my_out, &out_dir)); + let mut cargo = build.cargo(&compiler, Mode::Librustc, target, "doc"); cargo.arg("--manifest-path") .arg(build.src.join("src/rustc/Cargo.toml")) .arg("--features").arg(build.rustc_features()); + + // Like with libstd above if compiler docs aren't enabled then we're not + // documenting internal dependencies, so we have a whitelist. + if !build.config.compiler_docs { + cargo.arg("--no-deps"); + for krate in &["proc_macro"] { + cargo.arg("-p").arg(krate); + } + } + build.run(&mut cargo); - cp_r(&out_dir, &out) + cp_r(&my_out, &out); } /// Generates the HTML rendered error-index by running the @@ -240,3 +273,15 @@ pub fn error_index(build: &Build, target: &str) { build.run(&mut index); } + +fn symlink_dir_force(src: &Path, dst: &Path) -> io::Result<()> { + if let Ok(m) = fs::symlink_metadata(dst) { + if m.file_type().is_dir() { + try!(fs::remove_dir_all(dst)); + } else { + try!(fs::remove_file(dst)); + } + } + + symlink_dir(src, dst) +} diff --git a/src/bootstrap/lib.rs b/src/bootstrap/lib.rs index 98b68d870d375..5a5f36f1a4c9f 100644 --- a/src/bootstrap/lib.rs +++ b/src/bootstrap/lib.rs @@ -707,6 +707,13 @@ impl Build { self.out.join(target).join("doc") } + /// Output directory for all crate documentation for a target (temporary) + /// + /// The artifacts here are then copied into `doc_out` above. + fn crate_doc_out(&self, target: &str) -> PathBuf { + self.out.join(target).join("crate-docs") + } + /// Returns true if no custom `llvm-config` is set for the specified target. /// /// If no custom `llvm-config` was specified then Rust's llvm will be used. diff --git a/src/bootstrap/step.rs b/src/bootstrap/step.rs index a5c0d11d21985..c24a555280ba9 100644 --- a/src/bootstrap/step.rs +++ b/src/bootstrap/step.rs @@ -640,7 +640,7 @@ pub fn build_rules<'a>(build: &'a Build) -> Rules { rules.doc(&krate.doc_step, path) .dep(|s| s.name("librustc-link")) .host(true) - .default(default && build.config.compiler_docs) + .default(default && build.config.docs) .run(move |s| doc::rustc(build, s.stage, s.target)); } diff --git a/src/bootstrap/util.rs b/src/bootstrap/util.rs index 520514f5fc95a..be427b39c682f 100644 --- a/src/bootstrap/util.rs +++ b/src/bootstrap/util.rs @@ -16,6 +16,7 @@ use std::env; use std::ffi::OsString; use std::fs; +use std::io; use std::path::{Path, PathBuf}; use std::process::Command; use std::time::Instant; @@ -175,3 +176,141 @@ impl Drop for TimeIt { time.subsec_nanos() / 1_000_000); } } + +/// Symlinks two directories, using junctions on Windows and normal symlinks on +/// Unix. +pub fn symlink_dir(src: &Path, dest: &Path) -> io::Result<()> { + let _ = fs::remove_dir(dest); + return symlink_dir_inner(src, dest); + + #[cfg(not(windows))] + fn symlink_dir_inner(src: &Path, dest: &Path) -> io::Result<()> { + use std::os::unix::fs; + fs::symlink(src, dest) + } + + // Creating a directory junction on windows involves dealing with reparse + // points and the DeviceIoControl function, and this code is a skeleton of + // what can be found here: + // + // http://www.flexhex.com/docs/articles/hard-links.phtml + // + // Copied from std + #[cfg(windows)] + #[allow(bad_style)] + fn symlink_dir_inner(target: &Path, junction: &Path) -> io::Result<()> { + use std::ptr; + use std::ffi::OsStr; + use std::os::windows::ffi::OsStrExt; + + const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: usize = 16 * 1024; + const GENERIC_WRITE: DWORD = 0x40000000; + const OPEN_EXISTING: DWORD = 3; + const FILE_FLAG_OPEN_REPARSE_POINT: DWORD = 0x00200000; + const FILE_FLAG_BACKUP_SEMANTICS: DWORD = 0x02000000; + const FSCTL_SET_REPARSE_POINT: DWORD = 0x900a4; + const IO_REPARSE_TAG_MOUNT_POINT: DWORD = 0xa0000003; + const FILE_SHARE_DELETE: DWORD = 0x4; + const FILE_SHARE_READ: DWORD = 0x1; + const FILE_SHARE_WRITE: DWORD = 0x2; + + type BOOL = i32; + type DWORD = u32; + type HANDLE = *mut u8; + type LPCWSTR = *const u16; + type LPDWORD = *mut DWORD; + type LPOVERLAPPED = *mut u8; + type LPSECURITY_ATTRIBUTES = *mut u8; + type LPVOID = *mut u8; + type WCHAR = u16; + type WORD = u16; + + #[repr(C)] + struct REPARSE_MOUNTPOINT_DATA_BUFFER { + ReparseTag: DWORD, + ReparseDataLength: DWORD, + Reserved: WORD, + ReparseTargetLength: WORD, + ReparseTargetMaximumLength: WORD, + Reserved1: WORD, + ReparseTarget: WCHAR, + } + + extern "system" { + fn CreateFileW(lpFileName: LPCWSTR, + dwDesiredAccess: DWORD, + dwShareMode: DWORD, + lpSecurityAttributes: LPSECURITY_ATTRIBUTES, + dwCreationDisposition: DWORD, + dwFlagsAndAttributes: DWORD, + hTemplateFile: HANDLE) + -> HANDLE; + fn DeviceIoControl(hDevice: HANDLE, + dwIoControlCode: DWORD, + lpInBuffer: LPVOID, + nInBufferSize: DWORD, + lpOutBuffer: LPVOID, + nOutBufferSize: DWORD, + lpBytesReturned: LPDWORD, + lpOverlapped: LPOVERLAPPED) -> BOOL; + } + + fn to_u16s>(s: S) -> io::Result> { + Ok(s.as_ref().encode_wide().chain(Some(0)).collect()) + } + + // We're using low-level APIs to create the junction, and these are more + // picky about paths. For example, forward slashes cannot be used as a + // path separator, so we should try to canonicalize the path first. + let target = try!(fs::canonicalize(target)); + + try!(fs::create_dir(junction)); + + let path = try!(to_u16s(junction)); + + unsafe { + let h = CreateFileW(path.as_ptr(), + GENERIC_WRITE, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + 0 as *mut _, + OPEN_EXISTING, + FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, + ptr::null_mut()); + + let mut data = [0u8; MAXIMUM_REPARSE_DATA_BUFFER_SIZE]; + let mut db = data.as_mut_ptr() + as *mut REPARSE_MOUNTPOINT_DATA_BUFFER; + let buf = &mut (*db).ReparseTarget as *mut _; + let mut i = 0; + // FIXME: this conversion is very hacky + let v = br"\??\"; + let v = v.iter().map(|x| *x as u16); + for c in v.chain(target.as_os_str().encode_wide().skip(4)) { + *buf.offset(i) = c; + i += 1; + } + *buf.offset(i) = 0; + i += 1; + (*db).ReparseTag = IO_REPARSE_TAG_MOUNT_POINT; + (*db).ReparseTargetMaximumLength = (i * 2) as WORD; + (*db).ReparseTargetLength = ((i - 1) * 2) as WORD; + (*db).ReparseDataLength = + (*db).ReparseTargetLength as DWORD + 12; + + let mut ret = 0; + let res = DeviceIoControl(h as *mut _, + FSCTL_SET_REPARSE_POINT, + data.as_ptr() as *mut _, + (*db).ReparseDataLength + 8, + ptr::null_mut(), 0, + &mut ret, + ptr::null_mut()); + + if res == 0 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } + } + } +} diff --git a/src/libproc_macro/lib.rs b/src/libproc_macro/lib.rs index 8d7fe655c23b2..0d2a467b57702 100644 --- a/src/libproc_macro/lib.rs +++ b/src/libproc_macro/lib.rs @@ -21,7 +21,7 @@ //! This functionality is intended to be expanded over time as more surface //! area for macro authors is stabilized. //! -//! See [the book](../../book/procedural-macros.html) for more. +//! See [the book](../book/procedural-macros.html) for more. #![crate_name = "proc_macro"] #![stable(feature = "proc_macro_lib", since = "1.15.0")] From 4f424b3c5a3e47732ca39cc14466b0e0d21f488a Mon Sep 17 00:00:00 2001 From: Taylor Cramer Date: Mon, 6 Mar 2017 18:16:57 -0800 Subject: [PATCH 09/15] Add compile-fail tests for catch expr in match or condition --- src/test/compile-fail/catch-in-match.rs | 15 +++++++++++++++ src/test/compile-fail/catch-in-while.rs | 15 +++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 src/test/compile-fail/catch-in-match.rs create mode 100644 src/test/compile-fail/catch-in-while.rs diff --git a/src/test/compile-fail/catch-in-match.rs b/src/test/compile-fail/catch-in-match.rs new file mode 100644 index 0000000000000..9f9968e81242a --- /dev/null +++ b/src/test/compile-fail/catch-in-match.rs @@ -0,0 +1,15 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(catch_expr)] + +fn main() { + match do catch { false } { _ => {} } //~ ERROR expected expression, found reserved keyword `do` +} diff --git a/src/test/compile-fail/catch-in-while.rs b/src/test/compile-fail/catch-in-while.rs new file mode 100644 index 0000000000000..cb8613ee60b42 --- /dev/null +++ b/src/test/compile-fail/catch-in-while.rs @@ -0,0 +1,15 @@ +// Copyright 2017 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![feature(catch_expr)] + +fn main() { + while do catch { false } {} //~ ERROR expected expression, found reserved keyword `do` +} From 9efee169583472acbc0f3acbc36c57fbe44aba0a Mon Sep 17 00:00:00 2001 From: Oliver Schneider Date: Tue, 7 Mar 2017 12:51:09 +0100 Subject: [PATCH 10/15] Allow lints to check Bodys directly --- src/librustc/lint/context.rs | 6 ++++++ src/librustc/lint/mod.rs | 2 ++ 2 files changed, 8 insertions(+) diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index 32bc81e947037..9279f24a57ab3 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -806,6 +806,12 @@ impl<'a, 'tcx> hir_visit::Visitor<'tcx> for LateContext<'a, 'tcx> { self.tables = old_tables; } + fn visit_body(&mut self, body: &'tcx hir::Body) { + run_lints!(self, check_body, late_passes, body); + hir_visit::walk_body(self, body); + run_lints!(self, check_body_post, late_passes, body); + } + fn visit_item(&mut self, it: &'tcx hir::Item) { self.with_lint_attrs(&it.attrs, |cx| { run_lints!(cx, check_item, late_passes, it); diff --git a/src/librustc/lint/mod.rs b/src/librustc/lint/mod.rs index e9f603db15d62..e81d09773701c 100644 --- a/src/librustc/lint/mod.rs +++ b/src/librustc/lint/mod.rs @@ -133,6 +133,8 @@ pub trait LintPass { // FIXME: eliminate the duplication with `Visitor`. But this also // contains a few lint-specific methods with no equivalent in `Visitor`. pub trait LateLintPass<'a, 'tcx>: LintPass { + fn check_body(&mut self, _: &LateContext, _: &'tcx hir::Body) { } + fn check_body_post(&mut self, _: &LateContext, _: &'tcx hir::Body) { } fn check_name(&mut self, _: &LateContext, _: Span, _: ast::Name) { } fn check_crate(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Crate) { } fn check_crate_post(&mut self, _: &LateContext<'a, 'tcx>, _: &'tcx hir::Crate) { } From c51a39de7c8cb8e138f07d1e0f4798068cad251d Mon Sep 17 00:00:00 2001 From: Joshua Horwitz Date: Tue, 7 Mar 2017 23:04:59 -0500 Subject: [PATCH 11/15] Removed RustFMT changes --- src/libstd/process.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/libstd/process.rs b/src/libstd/process.rs index f846ef3e69e09..e5ce30c5539fc 100644 --- a/src/libstd/process.rs +++ b/src/libstd/process.rs @@ -343,6 +343,23 @@ impl Command { /// Add an argument to pass to the program. /// + /// Only one argument can be passed per use. So instead of: + /// + /// ```ignore + /// .arg("-C /path/to/repo") + /// ``` + /// + /// usage would be: + /// + /// ```ignore + /// .arg("-C") + /// .arg("/path/to/repo") + /// ``` + /// + /// To pass multiple arguments see [`args`]. + /// + /// [`args`]: #method.args + /// /// # Examples /// /// Basic usage: @@ -364,6 +381,10 @@ impl Command { /// Add multiple arguments to pass to the program. /// + /// To pass a single argument see [`arg`]. + /// + /// [`arg`]: #method.arg + /// /// # Examples /// /// Basic usage: From 4eeede3e0f2496994b4c0bbaa59927066d642807 Mon Sep 17 00:00:00 2001 From: Tim Neumann Date: Sat, 4 Mar 2017 14:59:49 +0100 Subject: [PATCH 12/15] fix emscripten test detection --- src/bootstrap/check.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/bootstrap/check.rs b/src/bootstrap/check.rs index dfe96b51799c0..68b3623a53f25 100644 --- a/src/bootstrap/check.rs +++ b/src/bootstrap/check.rs @@ -550,7 +550,7 @@ fn find_tests(dir: &Path, let filename = e.file_name().into_string().unwrap(); if (target.contains("windows") && filename.ends_with(".exe")) || (!target.contains("windows") && !filename.contains(".")) || - (target.contains("emscripten") && filename.contains(".js")){ + (target.contains("emscripten") && filename.ends_with(".js")) { dst.push(e.path()); } } From 57c989caa1db0b000ff5e9fd2ebb0e6557a3cf30 Mon Sep 17 00:00:00 2001 From: Jake Goulding Date: Sat, 4 Mar 2017 10:07:55 -0500 Subject: [PATCH 13/15] Fix botched member variable rename --- src/tools/build-manifest/src/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tools/build-manifest/src/main.rs b/src/tools/build-manifest/src/main.rs index ceefcc9e0ec46..cbafa9e0bd272 100644 --- a/src/tools/build-manifest/src/main.rs +++ b/src/tools/build-manifest/src/main.rs @@ -218,7 +218,7 @@ impl Builder { self.package("rust-docs", &mut manifest.pkg, TARGETS); self.package("rust-src", &mut manifest.pkg, &["*"]); - if self.channel == "nightly" { + if self.rust_release == "nightly" { self.package("rust-analysis", &mut manifest.pkg, TARGETS); } @@ -271,7 +271,7 @@ impl Builder { target: target.to_string(), }); } - if self.channel == "nightly" { + if self.rust_release == "nightly" { extensions.push(Component { pkg: "rust-analysis".to_string(), target: target.to_string(), From 3e2390ff9cf95d9b35474cfb190b0c88a2b268c0 Mon Sep 17 00:00:00 2001 From: Jake Goulding Date: Thu, 2 Mar 2017 23:39:15 -0500 Subject: [PATCH 14/15] Restore creating the channel-rust-$channel-date.txt files --- src/tools/build-manifest/src/main.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/tools/build-manifest/src/main.rs b/src/tools/build-manifest/src/main.rs index cbafa9e0bd272..b9c8a84844465 100644 --- a/src/tools/build-manifest/src/main.rs +++ b/src/tools/build-manifest/src/main.rs @@ -183,15 +183,19 @@ impl Builder { let mut manifest = BTreeMap::new(); manifest.insert("manifest-version".to_string(), toml::Value::String(manifest_version)); - manifest.insert("date".to_string(), toml::Value::String(date)); + manifest.insert("date".to_string(), toml::Value::String(date.clone())); manifest.insert("pkg".to_string(), toml::encode(&pkg)); let manifest = toml::Value::Table(manifest).to_string(); let filename = format!("channel-rust-{}.toml", self.rust_release); self.write_manifest(&manifest, &filename); + let filename = format!("channel-rust-{}-date.txt", self.rust_release); + self.write_date_stamp(&date, &filename); + if self.rust_release != "beta" && self.rust_release != "nightly" { self.write_manifest(&manifest, "channel-rust-stable.toml"); + self.write_date_stamp(&date, "channel-rust-stable-date.txt"); } } @@ -411,4 +415,11 @@ impl Builder { self.hash(&dst); self.sign(&dst); } + + fn write_date_stamp(&self, date: &str, name: &str) { + let dst = self.output.join(name); + t!(t!(File::create(&dst)).write_all(date.as_bytes())); + self.hash(&dst); + self.sign(&dst); + } } From 58ff4f67e3a1d099d3c4cb8ccb554ee9fd0a16cd Mon Sep 17 00:00:00 2001 From: Robin Kruppe Date: Sun, 5 Mar 2017 16:11:11 +0100 Subject: [PATCH 15/15] rustbuild: expose LLVM_PARALLEL_LINK_JOBS This allows limiting the number of linker jobs to avoid swapping when linking LLVM with debug info. --- src/bootstrap/config.rs | 3 +++ src/bootstrap/config.toml.example | 8 ++++++++ src/bootstrap/native.rs | 6 ++++++ 3 files changed, 17 insertions(+) diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index 438ce6103d624..87c35e0502ce6 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -59,6 +59,7 @@ pub struct Config { pub llvm_static_stdcpp: bool, pub llvm_link_shared: bool, pub llvm_targets: Option, + pub llvm_link_jobs: Option, // rust codegen options pub rust_optimize: bool, @@ -179,6 +180,7 @@ struct Llvm { version_check: Option, static_libstdcpp: Option, targets: Option, + link_jobs: Option, } #[derive(RustcDecodable, Default, Clone)] @@ -333,6 +335,7 @@ impl Config { set(&mut config.llvm_version_check, llvm.version_check); set(&mut config.llvm_static_stdcpp, llvm.static_libstdcpp); config.llvm_targets = llvm.targets.clone(); + config.llvm_link_jobs = llvm.link_jobs; } if let Some(ref rust) = toml.rust { diff --git a/src/bootstrap/config.toml.example b/src/bootstrap/config.toml.example index 30763e38a336f..776bd729119e2 100644 --- a/src/bootstrap/config.toml.example +++ b/src/bootstrap/config.toml.example @@ -53,6 +53,14 @@ # Rust team and file an issue if you need assistance in porting! #targets = "X86;ARM;AArch64;Mips;PowerPC;SystemZ;JSBackend;MSP430;Sparc;NVPTX" +# Cap the number of parallel linker invocations when compiling LLVM. +# This can be useful when building LLVM with debug info, which significantly +# increases the size of binaries and consequently the memory required by +# each linker process. +# If absent or 0, linker invocations are treated like any other job and +# controlled by rustbuild's -j parameter. +#link-jobs = 0 + # ============================================================================= # General build configuration options # ============================================================================= diff --git a/src/bootstrap/native.rs b/src/bootstrap/native.rs index 483f45fdd6218..c13235b9c7680 100644 --- a/src/bootstrap/native.rs +++ b/src/bootstrap/native.rs @@ -115,6 +115,12 @@ pub fn llvm(build: &Build, target: &str) { cfg.define("LLVM_BUILD_32_BITS", "ON"); } + if let Some(num_linkers) = build.config.llvm_link_jobs { + if num_linkers > 0 { + cfg.define("LLVM_PARALLEL_LINK_JOBS", num_linkers.to_string()); + } + } + // http://llvm.org/docs/HowToCrossCompileLLVM.html if target != build.config.build { // FIXME: if the llvm root for the build triple is overridden then we