Skip to content

Commit

Permalink
Zig language added
Browse files Browse the repository at this point in the history
  • Loading branch information
kassane committed Mar 26, 2022
1 parent b3de1dc commit 376cfbf
Show file tree
Hide file tree
Showing 109 changed files with 905 additions and 34 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 @@ -133,7 +133,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 @@ -220,6 +220,10 @@ impl Bindings {
out.new_line();
out.close_brace(false);
}
Language::Zig => {
out.write("const std = @import(\"std\");");
out.new_line();
}
}
}

Expand All @@ -240,6 +244,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 @@ -308,6 +319,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
61 changes: 51 additions & 10 deletions src/bindgen/cdecl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,15 +130,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 @@ -179,6 +186,7 @@ impl CDecl {
}

fn write<F: Write>(&self, out: &mut SourceWriter<F>, ident: Option<&str>, config: &Config) {

// Write the type-specifier and type-qualifier first
if !self.type_qualifers.is_empty() {
write!(out, "{} ", self.type_qualifers);
Expand All @@ -190,14 +198,16 @@ 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("<");
out.write_horizontal_source_list(&self.type_generic_args, ListType::Join(", "));
out.write(">");
}

// When we have an identifier, put a space between the type and the declarators
if ident.is_some() {
out.write(" ");
Expand All @@ -216,11 +226,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 {
out.write("_");
}
}
if is_const {
out.write("const ");
if config.language == Language::Zig {
out.write(config.style.zig_def());
} else {
out.write("const ");
}
}
if !is_nullable && !is_ref && config.language != Language::Cython {
if !is_nullable && !is_ref && config.language != Language::Cython && config.language != Language::Zig {
if let Some(attr) = &config.pointer.non_null_attribute {
write!(out, "{} ", attr);
}
Expand All @@ -241,7 +263,11 @@ impl CDecl {

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

// Write the right part of declarators after the identifier
Expand All @@ -252,13 +278,24 @@ impl CDecl {
while let Some(declarator) = iter.next() {
match *declarator {
CDeclarator::Ptr { .. } => {
if config.language == Language::Zig {
write!(out, ": ?*{}", self.type_name);
}
last_was_pointer = true;
}
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;
}
Expand All @@ -270,7 +307,7 @@ impl CDecl {
out.write("(");
if args.is_empty() && config.language == Language::C {
out.write("void");
}
}
if layout_vertical {
let align_length = out.line_length_for_align();
out.push_set_spaces(align_length);
Expand Down Expand Up @@ -300,6 +337,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 @@ -693,6 +705,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 @@ -702,6 +716,7 @@ impl Default for ConstantConfig {
ConstantConfig {
allow_static_const: true,
allow_constexpr: false,
allow_comptime: false,
sort_by: None,
}
}
Expand Down Expand Up @@ -876,6 +891,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 @@ -998,6 +1022,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 @@ -1040,6 +1066,7 @@ impl Default for Config {
pointer: PtrConfig::default(),
only_target_dependencies: false,
cython: CythonConfig::default(),
zig: ZigConfig::default(),
}
}
}
Expand All @@ -1050,23 +1077,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
20 changes: 20 additions & 0 deletions src/bindgen/ir/constant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,7 @@ impl Literal {
Language::C => write!(out, "({})", export_name),
Language::Cxx => write!(out, "{}", export_name),
Language::Cython => write!(out, "<{}>", export_name),
Language::Zig => write!(out, ":{} = ", export_name),
}

write!(out, "{{ ");
Expand All @@ -351,6 +352,7 @@ impl Literal {
Language::Cxx => write!(out, "/* .{} = */ ", ordered_key),
Language::C => write!(out, ".{} = ", ordered_key),
Language::Cython => {}
Language::Zig => write!(out, ".{} = ", ordered_key),
}
lit.write(config, out);
}
Expand Down Expand Up @@ -564,6 +566,12 @@ impl Constant {
false
};

let allow_comptime = if let Type::Primitive(..) = self.ty {
config.constant.allow_comptime
} else {
false
};

match config.language {
Language::Cxx if config.constant.allow_static_const || allow_constexpr => {
if allow_constexpr {
Expand Down Expand Up @@ -596,6 +604,18 @@ impl Constant {
// but still useful as documentation, so we write it as a comment.
write!(out, " {} # = ", name);
value.write(config, out);
},
Language::Zig if allow_comptime => {

if allow_comptime {
out.write("comptime ");
}
}
Language::Zig => {
out.write(config.style.zig_def());
self.ty.write(config, out);
write!(out, " {} = ", name);
value.write(config, out);
}
}

Expand Down
Loading

0 comments on commit 376cfbf

Please sign in to comment.