1 use rustc::hir::itemlikevisit::ItemLikeVisitor;
3 use rustc::middle::cstore::{self, NativeLibrary};
4 use rustc::session::Session;
6 use rustc::util::nodemap::FxHashSet;
7 use rustc_target::spec::abi::Abi;
9 use syntax::source_map::Span;
10 use syntax::feature_gate::{self, GateIssue};
11 use syntax::symbol::{kw, sym, Symbol};
12 use syntax::{span_err, struct_span_err};
14 crate fn collect(tcx: TyCtxt<'_>) -> Vec<NativeLibrary> {
15 let mut collector = Collector {
19 tcx.hir().krate().visit_all_item_likes(&mut collector);
20 collector.process_command_line();
21 return collector.libs;
24 crate fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
26 Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
31 struct Collector<'tcx> {
33 libs: Vec<NativeLibrary>,
36 impl ItemLikeVisitor<'tcx> for Collector<'tcx> {
37 fn visit_item(&mut self, it: &'tcx hir::Item) {
38 let fm = match it.kind {
39 hir::ItemKind::ForeignMod(ref fm) => fm,
43 if fm.abi == Abi::Rust ||
44 fm.abi == Abi::RustIntrinsic ||
45 fm.abi == Abi::PlatformIntrinsic {
49 // Process all of the #[link(..)]-style arguments
50 for m in it.attrs.iter().filter(|a| a.check_name(sym::link)) {
51 let items = match m.meta_item_list() {
55 let mut lib = NativeLibrary {
57 kind: cstore::NativeUnknown,
59 foreign_module: Some(self.tcx.hir().local_def_id(it.hir_id)),
60 wasm_import_module: None,
62 let mut kind_specified = false;
64 for item in items.iter() {
65 if item.check_name(sym::kind) {
66 kind_specified = true;
67 let kind = match item.value_str() {
69 None => continue, // skip like historical compilers
71 lib.kind = match &kind.as_str()[..] {
72 "static" => cstore::NativeStatic,
73 "static-nobundle" => cstore::NativeStaticNobundle,
74 "dylib" => cstore::NativeUnknown,
75 "framework" => cstore::NativeFramework,
76 "raw-dylib" => cstore::NativeRawDylib,
78 struct_span_err!(self.tcx.sess, item.span(), E0458,
79 "unknown kind: `{}`", k)
80 .span_label(item.span(), "unknown kind")
81 .span_label(m.span, "").emit();
85 } else if item.check_name(sym::name) {
86 lib.name = item.value_str();
87 } else if item.check_name(sym::cfg) {
88 let cfg = match item.meta_item_list() {
90 None => continue, // skip like historical compilers
93 self.tcx.sess.span_err(
95 "`cfg()` must have an argument",
97 } else if let cfg @ Some(..) = cfg[0].meta_item() {
98 lib.cfg = cfg.cloned();
100 self.tcx.sess.span_err(cfg[0].span(), "invalid argument for `cfg(..)`");
102 } else if item.check_name(sym::wasm_import_module) {
103 match item.value_str() {
104 Some(s) => lib.wasm_import_module = Some(s),
106 let msg = "must be of the form `#[link(wasm_import_module = \"...\")]`";
107 self.tcx.sess.span_err(item.span(), msg);
111 // currently, like past compilers, ignore unknown
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!(self.tcx.sess, m.span, E0459,
121 "`#[link(...)]` specified without \
123 .span_label(m.span, "missing `name` argument")
126 self.register_native_lib(Some(m.span), lib);
130 fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem) {}
131 fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem) {}
134 impl Collector<'tcx> {
135 fn register_native_lib(&mut self, span: Option<Span>, lib: NativeLibrary) {
136 if lib.name.as_ref().map(|&s| s == kw::Invalid).unwrap_or(false) {
139 struct_span_err!(self.tcx.sess, span, E0454,
140 "`#[link(name = \"\")]` given with empty name")
141 .span_label(span, "empty name given")
145 self.tcx.sess.err("empty library name given via `-l`");
150 let is_osx = self.tcx.sess.target.target.options.is_like_osx;
151 if lib.kind == cstore::NativeFramework && !is_osx {
152 let msg = "native frameworks are only available on macOS targets";
154 Some(span) => span_err!(self.tcx.sess, span, E0455, "{}", msg),
155 None => self.tcx.sess.err(msg),
158 if lib.cfg.is_some() && !self.tcx.features().link_cfg {
159 feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
165 if lib.kind == cstore::NativeStaticNobundle &&
166 !self.tcx.features().static_nobundle {
167 feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
168 sym::static_nobundle,
169 span.unwrap_or_else(|| syntax_pos::DUMMY_SP),
171 "kind=\"static-nobundle\" is unstable");
173 if lib.kind == cstore::NativeRawDylib &&
174 !self.tcx.features().raw_dylib {
175 feature_gate::emit_feature_err(&self.tcx.sess.parse_sess,
177 span.unwrap_or_else(|| syntax_pos::DUMMY_SP),
179 "kind=\"raw-dylib\" is unstable");
184 // Process libs passed on the command line
185 fn process_command_line(&mut self) {
186 // First, check for errors
187 let mut renames = FxHashSet::default();
188 for &(ref name, ref new_name, _) in &self.tcx.sess.opts.libs {
189 if let &Some(ref new_name) = new_name {
190 let any_duplicate = self.libs
192 .filter_map(|lib| lib.name.as_ref())
193 .any(|n| n.as_str() == *name);
194 if new_name.is_empty() {
196 &format!("an empty renaming target was specified for library `{}`",name));
197 } else if !any_duplicate {
198 self.tcx.sess.err(&format!("renaming of the library `{}` was specified, \
199 however this crate contains no `#[link(...)]` \
200 attributes referencing this library.", name));
201 } else if renames.contains(name) {
202 self.tcx.sess.err(&format!("multiple renamings were \
203 specified for library `{}` .",
206 renames.insert(name);
211 // Update kind and, optionally, the name of all native libraries
212 // (there may be more than one) with the specified name. If any
213 // library is mentioned more than once, keep the latest mention
214 // of it, so that any possible dependent libraries appear before
215 // it. (This ensures that the linker is able to see symbols from
216 // all possible dependent libraries before linking in the library
218 for &(ref name, ref new_name, kind) in &self.tcx.sess.opts.libs {
219 // If we've already added any native libraries with the same
220 // name, they will be pulled out into `existing`, so that we
221 // can move them to the end of the list below.
222 let mut existing = self.libs.drain_filter(|lib| {
223 if let Some(lib_name) = lib.name {
224 if lib_name.as_str() == *name {
225 if let Some(k) = kind {
228 if let &Some(ref new_name) = new_name {
229 lib.name = Some(Symbol::intern(new_name));
235 }).collect::<Vec<_>>();
236 if existing.is_empty() {
238 let new_name = new_name.as_ref().map(|s| &**s); // &Option<String> -> Option<&str>
239 let lib = NativeLibrary {
240 name: Some(Symbol::intern(new_name.unwrap_or(name))),
241 kind: if let Some(k) = kind { k } else { cstore::NativeUnknown },
243 foreign_module: None,
244 wasm_import_module: None,
246 self.register_native_lib(None, lib);
248 // Move all existing libraries with the same name to the
249 // end of the command line.
250 self.libs.append(&mut existing);