rustc_attr_parsing/attributes/
stability.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
//! Parsing and validation of builtin attributes

use std::num::NonZero;

use rustc_ast::MetaItem;
use rustc_ast::attr::AttributeExt;
use rustc_ast_pretty::pprust;
use rustc_attr_data_structures::{
    ConstStability, DefaultBodyStability, Stability, StabilityLevel, StableSince, UnstableReason,
    VERSION_PLACEHOLDER,
};
use rustc_errors::ErrorGuaranteed;
use rustc_session::Session;
use rustc_span::{Span, Symbol, sym};

use crate::attributes::util::UnsupportedLiteralReason;
use crate::{parse_version, session_diagnostics};

/// Collects stability info from `stable`/`unstable`/`rustc_allowed_through_unstable_modules`
/// attributes in `attrs`. Returns `None` if no stability attributes are found.
pub fn find_stability(
    sess: &Session,
    attrs: &[impl AttributeExt],
    item_sp: Span,
) -> Option<(Stability, Span)> {
    let mut stab: Option<(Stability, Span)> = None;
    let mut allowed_through_unstable_modules = false;

    for attr in attrs {
        match attr.name_or_empty() {
            sym::rustc_allowed_through_unstable_modules => allowed_through_unstable_modules = true,
            sym::unstable => {
                if stab.is_some() {
                    sess.dcx().emit_err(session_diagnostics::MultipleStabilityLevels {
                        span: attr.span(),
                    });
                    break;
                }

                if let Some((feature, level)) = parse_unstability(sess, attr) {
                    stab = Some((Stability { level, feature }, attr.span()));
                }
            }
            sym::stable => {
                if stab.is_some() {
                    sess.dcx().emit_err(session_diagnostics::MultipleStabilityLevels {
                        span: attr.span(),
                    });
                    break;
                }
                if let Some((feature, level)) = parse_stability(sess, attr) {
                    stab = Some((Stability { level, feature }, attr.span()));
                }
            }
            _ => {}
        }
    }

    if allowed_through_unstable_modules {
        match &mut stab {
            Some((
                Stability {
                    level: StabilityLevel::Stable { allowed_through_unstable_modules, .. },
                    ..
                },
                _,
            )) => *allowed_through_unstable_modules = true,
            _ => {
                sess.dcx()
                    .emit_err(session_diagnostics::RustcAllowedUnstablePairing { span: item_sp });
            }
        }
    }

    stab
}

/// Collects stability info from `rustc_const_stable`/`rustc_const_unstable`/`rustc_promotable`
/// attributes in `attrs`. Returns `None` if no stability attributes are found.
pub fn find_const_stability(
    sess: &Session,
    attrs: &[impl AttributeExt],
    item_sp: Span,
) -> Option<(ConstStability, Span)> {
    let mut const_stab: Option<(ConstStability, Span)> = None;
    let mut promotable = false;
    let mut const_stable_indirect = false;

    for attr in attrs {
        match attr.name_or_empty() {
            sym::rustc_promotable => promotable = true,
            sym::rustc_const_stable_indirect => const_stable_indirect = true,
            sym::rustc_const_unstable => {
                if const_stab.is_some() {
                    sess.dcx().emit_err(session_diagnostics::MultipleStabilityLevels {
                        span: attr.span(),
                    });
                    break;
                }

                if let Some((feature, level)) = parse_unstability(sess, attr) {
                    const_stab = Some((
                        ConstStability {
                            level,
                            feature,
                            const_stable_indirect: false,
                            promotable: false,
                        },
                        attr.span(),
                    ));
                }
            }
            sym::rustc_const_stable => {
                if const_stab.is_some() {
                    sess.dcx().emit_err(session_diagnostics::MultipleStabilityLevels {
                        span: attr.span(),
                    });
                    break;
                }
                if let Some((feature, level)) = parse_stability(sess, attr) {
                    const_stab = Some((
                        ConstStability {
                            level,
                            feature,
                            const_stable_indirect: false,
                            promotable: false,
                        },
                        attr.span(),
                    ));
                }
            }
            _ => {}
        }
    }

    // Merge promotable and const_stable_indirect into stability info
    if promotable {
        match &mut const_stab {
            Some((stab, _)) => stab.promotable = promotable,
            _ => {
                _ = sess
                    .dcx()
                    .emit_err(session_diagnostics::RustcPromotablePairing { span: item_sp })
            }
        }
    }
    if const_stable_indirect {
        match &mut const_stab {
            Some((stab, _)) => {
                if stab.is_const_unstable() {
                    stab.const_stable_indirect = true;
                } else {
                    _ = sess.dcx().emit_err(session_diagnostics::RustcConstStableIndirectPairing {
                        span: item_sp,
                    })
                }
            }
            _ => {
                // This function has no const stability attribute, but has `const_stable_indirect`.
                // We ignore that; unmarked functions are subject to recursive const stability
                // checks by default so we do carry out the user's intent.
            }
        }
    }

    const_stab
}

/// Calculates the const stability for a const function in a `-Zforce-unstable-if-unmarked` crate
/// without the `staged_api` feature.
pub fn unmarked_crate_const_stab(
    _sess: &Session,
    attrs: &[impl AttributeExt],
    regular_stab: Stability,
) -> ConstStability {
    assert!(regular_stab.level.is_unstable());
    // The only attribute that matters here is `rustc_const_stable_indirect`.
    // We enforce recursive const stability rules for those functions.
    let const_stable_indirect =
        attrs.iter().any(|a| a.name_or_empty() == sym::rustc_const_stable_indirect);
    ConstStability {
        feature: regular_stab.feature,
        const_stable_indirect,
        promotable: false,
        level: regular_stab.level,
    }
}

/// Collects stability info from `rustc_default_body_unstable` attributes in `attrs`.
/// Returns `None` if no stability attributes are found.
pub fn find_body_stability(
    sess: &Session,
    attrs: &[impl AttributeExt],
) -> Option<(DefaultBodyStability, Span)> {
    let mut body_stab: Option<(DefaultBodyStability, Span)> = None;

    for attr in attrs {
        if attr.has_name(sym::rustc_default_body_unstable) {
            if body_stab.is_some() {
                sess.dcx()
                    .emit_err(session_diagnostics::MultipleStabilityLevels { span: attr.span() });
                break;
            }

            if let Some((feature, level)) = parse_unstability(sess, attr) {
                body_stab = Some((DefaultBodyStability { level, feature }, attr.span()));
            }
        }
    }

    body_stab
}

fn insert_or_error(sess: &Session, meta: &MetaItem, item: &mut Option<Symbol>) -> Option<()> {
    if item.is_some() {
        sess.dcx().emit_err(session_diagnostics::MultipleItem {
            span: meta.span,
            item: pprust::path_to_string(&meta.path),
        });
        None
    } else if let Some(v) = meta.value_str() {
        *item = Some(v);
        Some(())
    } else {
        sess.dcx().emit_err(session_diagnostics::IncorrectMetaItem { span: meta.span });
        None
    }
}

/// Read the content of a `stable`/`rustc_const_stable` attribute, and return the feature name and
/// its stability information.
fn parse_stability(sess: &Session, attr: &impl AttributeExt) -> Option<(Symbol, StabilityLevel)> {
    let metas = attr.meta_item_list()?;

    let mut feature = None;
    let mut since = None;
    for meta in metas {
        let Some(mi) = meta.meta_item() else {
            sess.dcx().emit_err(session_diagnostics::UnsupportedLiteral {
                span: meta.span(),
                reason: UnsupportedLiteralReason::Generic,
                is_bytestr: false,
                start_point_span: sess.source_map().start_point(meta.span()),
            });
            return None;
        };

        match mi.name_or_empty() {
            sym::feature => insert_or_error(sess, mi, &mut feature)?,
            sym::since => insert_or_error(sess, mi, &mut since)?,
            _ => {
                sess.dcx().emit_err(session_diagnostics::UnknownMetaItem {
                    span: meta.span(),
                    item: pprust::path_to_string(&mi.path),
                    expected: &["feature", "since"],
                });
                return None;
            }
        }
    }

    let feature = match feature {
        Some(feature) if rustc_lexer::is_ident(feature.as_str()) => Ok(feature),
        Some(_bad_feature) => {
            Err(sess.dcx().emit_err(session_diagnostics::NonIdentFeature { span: attr.span() }))
        }
        None => Err(sess.dcx().emit_err(session_diagnostics::MissingFeature { span: attr.span() })),
    };

    let since = if let Some(since) = since {
        if since.as_str() == VERSION_PLACEHOLDER {
            StableSince::Current
        } else if let Some(version) = parse_version(since) {
            StableSince::Version(version)
        } else {
            sess.dcx().emit_err(session_diagnostics::InvalidSince { span: attr.span() });
            StableSince::Err
        }
    } else {
        sess.dcx().emit_err(session_diagnostics::MissingSince { span: attr.span() });
        StableSince::Err
    };

    match feature {
        Ok(feature) => {
            let level = StabilityLevel::Stable { since, allowed_through_unstable_modules: false };
            Some((feature, level))
        }
        Err(ErrorGuaranteed { .. }) => None,
    }
}

/// Read the content of a `unstable`/`rustc_const_unstable`/`rustc_default_body_unstable`
/// attribute, and return the feature name and its stability information.
fn parse_unstability(sess: &Session, attr: &impl AttributeExt) -> Option<(Symbol, StabilityLevel)> {
    let metas = attr.meta_item_list()?;

    let mut feature = None;
    let mut reason = None;
    let mut issue = None;
    let mut issue_num = None;
    let mut is_soft = false;
    let mut implied_by = None;
    for meta in metas {
        let Some(mi) = meta.meta_item() else {
            sess.dcx().emit_err(session_diagnostics::UnsupportedLiteral {
                span: meta.span(),
                reason: UnsupportedLiteralReason::Generic,
                is_bytestr: false,
                start_point_span: sess.source_map().start_point(meta.span()),
            });
            return None;
        };

        match mi.name_or_empty() {
            sym::feature => insert_or_error(sess, mi, &mut feature)?,
            sym::reason => insert_or_error(sess, mi, &mut reason)?,
            sym::issue => {
                insert_or_error(sess, mi, &mut issue)?;

                // These unwraps are safe because `insert_or_error` ensures the meta item
                // is a name/value pair string literal.
                issue_num = match issue.unwrap().as_str() {
                    "none" => None,
                    issue => match issue.parse::<NonZero<u32>>() {
                        Ok(num) => Some(num),
                        Err(err) => {
                            sess.dcx().emit_err(
                                session_diagnostics::InvalidIssueString {
                                    span: mi.span,
                                    cause: session_diagnostics::InvalidIssueStringCause::from_int_error_kind(
                                        mi.name_value_literal_span().unwrap(),
                                        err.kind(),
                                    ),
                                },
                            );
                            return None;
                        }
                    },
                };
            }
            sym::soft => {
                if !mi.is_word() {
                    sess.dcx().emit_err(session_diagnostics::SoftNoArgs { span: mi.span });
                }
                is_soft = true;
            }
            sym::implied_by => insert_or_error(sess, mi, &mut implied_by)?,
            _ => {
                sess.dcx().emit_err(session_diagnostics::UnknownMetaItem {
                    span: meta.span(),
                    item: pprust::path_to_string(&mi.path),
                    expected: &["feature", "reason", "issue", "soft", "implied_by"],
                });
                return None;
            }
        }
    }

    let feature = match feature {
        Some(feature) if rustc_lexer::is_ident(feature.as_str()) => Ok(feature),
        Some(_bad_feature) => {
            Err(sess.dcx().emit_err(session_diagnostics::NonIdentFeature { span: attr.span() }))
        }
        None => Err(sess.dcx().emit_err(session_diagnostics::MissingFeature { span: attr.span() })),
    };

    let issue = issue.ok_or_else(|| {
        sess.dcx().emit_err(session_diagnostics::MissingIssue { span: attr.span() })
    });

    match (feature, issue) {
        (Ok(feature), Ok(_)) => {
            let level = StabilityLevel::Unstable {
                reason: UnstableReason::from_opt_reason(reason),
                issue: issue_num,
                is_soft,
                implied_by,
            };
            Some((feature, level))
        }
        (Err(ErrorGuaranteed { .. }), _) | (_, Err(ErrorGuaranteed { .. })) => None,
    }
}