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