Skip to main content

rustc_session/
output.rs

1//! Related to out filenames of compilation (e.g. binaries).
2
3use std::path::Path;
4
5use rustc_span::{Span, Symbol};
6use rustc_structures::CrateType;
7
8use crate::Session;
9use crate::config::{OutFileName, OutputFilenames, OutputType};
10use crate::diagnostics::{
11    CrateNameEmpty, FileIsNotWriteable, InvalidCharacterInCrateName,
12    InvalidCharacterInCrateNameSuggestion,
13};
14
15pub fn out_filename(
16    sess: &Session,
17    crate_type: CrateType,
18    outputs: &OutputFilenames,
19    crate_name: Symbol,
20) -> OutFileName {
21    let default_filename = filename_for_input(sess, crate_type, crate_name, outputs);
22    let out_filename = outputs
23        .outputs
24        .get(&OutputType::Exe)
25        .and_then(|s| s.to_owned())
26        .or_else(|| outputs.single_output_file.clone())
27        .unwrap_or(default_filename);
28
29    if let OutFileName::Real(ref path) = out_filename {
30        check_file_is_writeable(path, sess);
31    }
32
33    out_filename
34}
35
36/// Make sure files are writeable. Mac, FreeBSD, and Windows system linkers
37/// check this already -- however, the Linux linker will happily overwrite a
38/// read-only file. We should be consistent.
39pub fn check_file_is_writeable(file: &Path, sess: &Session) {
40    if !is_writeable(file) {
41        sess.dcx().emit_fatal(FileIsNotWriteable { file });
42    }
43}
44
45fn is_writeable(p: &Path) -> bool {
46    match p.metadata() {
47        Err(..) => true,
48        Ok(m) => !m.permissions().readonly(),
49    }
50}
51
52/// Validate the given crate name.
53///
54/// Note that this validation is more permissive than identifier parsing. It considers
55/// non-empty sequences of alphanumeric and underscore characters to be valid crate names.
56/// Most notably, it accepts names starting with a numeric character like `0`!
57///
58/// Furthermore, this shouldn't be taken as the canonical crate name validator.
59/// Other places may use a more restrictive grammar (e.g., identifier or ASCII identifier).
60pub fn validate_crate_name(sess: &Session, crate_name: Symbol, span: Option<Span>) {
61    let mut guar = None;
62
63    if crate_name.is_empty() {
64        guar = Some(sess.dcx().emit_err(CrateNameEmpty { span }));
65    }
66
67    for c in crate_name.as_str().chars() {
68        if c.is_alphanumeric() || c == '_' {
69            continue;
70        }
71        guar = Some(sess.dcx().emit_err(InvalidCharacterInCrateName {
72            span,
73            character: c,
74            crate_name,
75            suggestion: span.is_none().then(|| InvalidCharacterInCrateNameSuggestion {
76                suggested_name:
77                    crate_name.as_str().replace(|c: char| c != '_' && !c.is_alphanumeric(), "_"),
78            }),
79        }));
80    }
81
82    if let Some(guar) = guar {
83        guar.raise_fatal();
84    }
85}
86
87pub fn filename_for_metadata(sess: &Session, outputs: &OutputFilenames) -> OutFileName {
88    let out_filename = outputs.path(OutputType::Metadata);
89    if let OutFileName::Real(ref path) = out_filename {
90        check_file_is_writeable(path, sess);
91    }
92    out_filename
93}
94
95pub fn filename_for_input(
96    sess: &Session,
97    crate_type: CrateType,
98    crate_name: Symbol,
99    outputs: &OutputFilenames,
100) -> OutFileName {
101    let libname = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", crate_name,
                sess.opts.cg.extra_filename))
    })format!("{}{}", crate_name, sess.opts.cg.extra_filename);
102
103    match crate_type {
104        CrateType::Rlib => {
105            OutFileName::Real(outputs.out_directory.join(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("lib{0}.rlib", libname))
    })format!("lib{libname}.rlib")))
106        }
107        CrateType::Cdylib | CrateType::ProcMacro | CrateType::Dylib | CrateType::Sdylib => {
108            let (prefix, suffix) = (&sess.target.dll_prefix, &sess.target.dll_suffix);
109            OutFileName::Real(outputs.out_directory.join(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, libname,
                suffix))
    })format!("{prefix}{libname}{suffix}")))
110        }
111        CrateType::StaticLib => {
112            let (prefix, suffix) = sess.staticlib_components(false);
113            OutFileName::Real(outputs.out_directory.join(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}", prefix, libname,
                suffix))
    })format!("{prefix}{libname}{suffix}")))
114        }
115        CrateType::Executable => {
116            let suffix = &sess.target.exe_suffix;
117            let out_filename = outputs.path(OutputType::Exe);
118            if let OutFileName::Real(ref path) = out_filename {
119                if suffix.is_empty() {
120                    out_filename
121                } else {
122                    OutFileName::Real(path.with_extension(&suffix[1..]))
123                }
124            } else {
125                out_filename
126            }
127        }
128    }
129}
130
131/// Checks if target supports crate_type as output
132pub fn invalid_output_for_target(sess: &Session, crate_type: CrateType) -> bool {
133    if let CrateType::Cdylib | CrateType::Dylib | CrateType::ProcMacro = crate_type {
134        if !sess.target.dynamic_linking {
135            return true;
136        }
137        if sess.crt_static(Some(crate_type)) && !sess.target.crt_static_allows_dylibs {
138            return true;
139        }
140    }
141    if crate_type == CrateType::ProcMacro {
142        if sess.opts.target_triple == sess.wasm_proc_macro_tuple
143            && sess.opts.unstable_opts.wasm_proc_macros
144        {
145            return false;
146        }
147    }
148    if let CrateType::ProcMacro | CrateType::Dylib = crate_type
149        && sess.target.only_cdylib
150    {
151        return true;
152    }
153    if let CrateType::Executable = crate_type
154        && !sess.target.executables
155    {
156        return true;
157    }
158
159    false
160}