]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/native_libs.rs
Auto merge of #67808 - Marwes:projection_normalization_recurse, r=nikomatsakis
[rust.git] / src / librustc_metadata / native_libs.rs
1 use rustc::hir;
2 use rustc::hir::itemlikevisit::ItemLikeVisitor;
3 use rustc::middle::cstore::{self, NativeLibrary};
4 use rustc::session::Session;
5 use rustc::ty::TyCtxt;
6 use rustc_data_structures::fx::FxHashSet;
7 use rustc_span::source_map::Span;
8 use rustc_span::symbol::{kw, sym, Symbol};
9 use rustc_target::spec::abi::Abi;
10 use syntax::attr;
11 use syntax::feature_gate::feature_err;
12 use syntax::{span_err, struct_span_err};
13
14 use rustc_error_codes::*;
15
16 crate fn collect(tcx: TyCtxt<'_>) -> Vec<NativeLibrary> {
17     let mut collector = Collector { tcx, libs: Vec::new() };
18     tcx.hir().krate().visit_all_item_likes(&mut collector);
19     collector.process_command_line();
20     return collector.libs;
21 }
22
23 crate fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
24     match lib.cfg {
25         Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
26         None => true,
27     }
28 }
29
30 struct Collector<'tcx> {
31     tcx: TyCtxt<'tcx>,
32     libs: Vec<NativeLibrary>,
33 }
34
35 impl ItemLikeVisitor<'tcx> for Collector<'tcx> {
36     fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) {
37         let fm = match it.kind {
38             hir::ItemKind::ForeignMod(ref fm) => fm,
39             _ => return,
40         };
41
42         if fm.abi == Abi::Rust || fm.abi == Abi::RustIntrinsic || fm.abi == Abi::PlatformIntrinsic {
43             return;
44         }
45
46         // Process all of the #[link(..)]-style arguments
47         for m in it.attrs.iter().filter(|a| a.check_name(sym::link)) {
48             let items = match m.meta_item_list() {
49                 Some(item) => item,
50                 None => continue,
51             };
52             let mut lib = NativeLibrary {
53                 name: None,
54                 kind: cstore::NativeUnknown,
55                 cfg: None,
56                 foreign_module: Some(self.tcx.hir().local_def_id(it.hir_id)),
57                 wasm_import_module: None,
58             };
59             let mut kind_specified = false;
60
61             for item in items.iter() {
62                 if item.check_name(sym::kind) {
63                     kind_specified = true;
64                     let kind = match item.value_str() {
65                         Some(name) => name,
66                         None => continue, // skip like historical compilers
67                     };
68                     lib.kind = match &*kind.as_str() {
69                         "static" => cstore::NativeStatic,
70                         "static-nobundle" => cstore::NativeStaticNobundle,
71                         "dylib" => cstore::NativeUnknown,
72                         "framework" => cstore::NativeFramework,
73                         "raw-dylib" => cstore::NativeRawDylib,
74                         k => {
75                             struct_span_err!(
76                                 self.tcx.sess,
77                                 item.span(),
78                                 E0458,
79                                 "unknown kind: `{}`",
80                                 k
81                             )
82                             .span_label(item.span(), "unknown kind")
83                             .span_label(m.span, "")
84                             .emit();
85                             cstore::NativeUnknown
86                         }
87                     };
88                 } else if item.check_name(sym::name) {
89                     lib.name = item.value_str();
90                 } else if item.check_name(sym::cfg) {
91                     let cfg = match item.meta_item_list() {
92                         Some(list) => list,
93                         None => continue, // skip like historical compilers
94                     };
95                     if cfg.is_empty() {
96                         self.tcx.sess.span_err(item.span(), "`cfg()` must have an argument");
97                     } else if let cfg @ Some(..) = cfg[0].meta_item() {
98                         lib.cfg = cfg.cloned();
99                     } else {
100                         self.tcx.sess.span_err(cfg[0].span(), "invalid argument for `cfg(..)`");
101                     }
102                 } else if item.check_name(sym::wasm_import_module) {
103                     match item.value_str() {
104                         Some(s) => lib.wasm_import_module = Some(s),
105                         None => {
106                             let msg = "must be of the form `#[link(wasm_import_module = \"...\")]`";
107                             self.tcx.sess.span_err(item.span(), msg);
108                         }
109                     }
110                 } else {
111                     // currently, like past compilers, ignore unknown
112                     // directives here.
113                 }
114             }
115
116             // In general we require #[link(name = "...")] but we allow
117             // #[link(wasm_import_module = "...")] without the `name`.
118             let requires_name = kind_specified || lib.wasm_import_module.is_none();
119             if lib.name.is_none() && requires_name {
120                 struct_span_err!(
121                     self.tcx.sess,
122                     m.span,
123                     E0459,
124                     "`#[link(...)]` specified without \
125                                   `name = \"foo\"`"
126                 )
127                 .span_label(m.span, "missing `name` argument")
128                 .emit();
129             }
130             self.register_native_lib(Some(m.span), lib);
131         }
132     }
133
134     fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem<'tcx>) {}
135     fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem<'tcx>) {}
136 }
137
138 impl Collector<'tcx> {
139     fn register_native_lib(&mut self, span: Option<Span>, lib: NativeLibrary) {
140         if lib.name.as_ref().map(|&s| s == kw::Invalid).unwrap_or(false) {
141             match span {
142                 Some(span) => {
143                     struct_span_err!(
144                         self.tcx.sess,
145                         span,
146                         E0454,
147                         "`#[link(name = \"\")]` given with empty name"
148                     )
149                     .span_label(span, "empty name given")
150                     .emit();
151                 }
152                 None => {
153                     self.tcx.sess.err("empty library name given via `-l`");
154                 }
155             }
156             return;
157         }
158         let is_osx = self.tcx.sess.target.target.options.is_like_osx;
159         if lib.kind == cstore::NativeFramework && !is_osx {
160             let msg = "native frameworks are only available on macOS targets";
161             match span {
162                 Some(span) => span_err!(self.tcx.sess, span, E0455, "{}", msg),
163                 None => self.tcx.sess.err(msg),
164             }
165         }
166         if lib.cfg.is_some() && !self.tcx.features().link_cfg {
167             feature_err(&self.tcx.sess.parse_sess, sym::link_cfg, span.unwrap(), "is unstable")
168                 .emit();
169         }
170         if lib.kind == cstore::NativeStaticNobundle && !self.tcx.features().static_nobundle {
171             feature_err(
172                 &self.tcx.sess.parse_sess,
173                 sym::static_nobundle,
174                 span.unwrap_or_else(|| rustc_span::DUMMY_SP),
175                 "kind=\"static-nobundle\" is unstable",
176             )
177             .emit();
178         }
179         if lib.kind == cstore::NativeRawDylib && !self.tcx.features().raw_dylib {
180             feature_err(
181                 &self.tcx.sess.parse_sess,
182                 sym::raw_dylib,
183                 span.unwrap_or_else(|| rustc_span::DUMMY_SP),
184                 "kind=\"raw-dylib\" is unstable",
185             )
186             .emit();
187         }
188         self.libs.push(lib);
189     }
190
191     // Process libs passed on the command line
192     fn process_command_line(&mut self) {
193         // First, check for errors
194         let mut renames = FxHashSet::default();
195         for &(ref name, ref new_name, _) in &self.tcx.sess.opts.libs {
196             if let &Some(ref new_name) = new_name {
197                 let any_duplicate = self
198                     .libs
199                     .iter()
200                     .filter_map(|lib| lib.name.as_ref())
201                     .any(|n| n.as_str() == *name);
202                 if new_name.is_empty() {
203                     self.tcx.sess.err(&format!(
204                         "an empty renaming target was specified for library `{}`",
205                         name
206                     ));
207                 } else if !any_duplicate {
208                     self.tcx.sess.err(&format!(
209                         "renaming of the library `{}` was specified, \
210                                                 however this crate contains no `#[link(...)]` \
211                                                 attributes referencing this library.",
212                         name
213                     ));
214                 } else if !renames.insert(name) {
215                     self.tcx.sess.err(&format!(
216                         "multiple renamings were \
217                                                 specified for library `{}` .",
218                         name
219                     ));
220                 }
221             }
222         }
223
224         // Update kind and, optionally, the name of all native libraries
225         // (there may be more than one) with the specified name.  If any
226         // library is mentioned more than once, keep the latest mention
227         // of it, so that any possible dependent libraries appear before
228         // it.  (This ensures that the linker is able to see symbols from
229         // all possible dependent libraries before linking in the library
230         // in question.)
231         for &(ref name, ref new_name, kind) in &self.tcx.sess.opts.libs {
232             // If we've already added any native libraries with the same
233             // name, they will be pulled out into `existing`, so that we
234             // can move them to the end of the list below.
235             let mut existing = self
236                 .libs
237                 .drain_filter(|lib| {
238                     if let Some(lib_name) = lib.name {
239                         if lib_name.as_str() == *name {
240                             if let Some(k) = kind {
241                                 lib.kind = k;
242                             }
243                             if let &Some(ref new_name) = new_name {
244                                 lib.name = Some(Symbol::intern(new_name));
245                             }
246                             return true;
247                         }
248                     }
249                     false
250                 })
251                 .collect::<Vec<_>>();
252             if existing.is_empty() {
253                 // Add if not found
254                 let new_name = new_name.as_ref().map(|s| &**s); // &Option<String> -> Option<&str>
255                 let lib = NativeLibrary {
256                     name: Some(Symbol::intern(new_name.unwrap_or(name))),
257                     kind: if let Some(k) = kind { k } else { cstore::NativeUnknown },
258                     cfg: None,
259                     foreign_module: None,
260                     wasm_import_module: None,
261                 };
262                 self.register_native_lib(None, lib);
263             } else {
264                 // Move all existing libraries with the same name to the
265                 // end of the command line.
266                 self.libs.append(&mut existing);
267             }
268         }
269     }
270 }