Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for custom languages #867

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/bindgen/bindings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,21 @@ impl Bindings {
}
}

#[allow(unused)]
pub fn constants(&self) -> &[Constant] {
&self.constants
}

#[allow(unused)]
pub fn items(&self) -> &[ItemContainer] {
&self.items
}

#[allow(unused)]
pub fn functions(&self) -> &[Function] {
&self.functions
}

// FIXME(emilio): What to do when the configuration doesn't match?
pub fn struct_is_transparent(&self, path: &BindgenPath) -> bool {
let mut any = false;
Expand Down Expand Up @@ -308,6 +323,7 @@ impl Bindings {
out.new_line();
out.close_brace(false);
}
Language::Custom(_) => unreachable!()
}
}

Expand Down Expand Up @@ -339,6 +355,15 @@ impl Bindings {
return;
}

match &self.config.language {
Language::Custom(custom_language) => {
let mut file = file;
custom_language.write(&mut file, self, &self.config).unwrap();
return;
},
_ => {}
}

let mut out = SourceWriter::new(file, self);

self.write_headers(&mut out);
Expand Down
8 changes: 8 additions & 0 deletions src/bindgen/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use std::path;
use std::rc::Rc;

use crate::bindgen::CustomLanguage;
use crate::bindgen::bindings::Bindings;
use crate::bindgen::cargo::Cargo;
use crate::bindgen::config::{Braces, Config, Language, Profile, Style};
Expand Down Expand Up @@ -149,6 +151,12 @@ impl Builder {
self
}

#[allow(unused)]
pub fn with_custom_language(mut self, language: impl CustomLanguage) -> Builder {
self.config.language = Language::Custom(Rc::new(language));
self
}

#[allow(unused)]
pub fn with_cpp_compat(mut self, cpp_compat: bool) -> Builder {
self.config.cpp_compat = cpp_compat;
Expand Down
29 changes: 28 additions & 1 deletion src/bindgen/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,53 @@

use std::collections::{BTreeMap, HashMap};
use std::default::Default;
use std::rc::Rc;
use std::str::FromStr;
use std::{fmt, fs, path::Path as StdPath, path::PathBuf as StdPathBuf};

use serde::de::value::{MapAccessDeserializer, SeqAccessDeserializer};
use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};

use crate::Bindings;
use crate::bindgen::ir::annotation::AnnotationSet;
use crate::bindgen::ir::path::Path;
use crate::bindgen::ir::repr::ReprAlign;
pub use crate::bindgen::rename::RenameRule;

pub const VERSION: &str = env!("CARGO_PKG_VERSION");

pub trait CustomLanguage: 'static + std::fmt::Debug {
fn write(
&self,
file: &mut dyn std::io::Write,
bindings: &Bindings,
config: &Config
) -> std::io::Result<()>;
}

/// A language type to generate bindings for.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[derive(Debug, Clone)]
pub enum Language {
Cxx,
C,
Cython,
Custom(Rc<dyn CustomLanguage>)
}

impl PartialEq for Language {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Language::Cxx, Language::Cxx) => true,
(Language::C, Language::C) => true,
(Language::Cython, Language::Cython) => true,
(Language::Custom(a), Language::Custom(b)) => Rc::ptr_eq(a, b),
_ => false,
}
}
}

impl Eq for Language {}

impl FromStr for Language {
type Err = String;

Expand Down Expand Up @@ -54,6 +80,7 @@ impl Language {
match self {
Language::Cxx | Language::C => "typedef",
Language::Cython => "ctypedef",
Language::Custom(_) => unreachable!(),
}
}
}
Expand Down
12 changes: 8 additions & 4 deletions src/bindgen/ir/constant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,7 @@ impl Literal {

pub(crate) fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
match self {
Literal::Expr(v) => match (&**v, config.language) {
Literal::Expr(v) => match (&**v, &config.language) {
("true", Language::Cython) => write!(out, "True"),
("false", Language::Cython) => write!(out, "False"),
(v, _) => write!(out, "{}", v),
Expand All @@ -488,15 +488,16 @@ impl Literal {
if let Some(known) = to_known_assoc_constant(path, name) {
return write!(out, "{}", known);
}
let path_separator = match config.language {
let path_separator = match &config.language {
Language::Cython | Language::C => "_",
Language::Cxx => {
if config.structure.associated_constants_in_body {
"::"
} else {
"_"
}
}
},
Language::Custom(_) => unreachable!()
};
write!(out, "{}{}", export_name, path_separator)
}
Expand Down Expand Up @@ -548,6 +549,7 @@ impl Literal {
Language::C => write!(out, "({})", export_name),
Language::Cxx => write!(out, "{}", export_name),
Language::Cython => write!(out, "<{}>", export_name),
Language::Custom(_) => unreachable!()
}

write!(out, "{{ ");
Expand All @@ -565,6 +567,7 @@ impl Literal {
Language::Cxx => write!(out, "/* .{} = */ ", ordered_key),
Language::C => write!(out, ".{} = ", ordered_key),
Language::Cython => {}
Language::Custom(_) => unreachable!()
}
lit.write(config, out);
}
Expand Down Expand Up @@ -805,7 +808,8 @@ impl Constant {
// but still useful as documentation, so we write it as a comment.
write!(out, " {} # = ", name);
value.write(config, out);
}
},
Language::Custom(_) => unreachable!(),
}

condition.write_after(config, out);
Expand Down
10 changes: 6 additions & 4 deletions src/bindgen/ir/enumeration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -748,7 +748,7 @@ impl Enum {
tag_name: &str,
) {
// Open the tag enum.
match config.language {
match &config.language {
Language::C => {
if let Some(prim) = size {
// If we need to specify size, then we have no choice but to create a typedef,
Expand Down Expand Up @@ -800,7 +800,8 @@ impl Enum {
} else {
write!(out, "{}enum {}", config.style.cython_def(), tag_name);
}
}
},
Language::Custom(_) => unreachable!(),
}
out.open_brace();

Expand Down Expand Up @@ -831,7 +832,7 @@ impl Enum {

if config.language != Language::Cxx {
out.new_line();
write!(out, "{} {} {};", config.language.typedef(), prim, tag_name);
write!(out, "{} {} {};", config.language.clone().typedef(), prim, tag_name);
}

if config.cpp_compatible_c() {
Expand All @@ -851,10 +852,11 @@ impl Enum {
out: &mut SourceWriter<F>,
inline_tag_field: bool,
) {
match config.language {
match &config.language {
Language::C if config.style.generate_typedef() => out.write("typedef "),
Language::C | Language::Cxx => {}
Language::Cython => out.write(config.style.cython_def()),
Language::Custom(_) => unreachable!(),
}

out.write(if inline_tag_field { "union" } else { "struct" });
Expand Down
5 changes: 3 additions & 2 deletions src/bindgen/ir/opaque.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ impl Source for OpaqueItem {

self.generic_params.write_with_default(config, out);

match config.language {
match &config.language {
Language::C if config.style.generate_typedef() => {
write!(
out,
Expand All @@ -168,7 +168,8 @@ impl Source for OpaqueItem {
out.open_brace();
out.write("pass");
out.close_brace(false);
}
},
Language::Custom(_) => unreachable!(),
}

condition.write_after(config, out);
Expand Down
1 change: 1 addition & 0 deletions src/bindgen/ir/structure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,7 @@ impl Source for Struct {
Language::C if config.style.generate_typedef() => out.write("typedef "),
Language::C | Language::Cxx => {}
Language::Cython => out.write(config.style.cython_def()),
Language::Custom(_) => unreachable!(),
}

// Cython extern declarations don't manage layouts, layouts are defined entierly by the
Expand Down
5 changes: 3 additions & 2 deletions src/bindgen/ir/typedef.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,10 +195,11 @@ impl Source for Typedef {
self.aliased.write(config, out);
}
Language::C | Language::Cython => {
write!(out, "{} ", config.language.typedef());
write!(out, "{} ", config.language.clone().typedef());
Field::from_name_and_type(self.export_name().to_owned(), self.aliased.clone())
.write(config, out);
}
},
Language::Custom(_) => unreachable!(),
}

out.write(";");
Expand Down
1 change: 1 addition & 0 deletions src/bindgen/ir/union.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ impl Source for Union {
Language::C if config.style.generate_typedef() => out.write("typedef "),
Language::C | Language::Cxx => {}
Language::Cython => out.write(config.style.cython_def()),
Language::Custom(_) => unreachable!(),
}

out.write("union");
Expand Down
3 changes: 2 additions & 1 deletion src/bindgen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ mod config;
mod declarationtyperesolver;
mod dependencies;
mod error;
mod ir;
pub mod ir;
mod library;
mod mangle;
mod monomorph;
Expand All @@ -63,3 +63,4 @@ pub use self::builder::Builder;
pub use self::config::Profile; // disambiguate with cargo::Profile
pub use self::config::*;
pub use self::error::Error;
//pub use self::declarationtyperesolver::DeclarationType;
2 changes: 2 additions & 0 deletions src/bindgen/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ impl<'a, F: Write> SourceWriter<'a, F> {
self.new_line();
self.push_tab();
}
Language::Custom(_) => unreachable!()
}
}

Expand All @@ -191,6 +192,7 @@ impl<'a, F: Write> SourceWriter<'a, F> {
}
}
Language::Cython => {}
Language::Custom(_) => unreachable!()
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ extern crate quote;
extern crate syn;
extern crate toml;

mod bindgen;
pub mod bindgen;

pub use crate::bindgen::*;

Expand Down
12 changes: 8 additions & 4 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ fn run_cbindgen(
}
Language::Cython => {
command.arg("--lang").arg("cython");
}
},
Language::Custom(_) => unreachable!(),
}

if let Some(style) = style {
Expand Down Expand Up @@ -116,6 +117,7 @@ fn compile(
Language::Cxx => env::var("CXX").unwrap_or_else(|_| "g++".to_owned()),
Language::C => env::var("CC").unwrap_or_else(|_| "gcc".to_owned()),
Language::Cython => env::var("CYTHON").unwrap_or_else(|_| "cython".to_owned()),
Language::Custom(_) => unreachable!(),
};

let file_name = cbindgen_output
Expand Down Expand Up @@ -172,7 +174,8 @@ fn compile(
command.arg("-3");
command.arg("-o").arg(&object);
command.arg(cbindgen_output);
}
},
Language::Custom(_) => unreachable!(),
}

println!("Running: {:?}", command);
Expand Down Expand Up @@ -216,6 +219,7 @@ fn run_compile_test(
// is extension-sensitive and won't work on them, so we use implementation files (`.pyx`)
// in the test suite.
Language::Cython => ".pyx",
Language::Custom(_) => unreachable!(),
};

let skip_warning_as_error = name.rfind(SKIP_WARNING_AS_ERROR_SUFFIX).is_some();
Expand All @@ -238,7 +242,7 @@ fn run_compile_test(
let (cbindgen_output, depfile_contents) = run_cbindgen(
path,
output_file,
language,
language.clone(),
cpp_compat,
style,
generate_depfile,
Expand Down Expand Up @@ -285,7 +289,7 @@ fn run_compile_test(
&generated_file,
&tests_path,
tmp_dir,
language,
language.clone(),
style,
skip_warning_as_error,
);
Expand Down