]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/link_args.rs
Refactor mod/check (part vii)
[rust.git] / src / librustc_metadata / link_args.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::ty::TyCtxt;
14 use rustc_target::spec::abi::Abi;
15
16 pub fn collect<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Vec<String> {
17     let mut collector = Collector {
18         args: Vec::new(),
19     };
20     tcx.hir.krate().visit_all_item_likes(&mut collector);
21
22     for attr in tcx.hir.krate().attrs.iter() {
23         if attr.path == "link_args" {
24             if let Some(linkarg) = attr.value_str() {
25                 collector.add_link_args(&linkarg.as_str());
26             }
27         }
28     }
29
30     return collector.args
31 }
32
33 struct Collector {
34     args: Vec<String>,
35 }
36
37 impl<'tcx> ItemLikeVisitor<'tcx> for Collector {
38     fn visit_item(&mut self, it: &'tcx hir::Item) {
39         let fm = match it.node {
40             hir::ItemKind::ForeignMod(ref fm) => fm,
41             _ => return,
42         };
43         if fm.abi == Abi::Rust ||
44             fm.abi == Abi::RustIntrinsic ||
45             fm.abi == Abi::PlatformIntrinsic {
46             return
47         }
48
49         // First, add all of the custom #[link_args] attributes
50         for m in it.attrs.iter().filter(|a| a.check_name("link_args")) {
51             if let Some(linkarg) = m.value_str() {
52                 self.add_link_args(&linkarg.as_str());
53             }
54         }
55     }
56
57     fn visit_trait_item(&mut self, _it: &'tcx hir::TraitItem) {}
58     fn visit_impl_item(&mut self, _it: &'tcx hir::ImplItem) {}
59 }
60
61 impl Collector {
62     fn add_link_args(&mut self, args: &str) {
63         self.args.extend(args.split(' ').filter(|s| !s.is_empty()).map(|s| s.to_string()))
64     }
65 }