Skip to content

Commit

Permalink
Zig language added
Browse files Browse the repository at this point in the history
  • Loading branch information
kassane committed May 14, 2022
1 parent c732069 commit 044a0a9
Show file tree
Hide file tree
Showing 110 changed files with 988 additions and 49 deletions.
5 changes: 5 additions & 0 deletions .github/workflows/cbindgen.yml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ jobs:
python -m pip install --upgrade pip wheel
pip install Cython==0.29.*
- name: Install Zig
uses: goto-bus-stop/setup-zig@v1
with:
version: master

- name: Build
run: |
cargo build --verbose
Expand Down
6 changes: 3 additions & 3 deletions docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ cbindgen --config cbindgen.toml --crate my_rust_library --output my_header.h
```

This produces a header file for C++. For C, add the `--lang c` switch. \
`cbindgen` also supports generation of [Cython](https://cython.org) bindings,
use `--lang cython` for that.
`cbindgen` also supports generation of [Cython](https://cython.org) and [Zig](https://ziglang.org) bindings,
use `--lang cython` or `--lang zig` for that.

See `cbindgen --help` for more options.

Expand Down Expand Up @@ -385,7 +385,7 @@ Note that many options defined here only apply for one of C or C++. Usually it's
```toml
# The language to output bindings in
#
# possible values: "C", "C++", "Cython"
# possible values: "C", "C++", "Cython", "Zig"
#
# default: "C++"
language = "C"
Expand Down
23 changes: 22 additions & 1 deletion src/bindgen/bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ impl Bindings {
write!(out, "#define {}", f);
out.new_line();
}
if self.config.pragma_once && self.config.language != Language::Cython {
if self.config.pragma_once && self.config.language != Language::Cython && self.config.language != Language::Zig {
out.new_line_if_not_start();
write!(out, "#pragma once");
out.new_line();
Expand Down Expand Up @@ -233,6 +233,10 @@ impl Bindings {
out.new_line();
out.close_brace(false);
}
Language::Zig => {
out.write("const std = @import(\"std\");");
out.new_line();
}
}
}

Expand All @@ -253,6 +257,13 @@ impl Bindings {
}
}

if self.config.language == Language::Zig {
for (module, names) in &self.config.zig.cimports {
write!(out, "const {} = @cImport ({{ @cInclude(\"{}\")}});", names.join(""), module);
out.new_line();
}
}

if let Some(ref line) = self.config.after_includes {
write!(out, "{}", line);
out.new_line();
Expand Down Expand Up @@ -325,6 +336,16 @@ impl Bindings {
}
}

if self.config.language == Language::Zig {
if let Some(ref using_namespaces) = self.config.using_namespaces {
for namespace in using_namespaces {
out.new_line();
write!(out, "usingnamespace {};", namespace);
}
out.new_line();
}
}

if self.config.language == Language::Cxx || self.config.cpp_compatible_c() {
out.new_line();
out.write("extern \"C\" {");
Expand Down
92 changes: 81 additions & 11 deletions src/bindgen/cdecl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ impl CDecl {
"error generating cdecl for {:?}",
t
);
self.type_qualifers = "const".to_owned();
if config.language != Language::Zig {
self.type_qualifers = "const".to_owned();
}
}

assert!(
Expand All @@ -130,15 +132,22 @@ impl CDecl {
"error generating cdecl for {:?}",
t
);
self.type_qualifers = "const".to_owned();
if config.language != Language::Zig {
self.type_qualifers = "const".to_owned();
}
}

assert!(
self.type_name.is_empty(),
"error generating cdecl for {:?}",
t
);
self.type_name = p.to_repr_c(config).to_string();

if config.language == Language::Zig {
self.type_name = p.to_repr_zig().to_string();
} else {
self.type_name = p.to_repr_c(config).to_string();
}
}
Type::Ptr {
ref ty,
Expand Down Expand Up @@ -190,7 +199,9 @@ impl CDecl {
}
}

write!(out, "{}", self.type_name);
if config.language != Language::Zig {
write!(out, "{}", self.type_name);
}

if !self.type_generic_args.is_empty() {
out.write("<");
Expand All @@ -200,11 +211,16 @@ impl CDecl {

// When we have an identifier, put a space between the type and the declarators
if ident.is_some() {
out.write(" ");
if config.language == Language::Zig && self.declarators.is_empty() {
out.write("");
} else {
out.write(" ");
}
}

// Write the left part of declarators before the identifier
let mut iter_rev = self.declarators.iter().rev().peekable();
let mut is_functors = false;

#[allow(clippy::while_let_on_iterator)]
while let Some(declarator) = iter_rev.next() {
Expand All @@ -216,9 +232,23 @@ impl CDecl {
is_nullable,
is_ref,
} => {
out.write(if is_ref { "&" } else { "*" });
if config.language != Language::Zig {
out.write(if is_ref { "&" } else { "*" });
} else {
if !self.type_qualifers.is_empty() {
write!(out, "{}", self.type_qualifers);
} else {
if config.language != Language::Zig {
out.write("_");
}
}
}
if is_const {
out.write("const ");
if config.language == Language::Zig {
write!(out, "{} ", config.style.zig_def());
} else {
out.write("const ");
}
}
if !is_nullable && !is_ref && config.language != Language::Cython {
if let Some(attr) = &config.pointer.non_null_attribute {
Expand All @@ -232,16 +262,25 @@ impl CDecl {
}
}
CDeclarator::Func(..) => {
if next_is_pointer {
if next_is_pointer && config.language != Language::Zig {
out.write("(");
}
is_functors = true;
}
}
}

// Write the identifier
if let Some(ident) = ident {
write!(out, "{}", ident);
if config.language == Language::Zig && self.declarators.is_empty() {
if ident.is_empty() {
write!(out, "{}", self.type_name);
} else {
write!(out, "{}: {}", ident, self.type_name);
}
} else {
write!(out, "{}", ident);
}
}

// Write the right part of declarators after the identifier
Expand All @@ -253,19 +292,46 @@ impl CDecl {
match *declarator {
CDeclarator::Ptr { .. } => {
last_was_pointer = true;

if config.language == Language::Zig {
if self.type_name.contains("u8")
|| self.type_name.contains("const u8")
|| self.type_name.contains("CStr")
|| self.type_name.contains("c_char")
{
write!(out, ": ?[*:0]{}", self.type_name);
} else if is_functors {
out.write(": ?fn");
} else {
write!(out, ": ?*{}", self.type_name);
}
}
}
CDeclarator::Array(ref constant) => {
if last_was_pointer {
out.write(")");
}
write!(out, "[{}]", constant);
if config.language == Language::Zig {
if constant.is_empty() {
write!(out, "{}: [*]{}", self.type_qualifers, self.type_name);
} else {
write!(
out,
"{}: [{}]{}",
self.type_qualifers, constant, self.type_name
);
}
} else {
write!(out, "[{}]", constant);
}

last_was_pointer = false;
}
CDeclarator::Func(ref args, layout_vertical) => {
if last_was_pointer {
if last_was_pointer && config.language != Language::Zig {
out.write(")");
}
is_functors = true;

out.write("(");
if args.is_empty() && config.language == Language::C {
Expand Down Expand Up @@ -300,6 +366,10 @@ impl CDecl {
}
out.write(")");

if config.language == Language::Zig {
write!(out, " {}", self.type_name);
}

last_was_pointer = true;
}
}
Expand Down
33 changes: 30 additions & 3 deletions src/bindgen/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub enum Language {
Cxx,
C,
Cython,
Zig,
}

impl FromStr for Language {
Expand All @@ -42,6 +43,8 @@ impl FromStr for Language {
"C" => Ok(Language::C),
"cython" => Ok(Language::Cython),
"Cython" => Ok(Language::Cython),
"zig" => Ok(Language::Zig),
"Zig" => Ok(Language::Zig),
_ => Err(format!("Unrecognized Language: '{}'.", s)),
}
}
Expand All @@ -54,6 +57,7 @@ impl Language {
match self {
Language::Cxx | Language::C => "typedef",
Language::Cython => "ctypedef",
Language::Zig => "pub const",
}
}
}
Expand Down Expand Up @@ -243,6 +247,14 @@ impl Style {
"ctypedef "
}
}

pub fn zig_def(self) -> &'static str {
if self.generate_tag() {
"pub const "
} else {
"pub extern"
}
}
}

impl Default for Style {
Expand Down Expand Up @@ -698,6 +710,8 @@ pub struct ConstantConfig {
pub allow_static_const: bool,
/// Whether a generated constant should be constexpr in C++ mode.
pub allow_constexpr: bool,
/// Whether a generated compile-time should be comptime in Zig mode.
pub allow_comptime: bool,
/// Sort key for constants
pub sort_by: Option<SortKey>,
}
Expand All @@ -707,6 +721,7 @@ impl Default for ConstantConfig {
ConstantConfig {
allow_static_const: true,
allow_constexpr: true,
allow_comptime: true,
sort_by: None,
}
}
Expand Down Expand Up @@ -881,6 +896,15 @@ pub struct CythonConfig {
pub cimports: BTreeMap<String, Vec<String>>,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
#[serde(default)]
pub struct ZigConfig {
pub header: Option<String>,
pub cimports: BTreeMap<String, Vec<String>>,
}

/// A collection of settings to customize the generated bindings.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "snake_case")]
Expand Down Expand Up @@ -1003,6 +1027,8 @@ pub struct Config {
pub only_target_dependencies: bool,
/// Configuration options specific to Cython.
pub cython: CythonConfig,
/// Configuration options specific to Zig.
pub zig: ZigConfig,
}

impl Default for Config {
Expand Down Expand Up @@ -1045,6 +1071,7 @@ impl Default for Config {
pointer: PtrConfig::default(),
only_target_dependencies: false,
cython: CythonConfig::default(),
zig: ZigConfig::default(),
}
}
}
Expand All @@ -1055,23 +1082,23 @@ impl Config {
}

pub(crate) fn include_guard(&self) -> Option<&str> {
if self.language == Language::Cython {
if self.language == Language::Cython || self.language == Language::Zig {
None
} else {
self.include_guard.as_deref()
}
}

pub(crate) fn includes(&self) -> &[String] {
if self.language == Language::Cython {
if self.language == Language::Cython || self.language == Language::Zig {
&[]
} else {
&self.includes
}
}

pub(crate) fn sys_includes(&self) -> &[String] {
if self.language == Language::Cython {
if self.language == Language::Cython || self.language == Language::Zig {
&[]
} else {
&self.sys_includes
Expand Down
Loading

0 comments on commit 044a0a9

Please sign in to comment.