]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/native_libs.rs
Auto merge of #55014 - ljedrz:lazyboye_unwraps, r=matthewjasper
[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 rustc_target::spec::abi::Abi;
18 use syntax::attr;
19 use syntax::source_map::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::ItemKind::ForeignMod(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 mut lib = NativeLibrary {
65                 name: None,
66                 kind: cstore::NativeUnknown,
67                 cfg: None,
68                 foreign_module: Some(self.tcx.hir.local_def_id(it.id)),
69                 wasm_import_module: None,
70             };
71             let mut kind_specified = false;
72
73             for item in items.iter() {
74                 if item.check_name("kind") {
75                     kind_specified = true;
76                     let kind = match item.value_str() {
77                         Some(name) => name,
78                         None => continue, // skip like historical compilers
79                     };
80                     lib.kind = match &kind.as_str()[..] {
81                         "static" => cstore::NativeStatic,
82                         "static-nobundle" => cstore::NativeStaticNobundle,
83                         "dylib" => cstore::NativeUnknown,
84                         "framework" => cstore::NativeFramework,
85                         k => {
86                             struct_span_err!(self.tcx.sess, m.span, E0458,
87                                       "unknown kind: `{}`", k)
88                                 .span_label(item.span, "unknown kind").emit();
89                             cstore::NativeUnknown
90                         }
91                     };
92                 } else if item.check_name("name") {
93                     lib.name = item.value_str();
94                 } else if item.check_name("cfg") {
95                     let cfg = match item.meta_item_list() {
96                         Some(list) => list,
97                         None => continue, // skip like historical compilers
98                     };
99                     if cfg.is_empty() {
100                         self.tcx.sess.span_err(
101                             item.span(),
102                             "`cfg()` must have an argument",
103                         );
104                     } else if let cfg @ Some(..) = cfg[0].meta_item() {
105                         lib.cfg = cfg.cloned();
106                     } else {
107                         self.tcx.sess.span_err(cfg[0].span(), "invalid argument for `cfg(..)`");
108                     }
109                 } else if item.check_name("wasm_import_module") {
110                     match item.value_str() {
111                         Some(s) => lib.wasm_import_module = Some(s),
112                         None => {
113                             let msg = "must be of the form #[link(wasm_import_module = \"...\")]";
114                             self.tcx.sess.span_err(item.span(), msg);
115                         }
116                     }
117                 } else {
118                     // currently, like past compilers, ignore unknown
119                     // directives here.
120                 }
121             }
122
123             // In general we require #[link(name = "...")] but we allow
124             // #[link(wasm_import_module = "...")] without the `name`.
125             let requires_name = kind_specified || lib.wasm_import_module.is_none();
126             if lib.name.is_none() && requires_name {
127                 struct_span_err!(self.tcx.sess, m.span, E0459,
128                                  "#[link(...)] specified without \
129                                   `name = \"foo\"`")
130                     .span_label(m.span, "missing `name` argument")
131                     .emit();
132             }
133             self.register_native_lib(Some(m.span), lib);
134         }
135     }
136
137     fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem) {}
138     fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem) {}
139 }
140
141 impl<'a, 'tcx> Collector<'a, 'tcx> {
142     fn register_native_lib(&mut self, span: Option<Span>, lib: NativeLibrary) {
143         if lib.name.as_ref().map(|s| s.as_str().is_empty()).unwrap_or(false) {
144             match span {
145                 Some(span) => {
146                     struct_span_err!(self.tcx.sess, span, E0454,
147                                      "#[link(name = \"\")] given with empty name")
148                         .span_label(span, "empty name given")
149                         .emit();
150                 }
151                 None => {
152                     self.tcx.sess.err("empty library name given via `-l`");
153                 }
154             }
155             return
156         }
157         let is_osx = self.tcx.sess.target.target.options.is_like_osx;
158         if lib.kind == cstore::NativeFramework && !is_osx {
159             let msg = "native frameworks are only available on macOS targets";
160             match span {
161                 Some(span) => span_err!(self.tcx.sess, span, E0455, "{}", msg),
162                 None => self.tcx.sess.err(msg),
163             }
164         }
165         if lib.cfg.is_some() && !self.tcx.features().link_cfg {
166             feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
167                                            "link_cfg",
168                                            span.unwrap(),
169                                            GateIssue::Language,
170                                            "is feature gated");
171         }
172         if lib.kind == cstore::NativeStaticNobundle &&
173            !self.tcx.features().static_nobundle {
174             feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
175                                            "static_nobundle",
176                                            span.unwrap(),
177                                            GateIssue::Language,
178                                            "kind=\"static-nobundle\" is feature gated");
179         }
180         self.libs.push(lib);
181     }
182
183     // Process libs passed on the command line
184     fn process_command_line(&mut self) {
185         // First, check for errors
186         let mut renames = FxHashSet::default();
187         for &(ref name, ref new_name, _) in &self.tcx.sess.opts.libs {
188             if let &Some(ref new_name) = new_name {
189                 let any_duplicate = self.libs
190                     .iter()
191                     .filter_map(|lib| lib.name.as_ref())
192                     .any(|n| n == name);
193                 if new_name.is_empty() {
194                     self.tcx.sess.err(
195                         &format!("an empty renaming target was specified for library `{}`",name));
196                 } else if !any_duplicate {
197                     self.tcx.sess.err(&format!("renaming of the library `{}` was specified, \
198                                                 however this crate contains no #[link(...)] \
199                                                 attributes referencing this library.", name));
200                 } else if renames.contains(name) {
201                     self.tcx.sess.err(&format!("multiple renamings were \
202                                                 specified for library `{}` .",
203                                                name));
204                 } else {
205                     renames.insert(name);
206                 }
207             }
208         }
209
210         // Update kind and, optionally, the name of all native libraries
211         // (there may be more than one) with the specified name.
212         for &(ref name, ref new_name, kind) in &self.tcx.sess.opts.libs {
213             let mut found = false;
214             for lib in self.libs.iter_mut() {
215                 let lib_name = match lib.name {
216                     Some(n) => n,
217                     None => continue,
218                 };
219                 if lib_name == name as &str {
220                     let mut changed = false;
221                     if let Some(k) = kind {
222                         lib.kind = k;
223                         changed = true;
224                     }
225                     if let &Some(ref new_name) = new_name {
226                         lib.name = Some(Symbol::intern(new_name));
227                         changed = true;
228                     }
229                     if !changed {
230                         let msg = format!("redundant linker flag specified for \
231                                            library `{}`", name);
232                         self.tcx.sess.warn(&msg);
233                     }
234
235                     found = true;
236                 }
237             }
238             if !found {
239                 // Add if not found
240                 let new_name = new_name.as_ref().map(|s| &**s); // &Option<String> -> Option<&str>
241                 let lib = NativeLibrary {
242                     name: Some(Symbol::intern(new_name.unwrap_or(name))),
243                     kind: if let Some(k) = kind { k } else { cstore::NativeUnknown },
244                     cfg: None,
245                     foreign_module: None,
246                     wasm_import_module: None,
247                 };
248                 self.register_native_lib(None, lib);
249             }
250         }
251     }
252 }