//! A parser for the declarations of a C header that bindings can use. //! //! It is not a C parser: it reads a header as a sequence of top-level //! declarations ended by `;` (or by a body in braces), after removing //! comments and preprocessor lines, and recognises a few shapes. Anything //! else becomes an [`Item::Other`], which the generator reports as //! skipped. Macros are not expanded, so a declaration that relies on one //! (`API int f(void);`) is not recognised. /// A token of the header, with its line (1-based). #[derive(Clone, Debug, PartialEq)] struct Token { text: String, line: u32, } /// The type of a parameter or result, as written. #[derive(Clone, Debug, PartialEq)] pub enum TypeSyntax { /// Specifier words (`unsigned`, `long`, `struct`, `sk_vec`, ...), /// `const` and `volatile` left out, then the number of `*`. Plain { words: Vec, is_const: bool, pointers: usize, }, /// `ret (*name)(params)`: a function pointer. FnPointer(Box), /// Something else (an array, a pointer to a function pointer, ...). Unsupported(String), } #[derive(Clone, Debug, PartialEq)] pub struct Param { pub name: Option, pub ty: TypeSyntax, } /// A function's or function pointer's parameters and result. #[derive(Clone, Debug, PartialEq)] pub struct Signature { pub ret: TypeSyntax, pub params: Vec, pub variadic: bool, } #[derive(Clone, Debug, PartialEq)] pub enum Item { /// `ret name(params);` Function { name: String, sig: Signature }, /// `struct name;`, or `typedef struct name alias;` (`alias` set). StructDecl { name: String, alias: Option }, /// `struct name { ... }`, possibly in a typedef naming `alias`. StructDef { name: Option, alias: Option, }, /// `typedef ret (*name)(params);` FnTypedef { name: String, sig: Signature }, /// `typedef type name;` Typedef { name: String, ty: TypeSyntax }, /// Anything else: what it looks like. Other(String), } /// A declaration and the line it starts on. #[derive(Clone, Debug, PartialEq)] pub struct Located { pub line: u32, pub item: Item, } /// The declarations of `header`, in order. pub fn parse(header: &str) -> Vec { let tokens = tokenize(header); let mut items = Vec::new(); let mut i = 0; while i < tokens.len() { // `extern "C" {` ... `}` wraps declarations in C++-aware headers. if tokens[i].text == "extern" && tokens.get(i + 1).is_some_and(|t| t.text == "\"C\"") && tokens.get(i + 2).is_some_and(|t| t.text == "{") { i += 3; continue; } if tokens[i].text == "}" || tokens[i].text == ";" { i += 1; continue; } let (end, has_body) = declaration_end(&tokens, i); let line = tokens[i].line; items.push(Located { line, item: classify(&tokens[i..end], has_body), }); i = end; } items } /// Where the declaration starting at `start` ends (exclusive), and /// whether it has a body in braces. fn declaration_end(tokens: &[Token], start: usize) -> (usize, bool) { let mut depth = 0usize; let mut i = start; let mut body = false; while i < tokens.len() { match tokens[i].text.as_str() { "(" | "[" => depth += 1, ")" | "]" => depth = depth.saturating_sub(1), ";" if depth == 0 => return (i + 1, body), "{" if depth == 0 => { let open = i; let mut braces = 0usize; while i < tokens.len() { match tokens[i].text.as_str() { "{" => braces += 1, "}" => { braces -= 1; if braces == 0 { break; } } _ => {} } i += 1; } body = true; // A function definition ends with its body; a struct, // union or enum definition continues to its `;`. if tokens[start..open].iter().any(|t| t.text == "(") { return (i + 1, body); } } _ => {} } i += 1; } (tokens.len(), body) } fn texts(tokens: &[Token]) -> Vec<&str> { tokens.iter().map(|t| t.text.as_str()).collect() } fn is_ident(s: &str) -> bool { s.chars() .next() .is_some_and(|c| c.is_ascii_alphabetic() || c == '_') && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') } fn classify(decl: &[Token], has_body: bool) -> Item { let words = texts(decl); let shown = summary(&words); if has_body { return classify_with_body(&words, shown); } match words.as_slice() { ["struct", name, ";"] if is_ident(name) => Item::StructDecl { name: (*name).into(), alias: None, }, ["typedef", "struct", name, alias, ";"] if is_ident(name) && is_ident(alias) => { Item::StructDecl { name: (*name).into(), alias: Some((*alias).into()), } } ["typedef", rest @ ..] => { let rest = &rest[..rest.len().saturating_sub(1)]; match declarator(rest) { Some((Some(name), TypeSyntax::FnPointer(sig))) => { Item::FnTypedef { name, sig: *sig } } Some((Some(name), ty)) => Item::Typedef { name, ty }, _ => Item::Other(shown), } } _ => function(&words).unwrap_or(Item::Other(shown)), } } /// `struct s { ... };`, `typedef struct s { ... } t;`, or something else /// with a body (an enum, a function definition). fn classify_with_body(words: &[&str], shown: String) -> Item { let open = words.iter().position(|w| *w == "{").unwrap_or(0); let close = words.iter().rposition(|w| *w == "}").unwrap_or(words.len()); let head = &words[..open]; let tail: Vec<&str> = words[close + 1..] .iter() .copied() .filter(|w| *w != ";") .collect(); let (head, typedef) = match head { ["typedef", rest @ ..] => (rest, true), _ => (head, false), }; match head { ["struct"] | ["struct", _] => Item::StructDef { name: head.get(1).map(|n| (*n).into()), alias: match tail.as_slice() { [alias] if typedef && is_ident(alias) => Some((*alias).into()), _ => None, }, }, _ => Item::Other(shown), } } /// `[extern] ret name(params);` fn function(words: &[&str]) -> Option { let words = match words { ["extern", rest @ ..] => rest, _ => words, }; let words = &words[..words.len().checked_sub(1)?]; if words.last() != Some(&")") { return None; } let open = words.iter().position(|w| *w == "(")?; let name = *words.get(open.checked_sub(1)?)?; if !is_ident(name) || open < 2 { return None; } let ret = type_syntax(&words[..open - 1]); let (params, variadic) = params(&words[open + 1..words.len() - 1])?; Some(Item::Function { name: name.into(), sig: Signature { ret, params, variadic, }, }) } /// The parameters between parentheses (`void` or nothing: none). fn params(words: &[&str]) -> Option<(Vec, bool)> { if words.is_empty() || words == ["void"] { return Some((Vec::new(), false)); } let mut out = Vec::new(); let mut variadic = false; for part in split_commas(words) { if part == ["..."] { variadic = true; continue; } let (name, ty) = declarator(part)?; out.push(Param { name, ty }); } Some((out, variadic)) } fn split_commas<'a>(words: &'a [&'a str]) -> Vec<&'a [&'a str]> { let mut parts = Vec::new(); let (mut depth, mut start) = (0usize, 0); for (i, w) in words.iter().enumerate() { match *w { "(" | "[" => depth += 1, ")" | "]" => depth = depth.saturating_sub(1), "," if depth == 0 => { parts.push(&words[start..i]); start = i + 1; } _ => {} } } parts.push(&words[start..]); parts } /// A type followed by an optional name: `const char *s`, `int`, /// `int (*cmp)(int, int)`. fn declarator(words: &[&str]) -> Option<(Option, TypeSyntax)> { if words.is_empty() { return None; } // ret ( * name ) ( params ) if let Some(open) = words.iter().position(|w| *w == "(") { let ret = type_syntax(&words[..open]); let inner_end = open + 1 + words[open + 1..].iter().position(|w| *w == ")")?; let inner = &words[open + 1..inner_end]; let name = match inner { ["*"] => None, ["*", name] if is_ident(name) => Some((*name).to_owned()), _ => return Some((None, TypeSyntax::Unsupported(summary(words)))), }; let rest = &words[inner_end + 1..]; if rest.first() != Some(&"(") || rest.last() != Some(&")") { return Some((name, TypeSyntax::Unsupported(summary(words)))); } let Some((params, variadic)) = params(&rest[1..rest.len() - 1]) else { return Some((name, TypeSyntax::Unsupported(summary(words)))); }; let sig = Signature { ret, params, variadic, }; return Some((name, TypeSyntax::FnPointer(Box::new(sig)))); } if words.contains(&"[") { return Some((None, TypeSyntax::Unsupported(summary(words)))); } // The name is a final identifier that is not a type word, after at // least one type word: `int x`, `sk_vec *v`, but not `int`, `size_t` // or `struct s`. let last = *words.last()?; let type_words = words .iter() .filter(|w| is_ident(w) && !QUALIFIERS.contains(w)) .count(); let tagged = words.len() >= 2 && ["struct", "union", "enum"].contains(&words[words.len() - 2]); if is_ident(last) && type_words >= 2 && !BUILTIN_WORDS.contains(&last) && !tagged { Some(( Some(last.to_owned()), type_syntax(&words[..words.len() - 1]), )) } else { Some((None, type_syntax(words))) } } const QUALIFIERS: &[&str] = &["const", "volatile", "restrict", "__restrict", "extern"]; /// Words that make up a type on their own, so they are never a name. const BUILTIN_WORDS: &[&str] = &[ "void", "char", "short", "int", "long", "float", "double", "signed", "unsigned", "_Bool", "bool", ]; fn type_syntax(words: &[&str]) -> TypeSyntax { let mut out = Vec::new(); let mut is_const = false; let mut pointers = 0; for w in words { match *w { "const" => { // `const` after a `*` qualifies the pointer, not the // pointee: only the pointee's matters here. if pointers == 0 { is_const = true; } } "volatile" | "restrict" | "__restrict" | "extern" | "static" | "inline" => {} "*" => pointers += 1, w if is_ident(w) && pointers == 0 => out.push(w.to_owned()), _ => return TypeSyntax::Unsupported(summary(words)), } } if out.is_empty() { return TypeSyntax::Unsupported(summary(words)); } TypeSyntax::Plain { words: out, is_const, pointers, } } /// Tokens joined back into readable C. pub fn summary(words: &[&str]) -> String { let mut s = String::new(); for (i, w) in words.iter().enumerate() { let prev = if i == 0 { "" } else { words[i - 1] }; let glue = i == 0 || matches!(*w, "," | ")" | ";" | "(" | "[" | "]") || prev == "(" || prev == "[" || (prev == "*" && *w != "const"); if !glue { s.push(' '); } s.push_str(w); } s } /// Tokens of `text`, without comments and preprocessor lines. fn tokenize(text: &str) -> Vec { let mut tokens = Vec::new(); let chars: Vec = text.chars().collect(); let mut line = 1u32; let mut i = 0; let mut line_start = true; while i < chars.len() { let c = chars[i]; if c == '\n' { line += 1; line_start = true; i += 1; continue; } if c.is_whitespace() { i += 1; continue; } if line_start && c == '#' { // A preprocessor line, with its `\` continuations. while i < chars.len() && chars[i] != '\n' { if chars[i] == '\\' && chars.get(i + 1) == Some(&'\n') { line += 1; i += 1; } i += 1; } continue; } line_start = false; if c == '/' && chars.get(i + 1) == Some(&'/') { while i < chars.len() && chars[i] != '\n' { i += 1; } continue; } if c == '/' && chars.get(i + 1) == Some(&'*') { i += 2; while i < chars.len() && !(chars[i] == '*' && chars.get(i + 1) == Some(&'/')) { if chars[i] == '\n' { line += 1; } i += 1; } i += 2; continue; } let start = i; if c.is_ascii_alphanumeric() || c == '_' { while i < chars.len() && (chars[i].is_ascii_alphanumeric() || chars[i] == '_') { i += 1; } } else if c == '"' || c == '\'' { i += 1; while i < chars.len() && chars[i] != c { if chars[i] == '\\' { i += 1; } i += 1; } i += 1; } else if c == '.' && chars.get(i + 1) == Some(&'.') && chars.get(i + 2) == Some(&'.') { i += 3; } else { i += 1; } let end = i.min(chars.len()); tokens.push(Token { text: chars[start..end].iter().collect(), line, }); } tokens } #[cfg(test)] mod tests { use super::*; fn plain(words: &[&str], is_const: bool, pointers: usize) -> TypeSyntax { TypeSyntax::Plain { words: words.iter().map(|w| (*w).to_owned()).collect(), is_const, pointers, } } #[test] fn functions_and_parameters() { let items = parse( "/* doc */\n#include \n#define X(a) \\\n (a)\nsize_t count(const char *s, size_t len, int c);\n", ); assert_eq!(items.len(), 1); assert_eq!(items[0].line, 5); let Item::Function { name, sig } = &items[0].item else { panic!("{items:?}"); }; assert_eq!(name, "count"); assert_eq!(sig.ret, plain(&["size_t"], false, 0)); assert_eq!(sig.params[0].ty, plain(&["char"], true, 1)); assert_eq!(sig.params[0].name.as_deref(), Some("s")); assert_eq!(sig.params[2].ty, plain(&["int"], false, 0)); } #[test] fn unnamed_parameters_and_function_pointers() { let items = parse("void each(struct v *, int (*f)(int64_t, void *), void *);"); let Item::Function { sig, .. } = &items[0].item else { panic!("{items:?}"); }; assert_eq!(sig.params[0].name, None); assert_eq!(sig.params[0].ty, plain(&["struct", "v"], false, 1)); assert_eq!(sig.params[1].name.as_deref(), Some("f")); let TypeSyntax::FnPointer(f) = &sig.params[1].ty else { panic!("{sig:?}"); }; assert_eq!(f.params[0].ty, plain(&["int64_t"], false, 0)); assert_eq!(f.params[1].ty, plain(&["void"], false, 1)); } #[test] fn structs_typedefs_and_others() { let items = parse( "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", ); let kinds: Vec<&Item> = items.iter().map(|l| &l.item).collect(); assert_eq!( kinds[0], &Item::StructDecl { name: "v".into(), alias: Some("v".into()) } ); assert_eq!( kinds[1], &Item::StructDecl { name: "w".into(), alias: None } ); assert_eq!( kinds[2], &Item::StructDef { name: Some("s".into()), alias: Some("s".into()) } ); assert!(matches!(kinds[3], Item::FnTypedef { name, .. } if name == "cmp")); assert!(matches!(kinds[4], Item::Typedef { name, .. } if name == "ssize")); assert!(matches!(kinds[5], Item::Other(s) if s.starts_with("enum e"))); assert!(matches!(kinds[6], Item::Other(s) if s.starts_with("static inline int f"))); assert!(matches!(kinds[7], Item::Function { name, .. } if name == "g")); assert!(matches!(kinds[8], Item::Other(s) if s == "extern int counter;")); assert_eq!(items.len(), 9); } }