rucc_gnu/lib.rs
1//! The GNU compatibility surface: features.toml, attributes, builtins, pragmas.
2//!
3//! Design: `spec/13-gnu-compat.md`. Layer rank 4, see `spec/18-package-layout.md`.
4//!
5//! # Status
6//!
7//! The matrix is real. `features.toml` next to this file is the source of truth for what the
8//! compiler claims to support, `build.rs` turns it into the table below, and the `__has_*`
9//! family in the preprocessor answers out of it. The attributes and builtins themselves land
10//! with the parser, and every row that says `unimplemented` says so because it is.
11//!
12//! The rule that makes the table worth having is in section 13.2: answering `__has_builtin`
13//! untruthfully is worse than answering no, because a header that gets a yes and then fails
14//! to compile is much harder to diagnose than one that takes its fallback path. So only a row
15//! marked `implemented` answers yes, and a row marked `implemented` with no test named
16//! against it fails the build.
17//!
18//! ```
19//! use rucc_gnu::{Kind, Status};
20//!
21//! assert_eq!(rucc_gnu::has_feature("__has_include"), 1);
22//! assert_eq!(rucc_gnu::has_attribute("cleanup"), 0, "not until the parser lands");
23//! assert_eq!(rucc_gnu::has_attribute("no_such_attribute"), 0);
24//!
25//! // The armoured spelling is the same question.
26//! assert_eq!(rucc_gnu::lookup(Kind::Attribute, "__packed__").map(|f| f.name), Some("packed"));
27//!
28//! // Nested functions are refused rather than pending, and the table says which.
29//! let nested = rucc_gnu::lookup(Kind::Extension, "nested_functions").unwrap();
30//! assert_eq!(nested.status, Status::Rejected);
31//! ```
32//!
33//! Every crate in the workspace is published, and publishing implies a promise. This one is
34//! tier 3: its Rust API is explicitly unstable and will change without a major version bump.
35//! Depend on the `rucc` binary's behaviour, not on this.
36
37#![doc(html_root_url = "https://docs.rs/rucc-gnu/0.2.19")]
38
39/// What kind of thing a row of the matrix describes.
40///
41/// The kind is part of the identity of a row, because `deprecated` is both a GNU attribute
42/// and a C23 one and the two are answered by different operators with different values.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
44pub enum Kind {
45 /// `__attribute__((x))` and `[[gnu::x]]`, asked about with `__has_attribute`.
46 Attribute,
47 /// A standard `[[x]]` attribute, asked about with `__has_c_attribute`.
48 CAttribute,
49 /// `__builtin_x`, asked about with `__has_builtin`.
50 Builtin,
51 /// A language or preprocessor feature, asked about with `__has_feature`.
52 Feature,
53 /// A GNU extension to the language, asked about with `__has_extension`.
54 Extension,
55}
56
57/// How far along a row is.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
59pub enum Status {
60 /// Recognised and not done. The `__has_*` operators answer no.
61 Unimplemented,
62 /// Some of it works. The `__has_*` operators still answer no, because a feature that
63 /// works most of the time is exactly the case where the fallback path is the safer one.
64 Partial,
65 /// Done, with a test named against it.
66 Implemented,
67 /// Will not be done, and the row says why. `nested_functions` is the example.
68 Rejected,
69}
70
71impl Status {
72 /// Whether the `__has_*` family answers yes for a row at this status.
73 pub const fn is_available(self) -> bool {
74 matches!(self, Status::Implemented)
75 }
76}
77
78/// What happens when the compiler meets something this row describes and cannot do it.
79#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
80pub enum Answer {
81 /// Warn and carry on, which is what GCC does for an attribute it does not know. Ignoring
82 /// `hot` produces slower code and nothing worse.
83 Warn,
84 /// Refuse. Ignoring `packed`, `aligned`, `section`, `no_sanitize` or `naked` produces
85 /// wrong code rather than slow code, and wrong code that compiles is the worst outcome
86 /// available. This is section 13.4's rule.
87 Error,
88}
89
90/// One row of the matrix.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub struct Feature {
93 /// The spelling asked about, with no `__` armour on it.
94 pub name: &'static str,
95 /// Which operator answers for it.
96 pub kind: Kind,
97 /// The GCC release that introduced it.
98 pub gcc_version: &'static str,
99 /// How far along it is.
100 pub status: Status,
101 /// The type a builtin has, written as a C prototype without the name, or empty.
102 ///
103 /// Empty for everything that is not a builtin, and for a builtin whose type depends on
104 /// what it is handed: `__builtin_constant_p` takes anything, `__builtin_add_overflow`
105 /// takes three types that have to agree, and the atomics are a family rather than a
106 /// function. Those are decided where the arguments are, and a fixed type here would be a
107 /// worse answer than none.
108 ///
109 /// It is a string rather than a structure because `size_t` is a different type on two
110 /// targets and this table has no target. The compiler reads it once per builtin it is
111 /// asked for. The set of words it may use is fixed and `build.rs` checks it, so a typo
112 /// fails this crate's build rather than the compile of whoever first calls the builtin.
113 pub signature: &'static str,
114 /// What to do when it is met and is not implemented.
115 pub answer: Answer,
116 /// What `__has_c_attribute` answers with, which the standard fixes per attribute. One for
117 /// every other kind, where the operators answer one or nothing.
118 pub value: u32,
119 /// Projects known to need it, from the corpus in `spec/15-testing.md`.
120 pub used_by: &'static [&'static str],
121 /// The tests that prove the status, named as `crate::test` or as a file path.
122 pub tests: &'static [&'static str],
123 /// Anything a reader needs that the fields above do not say.
124 pub notes: &'static str,
125}
126
127include!(concat!(env!("OUT_DIR"), "/features.rs"));
128
129/// The whole matrix, sorted by kind and then by name.
130pub fn features() -> &'static [Feature] {
131 FEATURES
132}
133
134/// The row for a name, if the matrix has one.
135///
136/// The `__x__` spelling is the same question as `x`, because that is how a header writes an
137/// attribute name that a macro might otherwise have taken.
138pub fn lookup(kind: Kind, name: &str) -> Option<&'static Feature> {
139 let bare = unarmour(name);
140 let at = FEATURES.binary_search_by(|f| f.kind.cmp(&kind).then_with(|| f.name.cmp(bare)));
141 at.ok().map(|at| &FEATURES[at])
142}
143
144/// What `__has_attribute(name)` answers.
145pub fn has_attribute(name: &str) -> u32 {
146 answer(Kind::Attribute, name)
147}
148
149/// What `__has_c_attribute(name)` answers, which is the number the standard gives the
150/// attribute rather than one.
151pub fn has_c_attribute(name: &str) -> u32 {
152 answer(Kind::CAttribute, name)
153}
154
155/// What `__has_builtin(name)` answers.
156pub fn has_builtin(name: &str) -> u32 {
157 answer(Kind::Builtin, name)
158}
159
160/// What `__has_feature(name)` answers.
161pub fn has_feature(name: &str) -> u32 {
162 answer(Kind::Feature, name)
163}
164
165/// What `__has_extension(name)` answers.
166///
167/// GCC treats the two as the same question and so do we: a feature that is available is
168/// available whether or not the mode it is asked in makes it standard.
169pub fn has_extension(name: &str) -> u32 {
170 let extension = answer(Kind::Extension, name);
171 if extension == 0 { answer(Kind::Feature, name) } else { extension }
172}
173
174fn answer(kind: Kind, name: &str) -> u32 {
175 match lookup(kind, name) {
176 Some(feature) if feature.status.is_available() => feature.value,
177 _ => 0,
178 }
179}
180
181/// `__packed__` and `packed` are the same attribute.
182fn unarmour(name: &str) -> &str {
183 let bare = name.strip_prefix("__").and_then(|n| n.strip_suffix("__"));
184 match bare {
185 // `__builtin_x` and the atomics keep their prefix, because it is part of the name
186 // rather than armour around it.
187 Some(bare) if !bare.is_empty() && !name.starts_with("__builtin") => bare,
188 _ => name,
189 }
190}
191
192/// The milestone in `spec/17-milestones.md` that fills this crate in.
193pub const MILESTONE: &str = "M1";
194
195#[cfg(test)]
196mod tests {
197 use super::*;
198
199 #[test]
200 fn the_table_is_sorted_so_the_lookup_can_be_a_search() {
201 let keys: Vec<(Kind, &str)> = FEATURES.iter().map(|f| (f.kind, f.name)).collect();
202 let mut sorted = keys.clone();
203 sorted.sort_unstable();
204 assert_eq!(keys, sorted);
205 }
206
207 #[test]
208 fn every_row_is_findable_by_its_own_name() {
209 for feature in FEATURES {
210 assert_eq!(lookup(feature.kind, feature.name), Some(feature));
211 }
212 }
213
214 #[test]
215 fn a_name_that_is_not_in_the_matrix_answers_no() {
216 assert_eq!(has_attribute("nonesuch"), 0);
217 assert_eq!(has_builtin("__builtin_nonesuch"), 0);
218 assert_eq!(has_feature("nonesuch"), 0);
219 assert_eq!(lookup(Kind::Attribute, "nonesuch"), None);
220 }
221
222 #[test]
223 fn the_armoured_spelling_is_the_same_question() {
224 assert_eq!(lookup(Kind::Attribute, "__packed__").map(|f| f.name), Some("packed"));
225 assert_eq!(lookup(Kind::Attribute, "packed").map(|f| f.name), Some("packed"));
226 assert_eq!(lookup(Kind::Attribute, "__packed"), None, "half the armour is not a name");
227 }
228
229 #[test]
230 fn a_builtin_keeps_the_prefix_that_is_part_of_its_name() {
231 assert!(lookup(Kind::Builtin, "__builtin_expect").is_some());
232 assert_eq!(lookup(Kind::Builtin, "expect"), None);
233 }
234
235 #[test]
236 fn only_an_implemented_row_answers_yes() {
237 for feature in FEATURES {
238 let answered = answer(feature.kind, feature.name);
239 assert_eq!(
240 answered != 0,
241 feature.status == Status::Implemented,
242 "{} answered {answered} at status {:?}",
243 feature.name,
244 feature.status
245 );
246 }
247 }
248
249 #[test]
250 fn an_implemented_row_names_a_test() {
251 // build.rs enforces this too. It is here as well because the build script failing is
252 // a harder message to read than a failing test.
253 for feature in FEATURES {
254 if feature.status == Status::Implemented {
255 assert!(!feature.tests.is_empty(), "{} claims to be implemented", feature.name);
256 }
257 }
258 }
259
260 #[test]
261 fn a_c_attribute_answers_with_the_number_the_standard_gives_it() {
262 let deprecated = lookup(Kind::CAttribute, "deprecated").expect("C23 has it");
263 assert_eq!(deprecated.value, 201904);
264 // And it is a different row from the GNU attribute of the same name.
265 let gnu = lookup(Kind::Attribute, "deprecated").expect("GCC has it too");
266 assert_eq!(gnu.value, 1);
267 }
268
269 #[test]
270 fn ignoring_an_attribute_silently_is_a_decision_the_table_records() {
271 let packed = lookup(Kind::Attribute, "packed").expect("in the table");
272 assert_eq!(packed.answer, Answer::Error, "ignoring it would produce wrong code");
273 let cold = lookup(Kind::Attribute, "cold").expect("in the table");
274 assert_eq!(cold.answer, Answer::Warn, "ignoring it would only produce slow code");
275 }
276
277 #[test]
278 fn nested_functions_are_rejected_rather_than_pending() {
279 let nested = lookup(Kind::Extension, "nested_functions").expect("in the table");
280 assert_eq!(nested.status, Status::Rejected);
281 assert!(!nested.notes.is_empty(), "a rejection has to say why");
282 }
283
284 #[test]
285 fn milestone_is_recorded() {
286 assert!(MILESTONE.starts_with('M'));
287 }
288}