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.3.3")]
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 /// The library function this builtin is, for the family where that is the whole answer.
115 ///
116 /// Empty for everything else. GCC's `__builtin_abort` is a call to `abort`, its
117 /// `__builtin_strlen` a call to `strlen`, and the prefix is there so that a program can
118 /// reach the function the C library promises even where its own name has been taken by a
119 /// macro or by a definition of its own. GCC folds some of these when the arguments allow
120 /// it, and folding is an optimization on top: the call is the meaning, and a compiler that
121 /// only ever emits the call is right and slow rather than wrong.
122 ///
123 /// The name is written out rather than worked out by stripping the prefix, because the two
124 /// are the same for every row here and need not be for the next one, and a table that says
125 /// what it means is worth more than one that saves thirty words.
126 pub library: &'static str,
127 /// What to do when it is met and is not implemented.
128 pub answer: Answer,
129 /// What `__has_c_attribute` answers with, which the standard fixes per attribute. One for
130 /// every other kind, where the operators answer one or nothing.
131 pub value: u32,
132 /// Projects known to need it, from the corpus in `spec/15-testing.md`.
133 pub used_by: &'static [&'static str],
134 /// The tests that prove the status, named as `crate::test` or as a file path.
135 pub tests: &'static [&'static str],
136 /// Anything a reader needs that the fields above do not say.
137 pub notes: &'static str,
138}
139
140include!(concat!(env!("OUT_DIR"), "/features.rs"));
141
142/// The whole matrix, sorted by kind and then by name.
143pub fn features() -> &'static [Feature] {
144 FEATURES
145}
146
147/// The row for a name, if the matrix has one.
148///
149/// The `__x__` spelling is the same question as `x`, because that is how a header writes an
150/// attribute name that a macro might otherwise have taken.
151pub fn lookup(kind: Kind, name: &str) -> Option<&'static Feature> {
152 let bare = unarmour(name);
153 let at = FEATURES.binary_search_by(|f| f.kind.cmp(&kind).then_with(|| f.name.cmp(bare)));
154 at.ok().map(|at| &FEATURES[at])
155}
156
157/// What `__has_attribute(name)` answers.
158pub fn has_attribute(name: &str) -> u32 {
159 answer(Kind::Attribute, name)
160}
161
162/// What `__has_c_attribute(name)` answers, which is the number the standard gives the
163/// attribute rather than one.
164pub fn has_c_attribute(name: &str) -> u32 {
165 answer(Kind::CAttribute, name)
166}
167
168/// What `__has_builtin(name)` answers.
169pub fn has_builtin(name: &str) -> u32 {
170 answer(Kind::Builtin, name)
171}
172
173/// What `__has_feature(name)` answers.
174pub fn has_feature(name: &str) -> u32 {
175 answer(Kind::Feature, name)
176}
177
178/// What `__has_extension(name)` answers.
179///
180/// GCC treats the two as the same question and so do we: a feature that is available is
181/// available whether or not the mode it is asked in makes it standard.
182pub fn has_extension(name: &str) -> u32 {
183 let extension = answer(Kind::Extension, name);
184 if extension == 0 { answer(Kind::Feature, name) } else { extension }
185}
186
187fn answer(kind: Kind, name: &str) -> u32 {
188 match lookup(kind, name) {
189 Some(feature) if feature.status.is_available() => feature.value,
190 _ => 0,
191 }
192}
193
194/// `__packed__` and `packed` are the same attribute.
195fn unarmour(name: &str) -> &str {
196 let bare = name.strip_prefix("__").and_then(|n| n.strip_suffix("__"));
197 match bare {
198 // `__builtin_x` and the atomics keep their prefix, because it is part of the name
199 // rather than armour around it.
200 Some(bare) if !bare.is_empty() && !name.starts_with("__builtin") => bare,
201 _ => name,
202 }
203}
204
205/// The milestone in `spec/17-milestones.md` that fills this crate in.
206pub const MILESTONE: &str = "M1";
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211
212 #[test]
213 fn the_table_is_sorted_so_the_lookup_can_be_a_search() {
214 let keys: Vec<(Kind, &str)> = FEATURES.iter().map(|f| (f.kind, f.name)).collect();
215 let mut sorted = keys.clone();
216 sorted.sort_unstable();
217 assert_eq!(keys, sorted);
218 }
219
220 #[test]
221 fn every_row_is_findable_by_its_own_name() {
222 for feature in FEATURES {
223 assert_eq!(lookup(feature.kind, feature.name), Some(feature));
224 }
225 }
226
227 #[test]
228 fn a_name_that_is_not_in_the_matrix_answers_no() {
229 assert_eq!(has_attribute("nonesuch"), 0);
230 assert_eq!(has_builtin("__builtin_nonesuch"), 0);
231 assert_eq!(has_feature("nonesuch"), 0);
232 assert_eq!(lookup(Kind::Attribute, "nonesuch"), None);
233 }
234
235 #[test]
236 fn the_armoured_spelling_is_the_same_question() {
237 assert_eq!(lookup(Kind::Attribute, "__packed__").map(|f| f.name), Some("packed"));
238 assert_eq!(lookup(Kind::Attribute, "packed").map(|f| f.name), Some("packed"));
239 assert_eq!(lookup(Kind::Attribute, "__packed"), None, "half the armour is not a name");
240 }
241
242 #[test]
243 fn a_builtin_keeps_the_prefix_that_is_part_of_its_name() {
244 assert!(lookup(Kind::Builtin, "__builtin_expect").is_some());
245 assert_eq!(lookup(Kind::Builtin, "expect"), None);
246 }
247
248 #[test]
249 fn only_an_implemented_row_answers_yes() {
250 for feature in FEATURES {
251 let answered = answer(feature.kind, feature.name);
252 assert_eq!(
253 answered != 0,
254 feature.status == Status::Implemented,
255 "{} answered {answered} at status {:?}",
256 feature.name,
257 feature.status
258 );
259 }
260 }
261
262 #[test]
263 fn an_implemented_row_names_a_test() {
264 // build.rs enforces this too. It is here as well because the build script failing is
265 // a harder message to read than a failing test.
266 for feature in FEATURES {
267 if feature.status == Status::Implemented {
268 assert!(!feature.tests.is_empty(), "{} claims to be implemented", feature.name);
269 }
270 }
271 }
272
273 #[test]
274 fn a_library_builtin_names_the_function_it_is_and_the_type_to_call_it_with() {
275 let abort = lookup(Kind::Builtin, "__builtin_abort").expect("in the table");
276 assert_eq!(abort.library, "abort");
277 assert_eq!(abort.signature, "void(void)");
278 for feature in FEATURES {
279 if feature.library.is_empty() {
280 continue;
281 }
282 assert_eq!(feature.kind, Kind::Builtin, "{} is not a builtin", feature.name);
283 assert!(!feature.signature.is_empty(), "{} has no type to call with", feature.name);
284 }
285 }
286
287 /// Every one of them so far is the name with the prefix taken off, which is the rule GCC
288 /// documents. The field is written out anyway, so this is what checks the two agree.
289 #[test]
290 fn the_library_function_is_the_name_without_the_prefix() {
291 for feature in FEATURES {
292 if feature.library.is_empty() {
293 continue;
294 }
295 let bare = feature.name.strip_prefix("__builtin_");
296 assert_eq!(bare, Some(feature.library), "{} names something else", feature.name);
297 }
298 }
299
300 #[test]
301 fn a_c_attribute_answers_with_the_number_the_standard_gives_it() {
302 let deprecated = lookup(Kind::CAttribute, "deprecated").expect("C23 has it");
303 assert_eq!(deprecated.value, 201904);
304 // And it is a different row from the GNU attribute of the same name.
305 let gnu = lookup(Kind::Attribute, "deprecated").expect("GCC has it too");
306 assert_eq!(gnu.value, 1);
307 }
308
309 #[test]
310 fn ignoring_an_attribute_silently_is_a_decision_the_table_records() {
311 let packed = lookup(Kind::Attribute, "packed").expect("in the table");
312 assert_eq!(packed.answer, Answer::Error, "ignoring it would produce wrong code");
313 let cold = lookup(Kind::Attribute, "cold").expect("in the table");
314 assert_eq!(cold.answer, Answer::Warn, "ignoring it would only produce slow code");
315 }
316
317 #[test]
318 fn nested_functions_are_rejected_rather_than_pending() {
319 let nested = lookup(Kind::Extension, "nested_functions").expect("in the table");
320 assert_eq!(nested.status, Status::Rejected);
321 assert!(!nested.notes.is_empty(), "a rejection has to say why");
322 }
323
324 #[test]
325 fn milestone_is_recorded() {
326 assert!(MILESTONE.starts_with('M'));
327 }
328}