]> git.lizzy.rs Git - rust.git/blob - src/librustc_session/output.rs
Rollup merge of #73169 - Amanieu:asm-warnings, r=petrochenkov
[rust.git] / src / librustc_session / output.rs
1 //! Related to out filenames of compilation (e.g. save analysis, binaries).
2 use crate::config::{CrateType, Input, OutputFilenames, OutputType};
3 use crate::Session;
4 use rustc_ast::{ast, attr};
5 use rustc_span::symbol::sym;
6 use rustc_span::Span;
7 use std::path::{Path, PathBuf};
8
9 pub fn out_filename(
10     sess: &Session,
11     crate_type: CrateType,
12     outputs: &OutputFilenames,
13     crate_name: &str,
14 ) -> PathBuf {
15     let default_filename = filename_for_input(sess, crate_type, crate_name, outputs);
16     let out_filename = outputs
17         .outputs
18         .get(&OutputType::Exe)
19         .and_then(|s| s.to_owned())
20         .or_else(|| outputs.single_output_file.clone())
21         .unwrap_or(default_filename);
22
23     check_file_is_writeable(&out_filename, sess);
24
25     out_filename
26 }
27
28 /// Make sure files are writeable.  Mac, FreeBSD, and Windows system linkers
29 /// check this already -- however, the Linux linker will happily overwrite a
30 /// read-only file.  We should be consistent.
31 pub fn check_file_is_writeable(file: &Path, sess: &Session) {
32     if !is_writeable(file) {
33         sess.fatal(&format!(
34             "output file {} is not writeable -- check its \
35                             permissions",
36             file.display()
37         ));
38     }
39 }
40
41 fn is_writeable(p: &Path) -> bool {
42     match p.metadata() {
43         Err(..) => true,
44         Ok(m) => !m.permissions().readonly(),
45     }
46 }
47
48 pub fn find_crate_name(sess: Option<&Session>, attrs: &[ast::Attribute], input: &Input) -> String {
49     let validate = |s: String, span: Option<Span>| {
50         validate_crate_name(sess, &s, span);
51         s
52     };
53
54     // Look in attributes 100% of the time to make sure the attribute is marked
55     // as used. After doing this, however, we still prioritize a crate name from
56     // the command line over one found in the #[crate_name] attribute. If we
57     // find both we ensure that they're the same later on as well.
58     let attr_crate_name =
59         attr::find_by_name(attrs, sym::crate_name).and_then(|at| at.value_str().map(|s| (at, s)));
60
61     if let Some(sess) = sess {
62         if let Some(ref s) = sess.opts.crate_name {
63             if let Some((attr, name)) = attr_crate_name {
64                 if name.as_str() != *s {
65                     let msg = format!(
66                         "`--crate-name` and `#[crate_name]` are \
67                                        required to match, but `{}` != `{}`",
68                         s, name
69                     );
70                     sess.span_err(attr.span, &msg);
71                 }
72             }
73             return validate(s.clone(), None);
74         }
75     }
76
77     if let Some((attr, s)) = attr_crate_name {
78         return validate(s.to_string(), Some(attr.span));
79     }
80     if let Input::File(ref path) = *input {
81         if let Some(s) = path.file_stem().and_then(|s| s.to_str()) {
82             if s.starts_with('-') {
83                 let msg = format!(
84                     "crate names cannot start with a `-`, but \
85                                    `{}` has a leading hyphen",
86                     s
87                 );
88                 if let Some(sess) = sess {
89                     sess.err(&msg);
90                 }
91             } else {
92                 return validate(s.replace("-", "_"), None);
93             }
94         }
95     }
96
97     "rust_out".to_string()
98 }
99
100 pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
101     let mut err_count = 0;
102     {
103         let mut say = |s: &str| {
104             match (sp, sess) {
105                 (_, None) => panic!("{}", s),
106                 (Some(sp), Some(sess)) => sess.span_err(sp, s),
107                 (None, Some(sess)) => sess.err(s),
108             }
109             err_count += 1;
110         };
111         if s.is_empty() {
112             say("crate name must not be empty");
113         }
114         for c in s.chars() {
115             if c.is_alphanumeric() {
116                 continue;
117             }
118             if c == '_' {
119                 continue;
120             }
121             say(&format!("invalid character `{}` in crate name: `{}`", c, s));
122         }
123     }
124
125     if err_count > 0 {
126         sess.unwrap().abort_if_errors();
127     }
128 }
129
130 pub fn filename_for_metadata(
131     sess: &Session,
132     crate_name: &str,
133     outputs: &OutputFilenames,
134 ) -> PathBuf {
135     let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
136
137     let out_filename = outputs
138         .single_output_file
139         .clone()
140         .unwrap_or_else(|| outputs.out_directory.join(&format!("lib{}.rmeta", libname)));
141
142     check_file_is_writeable(&out_filename, sess);
143
144     out_filename
145 }
146
147 pub fn filename_for_input(
148     sess: &Session,
149     crate_type: CrateType,
150     crate_name: &str,
151     outputs: &OutputFilenames,
152 ) -> PathBuf {
153     let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
154
155     match crate_type {
156         CrateType::Rlib => outputs.out_directory.join(&format!("lib{}.rlib", libname)),
157         CrateType::Cdylib | CrateType::ProcMacro | CrateType::Dylib => {
158             let (prefix, suffix) =
159                 (&sess.target.target.options.dll_prefix, &sess.target.target.options.dll_suffix);
160             outputs.out_directory.join(&format!("{}{}{}", prefix, libname, suffix))
161         }
162         CrateType::Staticlib => {
163             let (prefix, suffix) = (
164                 &sess.target.target.options.staticlib_prefix,
165                 &sess.target.target.options.staticlib_suffix,
166             );
167             outputs.out_directory.join(&format!("{}{}{}", prefix, libname, suffix))
168         }
169         CrateType::Executable => {
170             let suffix = &sess.target.target.options.exe_suffix;
171             let out_filename = outputs.path(OutputType::Exe);
172             if suffix.is_empty() { out_filename } else { out_filename.with_extension(&suffix[1..]) }
173         }
174     }
175 }
176
177 /// Returns default crate type for target
178 ///
179 /// Default crate type is used when crate type isn't provided neither
180 /// through cmd line arguments nor through crate attributes
181 ///
182 /// It is CrateType::Executable for all platforms but iOS as there is no
183 /// way to run iOS binaries anyway without jailbreaking and
184 /// interaction with Rust code through static library is the only
185 /// option for now
186 pub fn default_output_for_target(sess: &Session) -> CrateType {
187     if !sess.target.target.options.executables {
188         CrateType::Staticlib
189     } else {
190         CrateType::Executable
191     }
192 }
193
194 /// Checks if target supports crate_type as output
195 pub fn invalid_output_for_target(sess: &Session, crate_type: CrateType) -> bool {
196     match crate_type {
197         CrateType::Cdylib | CrateType::Dylib | CrateType::ProcMacro => {
198             if !sess.target.target.options.dynamic_linking {
199                 return true;
200             }
201             if sess.crt_static(Some(crate_type))
202                 && !sess.target.target.options.crt_static_allows_dylibs
203             {
204                 return true;
205             }
206         }
207         _ => {}
208     }
209     if sess.target.target.options.only_cdylib {
210         match crate_type {
211             CrateType::ProcMacro | CrateType::Dylib => return true,
212             _ => {}
213         }
214     }
215     if !sess.target.target.options.executables {
216         if crate_type == CrateType::Executable {
217             return true;
218         }
219     }
220
221     false
222 }