Skip to content

Commit 21654a2

Browse files
authored
Rollup merge of rust-lang#132934 - Zalathar:native-libs, r=jieyouxu
Overhaul the `-l` option parser (for linking to native libs) The current parser for `-l` options has accumulated over time, making it hard to follow. This PR tries to clean it up in several ways. Key changes: - This code now gets its own submodule, to slightly reduce clutter in `rustc_session::config`. - Cleaner division between iterating over multiple `-l` options, and processing each individual one. - Separate “split” step that breaks up the value string into `[KIND[:MODIFIERS]=]NAME[:NEW_NAME]`, but leaves parsing/validating those parts to later steps. - This step also gets its own (disposable) unit test, to make sure it works as expected. - A context struct reduces the burden of parameter passing, and makes it easier to write error messages that adapt to nightly/stable compilers. - Fewer calls to `nightly_options` helper functions, because at this point we can get the same information from `UnstableOptions` and `UnstableFeatures` (which are downstream of earlier calls to those helper functions). There should be no overall change in compiler behaviour.
2 parents bf6adec + 78edefe commit 21654a2

14 files changed

+286
-148
lines changed

compiler/rustc_session/src/config.rs

+9-144
Original file line numberDiff line numberDiff line change
@@ -30,17 +30,18 @@ use rustc_target::spec::{
3030
};
3131
use tracing::debug;
3232

33+
pub use crate::config::cfg::{Cfg, CheckCfg, ExpectedValues};
34+
use crate::config::native_libs::parse_native_libs;
3335
use crate::errors::FileWriteFail;
3436
pub use crate::options::*;
3537
use crate::search_paths::SearchPath;
36-
use crate::utils::{CanonicalizedPath, NativeLib, NativeLibKind};
38+
use crate::utils::CanonicalizedPath;
3739
use crate::{EarlyDiagCtxt, HashStableContext, Session, filesearch, lint};
3840

3941
mod cfg;
42+
mod native_libs;
4043
pub mod sigpipe;
4144

42-
pub use cfg::{Cfg, CheckCfg, ExpectedValues};
43-
4445
/// The different settings that the `-C strip` flag can have.
4546
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
4647
pub enum Strip {
@@ -2134,143 +2135,6 @@ fn parse_assert_incr_state(
21342135
}
21352136
}
21362137

2137-
fn parse_native_lib_kind(
2138-
early_dcx: &EarlyDiagCtxt,
2139-
matches: &getopts::Matches,
2140-
kind: &str,
2141-
) -> (NativeLibKind, Option<bool>) {
2142-
let (kind, modifiers) = match kind.split_once(':') {
2143-
None => (kind, None),
2144-
Some((kind, modifiers)) => (kind, Some(modifiers)),
2145-
};
2146-
2147-
let kind = match kind {
2148-
"static" => NativeLibKind::Static { bundle: None, whole_archive: None },
2149-
"dylib" => NativeLibKind::Dylib { as_needed: None },
2150-
"framework" => NativeLibKind::Framework { as_needed: None },
2151-
"link-arg" => {
2152-
if !nightly_options::is_unstable_enabled(matches) {
2153-
let why = if nightly_options::match_is_nightly_build(matches) {
2154-
" and only accepted on the nightly compiler"
2155-
} else {
2156-
", the `-Z unstable-options` flag must also be passed to use it"
2157-
};
2158-
early_dcx.early_fatal(format!("library kind `link-arg` is unstable{why}"))
2159-
}
2160-
NativeLibKind::LinkArg
2161-
}
2162-
_ => early_dcx.early_fatal(format!(
2163-
"unknown library kind `{kind}`, expected one of: static, dylib, framework, link-arg"
2164-
)),
2165-
};
2166-
match modifiers {
2167-
None => (kind, None),
2168-
Some(modifiers) => parse_native_lib_modifiers(early_dcx, kind, modifiers, matches),
2169-
}
2170-
}
2171-
2172-
fn parse_native_lib_modifiers(
2173-
early_dcx: &EarlyDiagCtxt,
2174-
mut kind: NativeLibKind,
2175-
modifiers: &str,
2176-
matches: &getopts::Matches,
2177-
) -> (NativeLibKind, Option<bool>) {
2178-
let mut verbatim = None;
2179-
for modifier in modifiers.split(',') {
2180-
let (modifier, value) = match modifier.strip_prefix(['+', '-']) {
2181-
Some(m) => (m, modifier.starts_with('+')),
2182-
None => early_dcx.early_fatal(
2183-
"invalid linking modifier syntax, expected '+' or '-' prefix \
2184-
before one of: bundle, verbatim, whole-archive, as-needed",
2185-
),
2186-
};
2187-
2188-
let report_unstable_modifier = || {
2189-
if !nightly_options::is_unstable_enabled(matches) {
2190-
let why = if nightly_options::match_is_nightly_build(matches) {
2191-
" and only accepted on the nightly compiler"
2192-
} else {
2193-
", the `-Z unstable-options` flag must also be passed to use it"
2194-
};
2195-
early_dcx.early_fatal(format!("linking modifier `{modifier}` is unstable{why}"))
2196-
}
2197-
};
2198-
let assign_modifier = |dst: &mut Option<bool>| {
2199-
if dst.is_some() {
2200-
let msg = format!("multiple `{modifier}` modifiers in a single `-l` option");
2201-
early_dcx.early_fatal(msg)
2202-
} else {
2203-
*dst = Some(value);
2204-
}
2205-
};
2206-
match (modifier, &mut kind) {
2207-
("bundle", NativeLibKind::Static { bundle, .. }) => assign_modifier(bundle),
2208-
("bundle", _) => early_dcx.early_fatal(
2209-
"linking modifier `bundle` is only compatible with `static` linking kind",
2210-
),
2211-
2212-
("verbatim", _) => assign_modifier(&mut verbatim),
2213-
2214-
("whole-archive", NativeLibKind::Static { whole_archive, .. }) => {
2215-
assign_modifier(whole_archive)
2216-
}
2217-
("whole-archive", _) => early_dcx.early_fatal(
2218-
"linking modifier `whole-archive` is only compatible with `static` linking kind",
2219-
),
2220-
2221-
("as-needed", NativeLibKind::Dylib { as_needed })
2222-
| ("as-needed", NativeLibKind::Framework { as_needed }) => {
2223-
report_unstable_modifier();
2224-
assign_modifier(as_needed)
2225-
}
2226-
("as-needed", _) => early_dcx.early_fatal(
2227-
"linking modifier `as-needed` is only compatible with \
2228-
`dylib` and `framework` linking kinds",
2229-
),
2230-
2231-
// Note: this error also excludes the case with empty modifier
2232-
// string, like `modifiers = ""`.
2233-
_ => early_dcx.early_fatal(format!(
2234-
"unknown linking modifier `{modifier}`, expected one \
2235-
of: bundle, verbatim, whole-archive, as-needed"
2236-
)),
2237-
}
2238-
}
2239-
2240-
(kind, verbatim)
2241-
}
2242-
2243-
fn parse_libs(early_dcx: &EarlyDiagCtxt, matches: &getopts::Matches) -> Vec<NativeLib> {
2244-
matches
2245-
.opt_strs("l")
2246-
.into_iter()
2247-
.map(|s| {
2248-
// Parse string of the form "[KIND[:MODIFIERS]=]lib[:new_name]",
2249-
// where KIND is one of "dylib", "framework", "static", "link-arg" and
2250-
// where MODIFIERS are a comma separated list of supported modifiers
2251-
// (bundle, verbatim, whole-archive, as-needed). Each modifier is prefixed
2252-
// with either + or - to indicate whether it is enabled or disabled.
2253-
// The last value specified for a given modifier wins.
2254-
let (name, kind, verbatim) = match s.split_once('=') {
2255-
None => (s, NativeLibKind::Unspecified, None),
2256-
Some((kind, name)) => {
2257-
let (kind, verbatim) = parse_native_lib_kind(early_dcx, matches, kind);
2258-
(name.to_string(), kind, verbatim)
2259-
}
2260-
};
2261-
2262-
let (name, new_name) = match name.split_once(':') {
2263-
None => (name, None),
2264-
Some((name, new_name)) => (name.to_string(), Some(new_name.to_owned())),
2265-
};
2266-
if name.is_empty() {
2267-
early_dcx.early_fatal("library name must not be empty");
2268-
}
2269-
NativeLib { name, new_name, kind, verbatim }
2270-
})
2271-
.collect()
2272-
}
2273-
22742138
pub fn parse_externs(
22752139
early_dcx: &EarlyDiagCtxt,
22762140
matches: &getopts::Matches,
@@ -2644,7 +2508,10 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
26442508
let debuginfo = select_debuginfo(matches, &cg);
26452509
let debuginfo_compression = unstable_opts.debuginfo_compression;
26462510

2647-
let libs = parse_libs(early_dcx, matches);
2511+
let crate_name = matches.opt_str("crate-name");
2512+
let unstable_features = UnstableFeatures::from_environment(crate_name.as_deref());
2513+
// Parse any `-l` flags, which link to native libraries.
2514+
let libs = parse_native_libs(early_dcx, &unstable_opts, unstable_features, matches);
26482515

26492516
let test = matches.opt_present("test");
26502517

@@ -2659,8 +2526,6 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
26592526

26602527
let externs = parse_externs(early_dcx, matches, &unstable_opts);
26612528

2662-
let crate_name = matches.opt_str("crate-name");
2663-
26642529
let remap_path_prefix = parse_remap_path_prefix(early_dcx, matches, &unstable_opts);
26652530

26662531
let pretty = parse_pretty(early_dcx, &unstable_opts);
@@ -2734,7 +2599,7 @@ pub fn build_session_options(early_dcx: &mut EarlyDiagCtxt, matches: &getopts::M
27342599
error_format,
27352600
diagnostic_width,
27362601
externs,
2737-
unstable_features: UnstableFeatures::from_environment(crate_name.as_deref()),
2602+
unstable_features,
27382603
crate_name,
27392604
libs,
27402605
debug_assertions,
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
//! Parser for the `-l` command-line option, which links the generated crate to
2+
//! a native library.
3+
//!
4+
//! (There is also a similar but separate syntax for `#[link]` attributes,
5+
//! which have their own parser in `rustc_metadata`.)
6+
7+
use rustc_feature::UnstableFeatures;
8+
9+
use crate::EarlyDiagCtxt;
10+
use crate::config::UnstableOptions;
11+
use crate::utils::{NativeLib, NativeLibKind};
12+
13+
#[cfg(test)]
14+
mod tests;
15+
16+
/// Parses all `-l` options.
17+
pub(crate) fn parse_native_libs(
18+
early_dcx: &EarlyDiagCtxt,
19+
unstable_opts: &UnstableOptions,
20+
unstable_features: UnstableFeatures,
21+
matches: &getopts::Matches,
22+
) -> Vec<NativeLib> {
23+
let cx = ParseNativeLibCx {
24+
early_dcx,
25+
unstable_options_enabled: unstable_opts.unstable_options,
26+
is_nightly: unstable_features.is_nightly_build(),
27+
};
28+
matches.opt_strs("l").into_iter().map(|value| parse_native_lib(&cx, &value)).collect()
29+
}
30+
31+
struct ParseNativeLibCx<'a> {
32+
early_dcx: &'a EarlyDiagCtxt,
33+
unstable_options_enabled: bool,
34+
is_nightly: bool,
35+
}
36+
37+
impl ParseNativeLibCx<'_> {
38+
/// If unstable values are not permitted, exits with a fatal error made by
39+
/// combining the given strings.
40+
fn on_unstable_value(&self, message: &str, if_nightly: &str, if_stable: &str) {
41+
if self.unstable_options_enabled {
42+
return;
43+
}
44+
45+
let suffix = if self.is_nightly { if_nightly } else { if_stable };
46+
self.early_dcx.early_fatal(format!("{message}{suffix}"));
47+
}
48+
}
49+
50+
/// Parses the value of a single `-l` option.
51+
fn parse_native_lib(cx: &ParseNativeLibCx<'_>, value: &str) -> NativeLib {
52+
let NativeLibParts { kind, modifiers, name, new_name } = split_native_lib_value(value);
53+
54+
let kind = kind.map_or(NativeLibKind::Unspecified, |kind| match kind {
55+
"static" => NativeLibKind::Static { bundle: None, whole_archive: None },
56+
"dylib" => NativeLibKind::Dylib { as_needed: None },
57+
"framework" => NativeLibKind::Framework { as_needed: None },
58+
"link-arg" => {
59+
cx.on_unstable_value(
60+
"library kind `link-arg` is unstable",
61+
", the `-Z unstable-options` flag must also be passed to use it",
62+
" and only accepted on the nightly compiler",
63+
);
64+
NativeLibKind::LinkArg
65+
}
66+
_ => cx.early_dcx.early_fatal(format!(
67+
"unknown library kind `{kind}`, expected one of: static, dylib, framework, link-arg"
68+
)),
69+
});
70+
71+
// Provisionally create the result, so that modifiers can modify it.
72+
let mut native_lib = NativeLib {
73+
name: name.to_owned(),
74+
new_name: new_name.map(str::to_owned),
75+
kind,
76+
verbatim: None,
77+
};
78+
79+
if let Some(modifiers) = modifiers {
80+
// If multiple modifiers are present, they are separated by commas.
81+
for modifier in modifiers.split(',') {
82+
parse_and_apply_modifier(cx, modifier, &mut native_lib);
83+
}
84+
}
85+
86+
if native_lib.name.is_empty() {
87+
cx.early_dcx.early_fatal("library name must not be empty");
88+
}
89+
90+
native_lib
91+
}
92+
93+
/// Parses one of the comma-separated modifiers (prefixed by `+` or `-`), and
94+
/// modifies `native_lib` appropriately.
95+
///
96+
/// Exits with a fatal error if a malformed/unknown/inappropriate modifier is
97+
/// found.
98+
fn parse_and_apply_modifier(cx: &ParseNativeLibCx<'_>, modifier: &str, native_lib: &mut NativeLib) {
99+
let early_dcx = cx.early_dcx;
100+
101+
// Split off the leading `+` or `-` into a boolean value.
102+
let (modifier, value) = match modifier.split_at_checked(1) {
103+
Some(("+", m)) => (m, true),
104+
Some(("-", m)) => (m, false),
105+
_ => cx.early_dcx.early_fatal(
106+
"invalid linking modifier syntax, expected '+' or '-' prefix \
107+
before one of: bundle, verbatim, whole-archive, as-needed",
108+
),
109+
};
110+
111+
// Assigns the value (from `+` or `-`) to an empty `Option<bool>`, or emits
112+
// a fatal error if the option has already been set.
113+
let assign_modifier = |opt_bool: &mut Option<bool>| {
114+
if opt_bool.is_some() {
115+
let msg = format!("multiple `{modifier}` modifiers in a single `-l` option");
116+
early_dcx.early_fatal(msg)
117+
}
118+
*opt_bool = Some(value);
119+
};
120+
121+
// Check that the modifier is applicable to the native lib kind, and apply it.
122+
match (modifier, &mut native_lib.kind) {
123+
("bundle", NativeLibKind::Static { bundle, .. }) => assign_modifier(bundle),
124+
("bundle", _) => early_dcx
125+
.early_fatal("linking modifier `bundle` is only compatible with `static` linking kind"),
126+
127+
("verbatim", _) => assign_modifier(&mut native_lib.verbatim),
128+
129+
("whole-archive", NativeLibKind::Static { whole_archive, .. }) => {
130+
assign_modifier(whole_archive)
131+
}
132+
("whole-archive", _) => early_dcx.early_fatal(
133+
"linking modifier `whole-archive` is only compatible with `static` linking kind",
134+
),
135+
136+
("as-needed", NativeLibKind::Dylib { as_needed })
137+
| ("as-needed", NativeLibKind::Framework { as_needed }) => {
138+
cx.on_unstable_value(
139+
"linking modifier `as-needed` is unstable",
140+
", the `-Z unstable-options` flag must also be passed to use it",
141+
" and only accepted on the nightly compiler",
142+
);
143+
assign_modifier(as_needed)
144+
}
145+
("as-needed", _) => early_dcx.early_fatal(
146+
"linking modifier `as-needed` is only compatible with \
147+
`dylib` and `framework` linking kinds",
148+
),
149+
150+
_ => early_dcx.early_fatal(format!(
151+
"unknown linking modifier `{modifier}`, expected one \
152+
of: bundle, verbatim, whole-archive, as-needed"
153+
)),
154+
}
155+
}
156+
157+
#[derive(Debug, PartialEq, Eq)]
158+
struct NativeLibParts<'a> {
159+
kind: Option<&'a str>,
160+
modifiers: Option<&'a str>,
161+
name: &'a str,
162+
new_name: Option<&'a str>,
163+
}
164+
165+
/// Splits a string of the form `[KIND[:MODIFIERS]=]NAME[:NEW_NAME]` into those
166+
/// individual parts. This cannot fail, but the resulting strings require
167+
/// further validation.
168+
fn split_native_lib_value(value: &str) -> NativeLibParts<'_> {
169+
// Split the initial value into `[KIND=]NAME`.
170+
let name = value;
171+
let (kind, name) = match name.split_once('=') {
172+
Some((prefix, name)) => (Some(prefix), name),
173+
None => (None, name),
174+
};
175+
176+
// Split the kind part, if present, into `KIND[:MODIFIERS]`.
177+
let (kind, modifiers) = match kind {
178+
Some(kind) => match kind.split_once(':') {
179+
Some((kind, modifiers)) => (Some(kind), Some(modifiers)),
180+
None => (Some(kind), None),
181+
},
182+
None => (None, None),
183+
};
184+
185+
// Split the name part into `NAME[:NEW_NAME]`.
186+
let (name, new_name) = match name.split_once(':') {
187+
Some((name, new_name)) => (name, Some(new_name)),
188+
None => (name, None),
189+
};
190+
191+
NativeLibParts { kind, modifiers, name, new_name }
192+
}

0 commit comments

Comments
 (0)