]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_session/src/output.rs
Auto merge of #104889 - GuillaumeGomez:fix-impl-block-in-const-expr, r=notriddle
[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, Symbol};
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: Symbol,
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) -> Symbol {
49     let validate = |s: Symbol, 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         let s = Symbol::intern(s);
63         if let Some((attr, name)) = attr_crate_name {
64             if name != s {
65                 sess.emit_err(CrateNameDoesNotMatch { span: attr.span, s, name });
66             }
67         }
68         return validate(s, None);
69     }
70
71     if let Some((attr, s)) = attr_crate_name {
72         return validate(s, Some(attr.span));
73     }
74     if let Input::File(ref path) = *input {
75         if let Some(s) = path.file_stem().and_then(|s| s.to_str()) {
76             if s.starts_with('-') {
77                 sess.emit_err(CrateNameInvalid { s });
78             } else {
79                 return validate(Symbol::intern(&s.replace('-', "_")), None);
80             }
81         }
82     }
83
84     Symbol::intern("rust_out")
85 }
86
87 pub fn validate_crate_name(sess: &Session, s: Symbol, sp: Option<Span>) {
88     let mut err_count = 0;
89     {
90         if s.is_empty() {
91             err_count += 1;
92             sess.emit_err(CrateNameEmpty { span: sp });
93         }
94         for c in s.as_str().chars() {
95             if c.is_alphanumeric() {
96                 continue;
97             }
98             if c == '_' {
99                 continue;
100             }
101             err_count += 1;
102             sess.emit_err(InvalidCharacterInCrateName { span: sp, character: c, crate_name: s });
103         }
104     }
105
106     if err_count > 0 {
107         sess.abort_if_errors();
108     }
109 }
110
111 pub fn filename_for_metadata(
112     sess: &Session,
113     crate_name: Symbol,
114     outputs: &OutputFilenames,
115 ) -> PathBuf {
116     // If the command-line specified the path, use that directly.
117     if let Some(Some(out_filename)) = sess.opts.output_types.get(&OutputType::Metadata) {
118         return out_filename.clone();
119     }
120
121     let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
122
123     let out_filename = outputs
124         .single_output_file
125         .clone()
126         .unwrap_or_else(|| outputs.out_directory.join(&format!("lib{libname}.rmeta")));
127
128     check_file_is_writeable(&out_filename, sess);
129
130     out_filename
131 }
132
133 pub fn filename_for_input(
134     sess: &Session,
135     crate_type: CrateType,
136     crate_name: Symbol,
137     outputs: &OutputFilenames,
138 ) -> PathBuf {
139     let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
140
141     match crate_type {
142         CrateType::Rlib => outputs.out_directory.join(&format!("lib{libname}.rlib")),
143         CrateType::Cdylib | CrateType::ProcMacro | CrateType::Dylib => {
144             let (prefix, suffix) = (&sess.target.dll_prefix, &sess.target.dll_suffix);
145             outputs.out_directory.join(&format!("{prefix}{libname}{suffix}"))
146         }
147         CrateType::Staticlib => {
148             let (prefix, suffix) = (&sess.target.staticlib_prefix, &sess.target.staticlib_suffix);
149             outputs.out_directory.join(&format!("{prefix}{libname}{suffix}"))
150         }
151         CrateType::Executable => {
152             let suffix = &sess.target.exe_suffix;
153             let out_filename = outputs.path(OutputType::Exe);
154             if suffix.is_empty() { out_filename } else { out_filename.with_extension(&suffix[1..]) }
155         }
156     }
157 }
158
159 /// Returns default crate type for target
160 ///
161 /// Default crate type is used when crate type isn't provided neither
162 /// through cmd line arguments nor through crate attributes
163 ///
164 /// It is CrateType::Executable for all platforms but iOS as there is no
165 /// way to run iOS binaries anyway without jailbreaking and
166 /// interaction with Rust code through static library is the only
167 /// option for now
168 pub fn default_output_for_target(sess: &Session) -> CrateType {
169     if !sess.target.executables { CrateType::Staticlib } else { CrateType::Executable }
170 }
171
172 /// Checks if target supports crate_type as output
173 pub fn invalid_output_for_target(sess: &Session, crate_type: CrateType) -> bool {
174     if let CrateType::Cdylib | CrateType::Dylib | CrateType::ProcMacro = crate_type {
175         if !sess.target.dynamic_linking {
176             return true;
177         }
178         if sess.crt_static(Some(crate_type)) && !sess.target.crt_static_allows_dylibs {
179             return true;
180         }
181     }
182     if let CrateType::ProcMacro | CrateType::Dylib = crate_type && sess.target.only_cdylib {
183         return true;
184     }
185     if let CrateType::Executable = crate_type && !sess.target.executables {
186         return true;
187     }
188
189     false
190 }