tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

538 lignes · 17705 octetsBrut · Historique
1//! A parser for the declarations of a C header that bindings can use.
2//!
3//! It is not a C parser: it reads a header as a sequence of top-level
4//! declarations ended by `;` (or by a body in braces), after removing
5//! comments and preprocessor lines, and recognises a few shapes. Anything
6//! else becomes an [`Item::Other`], which the generator reports as
7//! skipped. Macros are not expanded, so a declaration that relies on one
8//! (`API int f(void);`) is not recognised.
9
10/// A token of the header, with its line (1-based).
11#[derive(Clone, Debug, PartialEq)]
12struct Token {
13 text: String,
14 line: u32,
15}
16
17/// The type of a parameter or result, as written.
18#[derive(Clone, Debug, PartialEq)]
19pub enum TypeSyntax {
20 /// Specifier words (`unsigned`, `long`, `struct`, `sk_vec`, ...),
21 /// `const` and `volatile` left out, then the number of `*`.
22 Plain {
23 words: Vec<String>,
24 is_const: bool,
25 pointers: usize,
26 },
27 /// `ret (*name)(params)`: a function pointer.
28 FnPointer(Box<Signature>),
29 /// Something else (an array, a pointer to a function pointer, ...).
30 Unsupported(String),
31}
32
33#[derive(Clone, Debug, PartialEq)]
34pub struct Param {
35 pub name: Option<String>,
36 pub ty: TypeSyntax,
37}
38
39/// A function's or function pointer's parameters and result.
40#[derive(Clone, Debug, PartialEq)]
41pub struct Signature {
42 pub ret: TypeSyntax,
43 pub params: Vec<Param>,
44 pub variadic: bool,
45}
46
47#[derive(Clone, Debug, PartialEq)]
48pub enum Item {
49 /// `ret name(params);`
50 Function { name: String, sig: Signature },
51 /// `struct name;`, or `typedef struct name alias;` (`alias` set).
52 StructDecl { name: String, alias: Option<String> },
53 /// `struct name { ... }`, possibly in a typedef naming `alias`.
54 StructDef {
55 name: Option<String>,
56 alias: Option<String>,
57 },
58 /// `typedef ret (*name)(params);`
59 FnTypedef { name: String, sig: Signature },
60 /// `typedef type name;`
61 Typedef { name: String, ty: TypeSyntax },
62 /// Anything else: what it looks like.
63 Other(String),
64}
65
66/// A declaration and the line it starts on.
67#[derive(Clone, Debug, PartialEq)]
68pub struct Located {
69 pub line: u32,
70 pub item: Item,
71}
72
73/// The declarations of `header`, in order.
74pub fn parse(header: &str) -> Vec<Located> {
75 let tokens = tokenize(header);
76 let mut items = Vec::new();
77 let mut i = 0;
78 while i < tokens.len() {
79 // `extern "C" {` ... `}` wraps declarations in C++-aware headers.
80 if tokens[i].text == "extern"
81 && tokens.get(i + 1).is_some_and(|t| t.text == "\"C\"")
82 && tokens.get(i + 2).is_some_and(|t| t.text == "{")
83 {
84 i += 3;
85 continue;
86 }
87 if tokens[i].text == "}" || tokens[i].text == ";" {
88 i += 1;
89 continue;
90 }
91 let (end, has_body) = declaration_end(&tokens, i);
92 let line = tokens[i].line;
93 items.push(Located {
94 line,
95 item: classify(&tokens[i..end], has_body),
96 });
97 i = end;
98 }
99 items
100}
101
102/// Where the declaration starting at `start` ends (exclusive), and
103/// whether it has a body in braces.
104fn declaration_end(tokens: &[Token], start: usize) -> (usize, bool) {
105 let mut depth = 0usize;
106 let mut i = start;
107 let mut body = false;
108 while i < tokens.len() {
109 match tokens[i].text.as_str() {
110 "(" | "[" => depth += 1,
111 ")" | "]" => depth = depth.saturating_sub(1),
112 ";" if depth == 0 => return (i + 1, body),
113 "{" if depth == 0 => {
114 let open = i;
115 let mut braces = 0usize;
116 while i < tokens.len() {
117 match tokens[i].text.as_str() {
118 "{" => braces += 1,
119 "}" => {
120 braces -= 1;
121 if braces == 0 {
122 break;
123 }
124 }
125 _ => {}
126 }
127 i += 1;
128 }
129 body = true;
130 // A function definition ends with its body; a struct,
131 // union or enum definition continues to its `;`.
132 if tokens[start..open].iter().any(|t| t.text == "(") {
133 return (i + 1, body);
134 }
135 }
136 _ => {}
137 }
138 i += 1;
139 }
140 (tokens.len(), body)
141}
142
143fn texts(tokens: &[Token]) -> Vec<&str> {
144 tokens.iter().map(|t| t.text.as_str()).collect()
145}
146
147fn is_ident(s: &str) -> bool {
148 s.chars()
149 .next()
150 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
151 && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
152}
153
154fn classify(decl: &[Token], has_body: bool) -> Item {
155 let words = texts(decl);
156 let shown = summary(&words);
157 if has_body {
158 return classify_with_body(&words, shown);
159 }
160 match words.as_slice() {
161 ["struct", name, ";"] if is_ident(name) => Item::StructDecl {
162 name: (*name).into(),
163 alias: None,
164 },
165 ["typedef", "struct", name, alias, ";"] if is_ident(name) && is_ident(alias) => {
166 Item::StructDecl {
167 name: (*name).into(),
168 alias: Some((*alias).into()),
169 }
170 }
171 ["typedef", rest @ ..] => {
172 let rest = &rest[..rest.len().saturating_sub(1)];
173 match declarator(rest) {
174 Some((Some(name), TypeSyntax::FnPointer(sig))) => {
175 Item::FnTypedef { name, sig: *sig }
176 }
177 Some((Some(name), ty)) => Item::Typedef { name, ty },
178 _ => Item::Other(shown),
179 }
180 }
181 _ => function(&words).unwrap_or(Item::Other(shown)),
182 }
183}
184
185/// `struct s { ... };`, `typedef struct s { ... } t;`, or something else
186/// with a body (an enum, a function definition).
187fn classify_with_body(words: &[&str], shown: String) -> Item {
188 let open = words.iter().position(|w| *w == "{").unwrap_or(0);
189 let close = words.iter().rposition(|w| *w == "}").unwrap_or(words.len());
190 let head = &words[..open];
191 let tail: Vec<&str> = words[close + 1..]
192 .iter()
193 .copied()
194 .filter(|w| *w != ";")
195 .collect();
196 let (head, typedef) = match head {
197 ["typedef", rest @ ..] => (rest, true),
198 _ => (head, false),
199 };
200 match head {
201 ["struct"] | ["struct", _] => Item::StructDef {
202 name: head.get(1).map(|n| (*n).into()),
203 alias: match tail.as_slice() {
204 [alias] if typedef && is_ident(alias) => Some((*alias).into()),
205 _ => None,
206 },
207 },
208 _ => Item::Other(shown),
209 }
210}
211
212/// `[extern] ret name(params);`
213fn function(words: &[&str]) -> Option<Item> {
214 let words = match words {
215 ["extern", rest @ ..] => rest,
216 _ => words,
217 };
218 let words = &words[..words.len().checked_sub(1)?];
219 if words.last() != Some(&")") {
220 return None;
221 }
222 let open = words.iter().position(|w| *w == "(")?;
223 let name = *words.get(open.checked_sub(1)?)?;
224 if !is_ident(name) || open < 2 {
225 return None;
226 }
227 let ret = type_syntax(&words[..open - 1]);
228 let (params, variadic) = params(&words[open + 1..words.len() - 1])?;
229 Some(Item::Function {
230 name: name.into(),
231 sig: Signature {
232 ret,
233 params,
234 variadic,
235 },
236 })
237}
238
239/// The parameters between parentheses (`void` or nothing: none).
240fn params(words: &[&str]) -> Option<(Vec<Param>, bool)> {
241 if words.is_empty() || words == ["void"] {
242 return Some((Vec::new(), false));
243 }
244 let mut out = Vec::new();
245 let mut variadic = false;
246 for part in split_commas(words) {
247 if part == ["..."] {
248 variadic = true;
249 continue;
250 }
251 let (name, ty) = declarator(part)?;
252 out.push(Param { name, ty });
253 }
254 Some((out, variadic))
255}
256
257fn split_commas<'a>(words: &'a [&'a str]) -> Vec<&'a [&'a str]> {
258 let mut parts = Vec::new();
259 let (mut depth, mut start) = (0usize, 0);
260 for (i, w) in words.iter().enumerate() {
261 match *w {
262 "(" | "[" => depth += 1,
263 ")" | "]" => depth = depth.saturating_sub(1),
264 "," if depth == 0 => {
265 parts.push(&words[start..i]);
266 start = i + 1;
267 }
268 _ => {}
269 }
270 }
271 parts.push(&words[start..]);
272 parts
273}
274
275/// A type followed by an optional name: `const char *s`, `int`,
276/// `int (*cmp)(int, int)`.
277fn declarator(words: &[&str]) -> Option<(Option<String>, TypeSyntax)> {
278 if words.is_empty() {
279 return None;
280 }
281 // ret ( * name ) ( params )
282 if let Some(open) = words.iter().position(|w| *w == "(") {
283 let ret = type_syntax(&words[..open]);
284 let inner_end = open + 1 + words[open + 1..].iter().position(|w| *w == ")")?;
285 let inner = &words[open + 1..inner_end];
286 let name = match inner {
287 ["*"] => None,
288 ["*", name] if is_ident(name) => Some((*name).to_owned()),
289 _ => return Some((None, TypeSyntax::Unsupported(summary(words)))),
290 };
291 let rest = &words[inner_end + 1..];
292 if rest.first() != Some(&"(") || rest.last() != Some(&")") {
293 return Some((name, TypeSyntax::Unsupported(summary(words))));
294 }
295 let Some((params, variadic)) = params(&rest[1..rest.len() - 1]) else {
296 return Some((name, TypeSyntax::Unsupported(summary(words))));
297 };
298 let sig = Signature {
299 ret,
300 params,
301 variadic,
302 };
303 return Some((name, TypeSyntax::FnPointer(Box::new(sig))));
304 }
305 if words.contains(&"[") {
306 return Some((None, TypeSyntax::Unsupported(summary(words))));
307 }
308 // The name is a final identifier that is not a type word, after at
309 // least one type word: `int x`, `sk_vec *v`, but not `int`, `size_t`
310 // or `struct s`.
311 let last = *words.last()?;
312 let type_words = words
313 .iter()
314 .filter(|w| is_ident(w) && !QUALIFIERS.contains(w))
315 .count();
316 let tagged = words.len() >= 2 && ["struct", "union", "enum"].contains(&words[words.len() - 2]);
317 if is_ident(last) && type_words >= 2 && !BUILTIN_WORDS.contains(&last) && !tagged {
318 Some((
319 Some(last.to_owned()),
320 type_syntax(&words[..words.len() - 1]),
321 ))
322 } else {
323 Some((None, type_syntax(words)))
324 }
325}
326
327const QUALIFIERS: &[&str] = &["const", "volatile", "restrict", "__restrict", "extern"];
328
329/// Words that make up a type on their own, so they are never a name.
330const BUILTIN_WORDS: &[&str] = &[
331 "void", "char", "short", "int", "long", "float", "double", "signed", "unsigned", "_Bool",
332 "bool",
333];
334
335fn type_syntax(words: &[&str]) -> TypeSyntax {
336 let mut out = Vec::new();
337 let mut is_const = false;
338 let mut pointers = 0;
339 for w in words {
340 match *w {
341 "const" => {
342 // `const` after a `*` qualifies the pointer, not the
343 // pointee: only the pointee's matters here.
344 if pointers == 0 {
345 is_const = true;
346 }
347 }
348 "volatile" | "restrict" | "__restrict" | "extern" | "static" | "inline" => {}
349 "*" => pointers += 1,
350 w if is_ident(w) && pointers == 0 => out.push(w.to_owned()),
351 _ => return TypeSyntax::Unsupported(summary(words)),
352 }
353 }
354 if out.is_empty() {
355 return TypeSyntax::Unsupported(summary(words));
356 }
357 TypeSyntax::Plain {
358 words: out,
359 is_const,
360 pointers,
361 }
362}
363
364/// Tokens joined back into readable C.
365pub fn summary(words: &[&str]) -> String {
366 let mut s = String::new();
367 for (i, w) in words.iter().enumerate() {
368 let prev = if i == 0 { "" } else { words[i - 1] };
369 let glue = i == 0
370 || matches!(*w, "," | ")" | ";" | "(" | "[" | "]")
371 || prev == "("
372 || prev == "["
373 || (prev == "*" && *w != "const");
374 if !glue {
375 s.push(' ');
376 }
377 s.push_str(w);
378 }
379 s
380}
381
382/// Tokens of `text`, without comments and preprocessor lines.
383fn tokenize(text: &str) -> Vec<Token> {
384 let mut tokens = Vec::new();
385 let chars: Vec<char> = text.chars().collect();
386 let mut line = 1u32;
387 let mut i = 0;
388 let mut line_start = true;
389 while i < chars.len() {
390 let c = chars[i];
391 if c == '\n' {
392 line += 1;
393 line_start = true;
394 i += 1;
395 continue;
396 }
397 if c.is_whitespace() {
398 i += 1;
399 continue;
400 }
401 if line_start && c == '#' {
402 // A preprocessor line, with its `\` continuations.
403 while i < chars.len() && chars[i] != '\n' {
404 if chars[i] == '\\' && chars.get(i + 1) == Some(&'\n') {
405 line += 1;
406 i += 1;
407 }
408 i += 1;
409 }
410 continue;
411 }
412 line_start = false;
413 if c == '/' && chars.get(i + 1) == Some(&'/') {
414 while i < chars.len() && chars[i] != '\n' {
415 i += 1;
416 }
417 continue;
418 }
419 if c == '/' && chars.get(i + 1) == Some(&'*') {
420 i += 2;
421 while i < chars.len() && !(chars[i] == '*' && chars.get(i + 1) == Some(&'/')) {
422 if chars[i] == '\n' {
423 line += 1;
424 }
425 i += 1;
426 }
427 i += 2;
428 continue;
429 }
430 let start = i;
431 if c.is_ascii_alphanumeric() || c == '_' {
432 while i < chars.len() && (chars[i].is_ascii_alphanumeric() || chars[i] == '_') {
433 i += 1;
434 }
435 } else if c == '"' || c == '\'' {
436 i += 1;
437 while i < chars.len() && chars[i] != c {
438 if chars[i] == '\\' {
439 i += 1;
440 }
441 i += 1;
442 }
443 i += 1;
444 } else if c == '.' && chars.get(i + 1) == Some(&'.') && chars.get(i + 2) == Some(&'.') {
445 i += 3;
446 } else {
447 i += 1;
448 }
449 let end = i.min(chars.len());
450 tokens.push(Token {
451 text: chars[start..end].iter().collect(),
452 line,
453 });
454 }
455 tokens
456}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461
462 fn plain(words: &[&str], is_const: bool, pointers: usize) -> TypeSyntax {
463 TypeSyntax::Plain {
464 words: words.iter().map(|w| (*w).to_owned()).collect(),
465 is_const,
466 pointers,
467 }
468 }
469
470 #[test]
471 fn functions_and_parameters() {
472 let items = parse(
473 "/* doc */\n#include <stddef.h>\n#define X(a) \\\n (a)\nsize_t count(const char *s, size_t len, int c);\n",
474 );
475 assert_eq!(items.len(), 1);
476 assert_eq!(items[0].line, 5);
477 let Item::Function { name, sig } = &items[0].item else {
478 panic!("{items:?}");
479 };
480 assert_eq!(name, "count");
481 assert_eq!(sig.ret, plain(&["size_t"], false, 0));
482 assert_eq!(sig.params[0].ty, plain(&["char"], true, 1));
483 assert_eq!(sig.params[0].name.as_deref(), Some("s"));
484 assert_eq!(sig.params[2].ty, plain(&["int"], false, 0));
485 }
486
487 #[test]
488 fn unnamed_parameters_and_function_pointers() {
489 let items = parse("void each(struct v *, int (*f)(int64_t, void *), void *);");
490 let Item::Function { sig, .. } = &items[0].item else {
491 panic!("{items:?}");
492 };
493 assert_eq!(sig.params[0].name, None);
494 assert_eq!(sig.params[0].ty, plain(&["struct", "v"], false, 1));
495 assert_eq!(sig.params[1].name.as_deref(), Some("f"));
496 let TypeSyntax::FnPointer(f) = &sig.params[1].ty else {
497 panic!("{sig:?}");
498 };
499 assert_eq!(f.params[0].ty, plain(&["int64_t"], false, 0));
500 assert_eq!(f.params[1].ty, plain(&["void"], false, 1));
501 }
502
503 #[test]
504 fn structs_typedefs_and_others() {
505 let items = parse(
506 "extern \"C\" {\ntypedef struct v v;\nstruct w;\ntypedef struct s { int a; } s;\ntypedef int (*cmp)(int, int);\ntypedef long ssize;\nenum e { A, B };\nstatic inline int f(void) { return 1; }\nint g(void);\nextern int counter;\n}\n",
507 );
508 let kinds: Vec<&Item> = items.iter().map(|l| &l.item).collect();
509 assert_eq!(
510 kinds[0],
511 &Item::StructDecl {
512 name: "v".into(),
513 alias: Some("v".into())
514 }
515 );
516 assert_eq!(
517 kinds[1],
518 &Item::StructDecl {
519 name: "w".into(),
520 alias: None
521 }
522 );
523 assert_eq!(
524 kinds[2],
525 &Item::StructDef {
526 name: Some("s".into()),
527 alias: Some("s".into())
528 }
529 );
530 assert!(matches!(kinds[3], Item::FnTypedef { name, .. } if name == "cmp"));
531 assert!(matches!(kinds[4], Item::Typedef { name, .. } if name == "ssize"));
532 assert!(matches!(kinds[5], Item::Other(s) if s.starts_with("enum e")));
533 assert!(matches!(kinds[6], Item::Other(s) if s.starts_with("static inline int f")));
534 assert!(matches!(kinds[7], Item::Function { name, .. } if name == "g"));
535 assert!(matches!(kinds[8], Item::Other(s) if s == "extern int counter;"));
536 assert_eq!(items.len(), 9);
537 }
538}