rustc_session/config/
externs.rs1use std::path::PathBuf;
4
5use rustc_errors::{Diag, FatalAbort};
6
7use super::UnstableOptions;
8use crate::EarlyDiagCtxt;
9
10#[cfg(test)]
11mod tests;
12
13pub(crate) struct ExternOpt {
15 pub(crate) crate_name: String,
16 pub(crate) path: Option<PathBuf>,
17 pub(crate) options: Option<String>,
18}
19
20pub(crate) fn split_extern_opt<'a>(
25 early_dcx: &'a EarlyDiagCtxt,
26 unstable_opts: &UnstableOptions,
27 extern_opt: &str,
28) -> Result<ExternOpt, Diag<'a, FatalAbort>> {
29 let (name, path) = match extern_opt.split_once('=') {
30 None => (extern_opt.to_string(), None),
31 Some((name, path)) => (name.to_string(), Some(PathBuf::from(path))),
32 };
33 let (options, crate_name) = match name.split_once(':') {
34 None => (None, name),
35 Some((opts, crate_name)) => {
36 if unstable_opts.namespaced_crates && crate_name.starts_with(':') {
37 (None, name)
40 } else {
41 (Some(opts.to_string()), crate_name.to_string())
42 }
43 }
44 };
45
46 if !valid_crate_name(&crate_name, unstable_opts) {
47 let mut error = early_dcx.early_struct_fatal(format!(
48 "crate name `{crate_name}` passed to `--extern` is not a valid ASCII identifier"
49 ));
50 let adjusted_name = crate_name.replace('-', "_");
51 if is_ascii_ident(&adjusted_name) {
52 #[allow(rustc::diagnostic_outside_of_impl)] error
54 .help(format!("consider replacing the dashes with underscores: `{adjusted_name}`"));
55 }
56 return Err(error);
57 }
58
59 Ok(ExternOpt { crate_name, path, options })
60}
61
62fn valid_crate_name(name: &str, unstable_opts: &UnstableOptions) -> bool {
63 match name.split_once("::") {
64 Some((a, b)) if unstable_opts.namespaced_crates => is_ascii_ident(a) && is_ascii_ident(b),
65 Some(_) => false,
66 None => is_ascii_ident(name),
67 }
68}
69
70fn is_ascii_ident(string: &str) -> bool {
71 let mut chars = string.chars();
72 if let Some(start) = chars.next()
73 && (start.is_ascii_alphabetic() || start == '_')
74 {
75 chars.all(|char| char.is_ascii_alphanumeric() || char == '_')
76 } else {
77 false
78 }
79}