rustc_session/config/
native_libs.rs

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