]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_session/src/output.rs
Rollup merge of #103757 - ffmancera:ff/clarify_E0207, r=jackh726
[rust.git] / compiler / rustc_session / src / 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::errors::{
4     CrateNameDoesNotMatch, CrateNameEmpty, CrateNameInvalid, FileIsNotWriteable,
5     InvalidCharacterInCrateName,
6 };
7 use crate::Session;
8 use rustc_ast as ast;
9 use rustc_span::symbol::sym;
10 use rustc_span::Span;
11 use std::path::{Path, PathBuf};
12
13 pub fn out_filename(
14     sess: &Session,
15     crate_type: CrateType,
16     outputs: &OutputFilenames,
17     crate_name: &str,
18 ) -> PathBuf {
19     let default_filename = filename_for_input(sess, crate_type, crate_name, outputs);
20     let out_filename = outputs
21         .outputs
22         .get(&OutputType::Exe)
23         .and_then(|s| s.to_owned())
24         .or_else(|| outputs.single_output_file.clone())
25         .unwrap_or(default_filename);
26
27     check_file_is_writeable(&out_filename, sess);
28
29     out_filename
30 }
31
32 /// Make sure files are writeable.  Mac, FreeBSD, and Windows system linkers
33 /// check this already -- however, the Linux linker will happily overwrite a
34 /// read-only file.  We should be consistent.
35 pub fn check_file_is_writeable(file: &Path, sess: &Session) {
36     if !is_writeable(file) {
37         sess.emit_fatal(FileIsNotWriteable { file });
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: &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         sess.find_by_name(attrs, sym::crate_name).and_then(|at| at.value_str().map(|s| (at, s)));
60
61     if let Some(ref s) = sess.opts.crate_name {
62         if let Some((attr, name)) = attr_crate_name {
63             if name.as_str() != s {
64                 sess.emit_err(CrateNameDoesNotMatch { span: attr.span, s, name });
65             }
66         }
67         return validate(s.clone(), None);
68     }
69
70     if let Some((attr, s)) = attr_crate_name {
71         return validate(s.to_string(), Some(attr.span));
72     }
73     if let Input::File(ref path) = *input {
74         if let Some(s) = path.file_stem().and_then(|s| s.to_str()) {
75             if s.starts_with('-') {
76                 sess.emit_err(CrateNameInvalid { s });
77             } else {
78                 return validate(s.replace('-', "_"), None);
79             }
80         }
81     }
82
83     "rust_out".to_string()
84 }
85
86 pub fn validate_crate_name(sess: &Session, s: &str, sp: Option<Span>) {
87     let mut err_count = 0;
88     {
89         if s.is_empty() {
90             err_count += 1;
91             sess.emit_err(CrateNameEmpty { span: sp });
92         }
93         for c in s.chars() {
94             if c.is_alphanumeric() {
95                 continue;
96             }
97             if c == '_' {
98                 continue;
99             }
100             err_count += 1;
101             sess.emit_err(InvalidCharacterInCrateName { span: sp, character: c, crate_name: s });
102         }
103     }
104
105     if err_count > 0 {
106         sess.abort_if_errors();
107     }
108 }
109
110 pub fn filename_for_metadata(
111     sess: &Session,
112     crate_name: &str,
113     outputs: &OutputFilenames,
114 ) -> PathBuf {
115     // If the command-line specified the path, use that directly.
116     if let Some(Some(out_filename)) = sess.opts.output_types.get(&OutputType::Metadata) {
117         return out_filename.clone();
118     }
119
120     let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
121
122     let out_filename = outputs
123         .single_output_file
124         .clone()
125         .unwrap_or_else(|| outputs.out_directory.join(&format!("lib{libname}.rmeta")));
126
127     check_file_is_writeable(&out_filename, sess);
128
129     out_filename
130 }
131
132 pub fn filename_for_input(
133     sess: &Session,
134     crate_type: CrateType,
135     crate_name: &str,
136     outputs: &OutputFilenames,
137 ) -> PathBuf {
138     let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
139
140     match crate_type {
141         CrateType::Rlib => outputs.out_directory.join(&format!("lib{libname}.rlib")),
142         CrateType::Cdylib | CrateType::ProcMacro | CrateType::Dylib => {
143             let (prefix, suffix) = (&sess.target.dll_prefix, &sess.target.dll_suffix);
144             outputs.out_directory.join(&format!("{prefix}{libname}{suffix}"))
145         }
146         CrateType::Staticlib => {
147             let (prefix, suffix) = (&sess.target.staticlib_prefix, &sess.target.staticlib_suffix);
148             outputs.out_directory.join(&format!("{prefix}{libname}{suffix}"))
149         }
150         CrateType::Executable => {
151             let suffix = &sess.target.exe_suffix;
152             let out_filename = outputs.path(OutputType::Exe);
153             if suffix.is_empty() { out_filename } else { out_filename.with_extension(&suffix[1..]) }
154         }
155     }
156 }
157
158 /// Returns default crate type for target
159 ///
160 /// Default crate type is used when crate type isn't provided neither
161 /// through cmd line arguments nor through crate attributes
162 ///
163 /// It is CrateType::Executable for all platforms but iOS as there is no
164 /// way to run iOS binaries anyway without jailbreaking and
165 /// interaction with Rust code through static library is the only
166 /// option for now
167 pub fn default_output_for_target(sess: &Session) -> CrateType {
168     if !sess.target.executables { CrateType::Staticlib } else { CrateType::Executable }
169 }
170
171 /// Checks if target supports crate_type as output
172 pub fn invalid_output_for_target(sess: &Session, crate_type: CrateType) -> bool {
173     if let CrateType::Cdylib | CrateType::Dylib | CrateType::ProcMacro = crate_type {
174         if !sess.target.dynamic_linking {
175             return true;
176         }
177         if sess.crt_static(Some(crate_type)) && !sess.target.crt_static_allows_dylibs {
178             return true;
179         }
180     }
181     if let CrateType::ProcMacro | CrateType::Dylib = crate_type && sess.target.only_cdylib {
182         return true;
183     }
184     if let CrateType::Executable = crate_type && !sess.target.executables {
185         return true;
186     }
187
188     false
189 }