]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/native_libs.rs
Auto merge of #46696 - kennytm:rollup, r=kennytm
[rust.git] / src / librustc_metadata / native_libs.rs
1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use rustc::hir::itemlikevisit::ItemLikeVisitor;
12 use rustc::hir;
13 use rustc::middle::cstore::{self, NativeLibrary};
14 use rustc::session::Session;
15 use rustc::ty::TyCtxt;
16 use rustc::util::nodemap::FxHashSet;
17 use syntax::abi::Abi;
18 use syntax::attr;
19 use syntax::codemap::Span;
20 use syntax::feature_gate::{self, GateIssue};
21 use syntax::symbol::Symbol;
22
23 pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Vec<NativeLibrary> {
24     let mut collector = Collector {
25         tcx,
26         libs: Vec::new(),
27     };
28     tcx.hir.krate().visit_all_item_likes(&mut collector);
29     collector.process_command_line();
30     return collector.libs
31 }
32
33 pub fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
34     match lib.cfg {
35         Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
36         None => true,
37     }
38 }
39
40 struct Collector<'a, 'tcx: 'a> {
41     tcx: TyCtxt<'a, 'tcx, 'tcx>,
42     libs: Vec<NativeLibrary>,
43 }
44
45 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for Collector<'a, 'tcx> {
46     fn visit_item(&mut self, it: &'tcx hir::Item) {
47         let fm = match it.node {
48             hir::ItemForeignMod(ref fm) => fm,
49             _ => return,
50         };
51
52         if fm.abi == Abi::Rust ||
53             fm.abi == Abi::RustIntrinsic ||
54             fm.abi == Abi::PlatformIntrinsic {
55             return
56         }
57
58         // Process all of the #[link(..)]-style arguments
59         for m in it.attrs.iter().filter(|a| a.check_name("link")) {
60             let items = match m.meta_item_list() {
61                 Some(item) => item,
62                 None => continue,
63             };
64             let kind = items.iter().find(|k| {
65                 k.check_name("kind")
66             }).and_then(|a| a.value_str()).map(Symbol::as_str);
67             let kind = match kind.as_ref().map(|s| &s[..]) {
68                 Some("static") => cstore::NativeStatic,
69                 Some("static-nobundle") => cstore::NativeStaticNobundle,
70                 Some("dylib") => cstore::NativeUnknown,
71                 Some("framework") => cstore::NativeFramework,
72                 Some(k) => {
73                     struct_span_err!(self.tcx.sess, m.span, E0458,
74                               "unknown kind: `{}`", k)
75                         .span_label(m.span, "unknown kind").emit();
76                     cstore::NativeUnknown
77                 }
78                 None => cstore::NativeUnknown
79             };
80             let n = items.iter().find(|n| {
81                 n.check_name("name")
82             }).and_then(|a| a.value_str());
83             let n = match n {
84                 Some(n) => n,
85                 None => {
86                     struct_span_err!(self.tcx.sess, m.span, E0459,
87                                      "#[link(...)] specified without `name = \"foo\"`")
88                         .span_label(m.span, "missing `name` argument").emit();
89                     Symbol::intern("foo")
90                 }
91             };
92             let cfg = items.iter().find(|k| {
93                 k.check_name("cfg")
94             }).and_then(|a| a.meta_item_list());
95             let cfg = cfg.map(|list| {
96                 list[0].meta_item().unwrap().clone()
97             });
98             let foreign_items = fm.items.iter()
99                 .map(|it| self.tcx.hir.local_def_id(it.id))
100                 .collect();
101             let lib = NativeLibrary {
102                 name: n,
103                 kind,
104                 cfg,
105                 foreign_items,
106             };
107             self.register_native_lib(Some(m.span), lib);
108         }
109     }
110
111     fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem) {}
112     fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem) {}
113 }
114
115 impl<'a, 'tcx> Collector<'a, 'tcx> {
116     fn register_native_lib(&mut self, span: Option<Span>, lib: NativeLibrary) {
117         if lib.name.as_str().is_empty() {
118             match span {
119                 Some(span) => {
120                     struct_span_err!(self.tcx.sess, span, E0454,
121                                      "#[link(name = \"\")] given with empty name")
122                         .span_label(span, "empty name given")
123                         .emit();
124                 }
125                 None => {
126                     self.tcx.sess.err("empty library name given via `-l`");
127                 }
128             }
129             return
130         }
131         let is_osx = self.tcx.sess.target.target.options.is_like_osx;
132         if lib.kind == cstore::NativeFramework && !is_osx {
133             let msg = "native frameworks are only available on macOS targets";
134             match span {
135                 Some(span) => span_err!(self.tcx.sess, span, E0455, "{}", msg),
136                 None => self.tcx.sess.err(msg),
137             }
138         }
139         if lib.cfg.is_some() && !self.tcx.sess.features.borrow().link_cfg {
140             feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
141                                            "link_cfg",
142                                            span.unwrap(),
143                                            GateIssue::Language,
144                                            "is feature gated");
145         }
146         if lib.kind == cstore::NativeStaticNobundle &&
147            !self.tcx.sess.features.borrow().static_nobundle {
148             feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
149                                            "static_nobundle",
150                                            span.unwrap(),
151                                            GateIssue::Language,
152                                            "kind=\"static-nobundle\" is feature gated");
153         }
154         self.libs.push(lib);
155     }
156
157     // Process libs passed on the command line
158     fn process_command_line(&mut self) {
159         // First, check for errors
160         let mut renames = FxHashSet();
161         for &(ref name, ref new_name, _) in &self.tcx.sess.opts.libs {
162             if let &Some(ref new_name) = new_name {
163                 if new_name.is_empty() {
164                     self.tcx.sess.err(
165                         &format!("an empty renaming target was specified for library `{}`",name));
166                 } else if !self.libs.iter().any(|lib| lib.name == name as &str) {
167                     self.tcx.sess.err(&format!("renaming of the library `{}` was specified, \
168                                                 however this crate contains no #[link(...)] \
169                                                 attributes referencing this library.", name));
170                 } else if renames.contains(name) {
171                     self.tcx.sess.err(&format!("multiple renamings were \
172                                                 specified for library `{}` .",
173                                                name));
174                 } else {
175                     renames.insert(name);
176                 }
177             }
178         }
179
180         // Update kind and, optionally, the name of all native libaries
181         // (there may be more than one) with the specified name.
182         for &(ref name, ref new_name, kind) in &self.tcx.sess.opts.libs {
183             let mut found = false;
184             for lib in self.libs.iter_mut() {
185                 if lib.name == name as &str {
186                     let mut changed = false;
187                     if let Some(k) = kind {
188                         lib.kind = k;
189                         changed = true;
190                     }
191                     if let &Some(ref new_name) = new_name {
192                         lib.name = Symbol::intern(new_name);
193                         changed = true;
194                     }
195                     if !changed {
196                         let msg = format!("redundant linker flag specified for \
197                                            library `{}`", name);
198                         self.tcx.sess.warn(&msg);
199                     }
200
201                     found = true;
202                 }
203             }
204             if !found {
205                 // Add if not found
206                 let new_name = new_name.as_ref().map(|s| &**s); // &Option<String> -> Option<&str>
207                 let lib = NativeLibrary {
208                     name: Symbol::intern(new_name.unwrap_or(name)),
209                     kind: if let Some(k) = kind { k } else { cstore::NativeUnknown },
210                     cfg: None,
211                     foreign_items: Vec::new(),
212                 };
213                 self.register_native_lib(None, lib);
214             }
215         }
216     }
217 }