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

Const generics #759

Merged
merged 2 commits into from May 9, 2022
Merged
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
4 changes: 2 additions & 2 deletions src/bindgen/cdecl.rs
Expand Up @@ -5,7 +5,7 @@
use std::io::Write;

use crate::bindgen::declarationtyperesolver::DeclarationType;
use crate::bindgen::ir::{ArrayLength, Function, Type};
use crate::bindgen::ir::{ArrayLength, Function, GenericArgument, Type};
use crate::bindgen::writer::{ListType, SourceWriter};
use crate::bindgen::{Config, Language};

Expand Down Expand Up @@ -35,7 +35,7 @@ impl CDeclarator {
struct CDecl {
type_qualifers: String,
type_name: String,
type_generic_args: Vec<Type>,
type_generic_args: Vec<GenericArgument>,
declarators: Vec<CDeclarator>,
type_ctype: Option<DeclarationType>,
}
Expand Down
36 changes: 10 additions & 26 deletions src/bindgen/ir/enumeration.rs
Expand Up @@ -10,8 +10,9 @@ use crate::bindgen::config::{Config, Language};
use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver;
use crate::bindgen::dependencies::Dependencies;
use crate::bindgen::ir::{
AnnotationSet, AnnotationValue, Cfg, ConditionWrite, Documentation, Field, GenericParams,
GenericPath, Item, ItemContainer, Literal, Path, Repr, ReprStyle, Struct, ToCondition, Type,
AnnotationSet, AnnotationValue, Cfg, ConditionWrite, Documentation, Field, GenericArgument,
GenericParams, GenericPath, Item, ItemContainer, Literal, Path, Repr, ReprStyle, Struct,
ToCondition, Type,
};
use crate::bindgen::library::Library;
use crate::bindgen::mangle;
Expand Down Expand Up @@ -61,8 +62,8 @@ impl VariantBody {

fn specialize(
&self,
generic_values: &[Type],
mappings: &[(&Path, &Type)],
generic_values: &[GenericArgument],
mappings: &[(&Path, &GenericArgument)],
config: &Config,
) -> Self {
match *self {
Expand Down Expand Up @@ -265,8 +266,8 @@ impl EnumVariant {

fn specialize(
&self,
generic_values: &[Type],
mappings: &[(&Path, &Type)],
generic_values: &[GenericArgument],
mappings: &[(&Path, &GenericArgument)],
config: &Config,
) -> Self {
Self::new(
Expand Down Expand Up @@ -382,7 +383,7 @@ impl Enum {
}

let path = Path::new(item.ident.unraw().to_string());
let generic_params = GenericParams::new(&item.generics);
let generic_params = GenericParams::load(&item.generics)?;

let mut variants = Vec::new();
let mut has_data = false;
Expand Down Expand Up @@ -611,28 +612,11 @@ impl Item for Enum {

fn instantiate_monomorph(
&self,
generic_values: &[Type],
generic_values: &[GenericArgument],
library: &Library,
out: &mut Monomorphs,
) {
assert!(
self.generic_params.len() > 0,
"{} is not generic",
self.path.name()
);
assert!(
self.generic_params.len() == generic_values.len(),
"{} has {} params but is being instantiated with {} values",
self.path.name(),
self.generic_params.len(),
generic_values.len(),
);

let mappings = self
.generic_params
.iter()
.zip(generic_values.iter())
.collect::<Vec<_>>();
let mappings = self.generic_params.call(self.path.name(), generic_values);

for variant in &self.variants {
if let VariantBody::Body { ref body, .. } = variant.body {
Expand Down
171 changes: 145 additions & 26 deletions src/bindgen/ir/generic_path.rs
Expand Up @@ -3,29 +3,95 @@ use std::ops::Deref;

use syn::ext::IdentExt;

use crate::bindgen::cdecl;
use crate::bindgen::config::{Config, Language};
use crate::bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver};
use crate::bindgen::ir::{Path, Type};
use crate::bindgen::ir::{ArrayLength, Path, Type};
use crate::bindgen::utilities::IterHelpers;
use crate::bindgen::writer::{Source, SourceWriter};

#[derive(Debug, Clone)]
pub enum GenericParamType {
Type,
Const(Type),
}

#[derive(Debug, Clone)]
pub struct GenericParam {
name: Path,
ty: GenericParamType,
}

impl GenericParam {
pub fn new_type_param(name: &str) -> Self {
GenericParam {
name: Path::new(name),
ty: GenericParamType::Type,
}
}

pub fn load(param: &syn::GenericParam) -> Result<Option<Self>, String> {
match *param {
syn::GenericParam::Type(syn::TypeParam { ref ident, .. }) => Ok(Some(GenericParam {
name: Path::new(ident.unraw().to_string()),
ty: GenericParamType::Type,
})),

syn::GenericParam::Lifetime(_) => Ok(None),

syn::GenericParam::Const(syn::ConstParam {
ref ident, ref ty, ..
}) => match Type::load(ty)? {
None => {
// A type that evaporates, like PhantomData.
Err(format!("unsupported const generic type: {:?}", ty))
}
Some(ty) => Ok(Some(GenericParam {
name: Path::new(ident.unraw().to_string()),
ty: GenericParamType::Const(ty),
})),
},
}
}

pub fn name(&self) -> &Path {
&self.name
}
}

#[derive(Default, Debug, Clone)]
pub struct GenericParams(pub Vec<Path>);
pub struct GenericParams(pub Vec<GenericParam>);

impl GenericParams {
pub fn new(generics: &syn::Generics) -> Self {
GenericParams(
generics
.params
.iter()
.filter_map(|x| match *x {
syn::GenericParam::Type(syn::TypeParam { ref ident, .. }) => {
Some(Path::new(ident.unraw().to_string()))
}
_ => None,
})
.collect(),
)
pub fn load(generics: &syn::Generics) -> Result<Self, String> {
let mut params = vec![];
for param in &generics.params {
if let Some(p) = GenericParam::load(param)? {
params.push(p);
}
}

Ok(GenericParams(params))
}

/// Associate each parameter with an argument.
pub fn call<'out>(
&'out self,
item_name: &str,
arguments: &'out [GenericArgument],
) -> Vec<(&'out Path, &'out GenericArgument)> {
assert!(self.len() > 0, "{} is not generic", item_name);
assert!(
self.len() == arguments.len(),
"{} has {} params but is being instantiated with {} values",
item_name,
self.len(),
arguments.len(),
);
self.iter()
.map(|param| param.name())
.zip(arguments.iter())
.collect()
}

fn write_internal<F: Write>(
Expand All @@ -40,9 +106,19 @@ impl GenericParams {
if i != 0 {
out.write(", ");
}
write!(out, "typename {}", item);
if with_default {
write!(out, " = void");
match item.ty {
GenericParamType::Type => {
write!(out, "typename {}", item.name);
if with_default {
write!(out, " = void");
}
}
GenericParamType::Const(ref ty) => {
cdecl::write_field(out, ty, item.name.name(), config);
if with_default {
write!(out, " = 0");
}
}
}
}
out.write(">");
Expand All @@ -56,9 +132,9 @@ impl GenericParams {
}

impl Deref for GenericParams {
type Target = [Path];
type Target = [GenericParam];

fn deref(&self) -> &[Path] {
fn deref(&self) -> &[GenericParam] {
&self.0
}
}
Expand All @@ -69,16 +145,52 @@ impl Source for GenericParams {
}
}

/// A (non-lifetime) argument passed to a generic, either a type or a constant expression.
///
/// Note: Both arguments in a type like `Array<T, N>` are represented as
/// `GenericArgument::Type`s, even if `N` is actually the name of a const. This
/// is a consequence of `syn::GenericArgument` doing the same thing.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum GenericArgument {
Type(Type),
Const(ArrayLength),
}

impl GenericArgument {
pub fn specialize(&self, mappings: &[(&Path, &GenericArgument)]) -> GenericArgument {
match *self {
GenericArgument::Type(ref ty) => GenericArgument::Type(ty.specialize(mappings)),
GenericArgument::Const(ref expr) => GenericArgument::Const(expr.clone()),
}
}

pub fn rename_for_config(&mut self, config: &Config, generic_params: &GenericParams) {
match *self {
GenericArgument::Type(ref mut ty) => ty.rename_for_config(config, generic_params),
GenericArgument::Const(ref mut expr) => expr.rename_for_config(config),
}
}
}

impl Source for GenericArgument {
fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
match *self {
GenericArgument::Type(ref ty) => ty.write(config, out),
GenericArgument::Const(ref expr) => expr.write(config, out),
}
}
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct GenericPath {
path: Path,
export_name: String,
generics: Vec<Type>,
generics: Vec<GenericArgument>,
ctype: Option<DeclarationType>,
}

impl GenericPath {
pub fn new(path: Path, generics: Vec<Type>) -> Self {
pub fn new(path: Path, generics: Vec<GenericArgument>) -> Self {
let export_name = path.name().to_owned();
Self {
path,
Expand All @@ -103,11 +215,11 @@ impl GenericPath {
&self.path
}

pub fn generics(&self) -> &[Type] {
pub fn generics(&self) -> &[GenericArgument] {
&self.generics
}

pub fn generics_mut(&mut self) -> &mut [Type] {
pub fn generics_mut(&mut self) -> &mut [GenericArgument] {
&mut self.generics
}

Expand All @@ -123,11 +235,15 @@ impl GenericPath {
&self.export_name
}

pub fn is_single_identifier(&self) -> bool {
self.generics.is_empty()
}

pub fn rename_for_config(&mut self, config: &Config, generic_params: &GenericParams) {
for generic in &mut self.generics {
generic.rename_for_config(config, generic_params);
}
if !generic_params.contains(&self.path) {
if !generic_params.iter().any(|param| param.name == self.path) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might be worth implementing a proper contains in GenericParams perhaps, if this check needs to be done in many places... For now it's just two so it's probably fine.

config.export.rename(&mut self.export_name);
}
}
Expand Down Expand Up @@ -156,8 +272,11 @@ impl GenericPath {
ref args,
..
}) => args.iter().try_skip_map(|x| match *x {
syn::GenericArgument::Type(ref x) => Type::load(x),
syn::GenericArgument::Type(ref x) => Ok(Type::load(x)?.map(GenericArgument::Type)),
syn::GenericArgument::Lifetime(_) => Ok(None),
syn::GenericArgument::Const(ref x) => {
Ok(Some(GenericArgument::Const(ArrayLength::load(x)?)))
}
_ => Err(format!("can't handle generic argument {:?}", x)),
})?,
syn::PathArguments::Parenthesized(_) => {
Expand Down
10 changes: 8 additions & 2 deletions src/bindgen/ir/item.rs
Expand Up @@ -9,7 +9,8 @@ use crate::bindgen::config::Config;
use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver;
use crate::bindgen::dependencies::Dependencies;
use crate::bindgen::ir::{
AnnotationSet, Cfg, Constant, Enum, OpaqueItem, Path, Static, Struct, Type, Typedef, Union,
AnnotationSet, Cfg, Constant, Enum, GenericArgument, OpaqueItem, Path, Static, Struct, Typedef,
Union,
};
use crate::bindgen::library::Library;
use crate::bindgen::monomorph::Monomorphs;
Expand Down Expand Up @@ -37,7 +38,12 @@ pub trait Item {
}
fn rename_for_config(&mut self, _config: &Config) {}
fn add_dependencies(&self, _library: &Library, _out: &mut Dependencies) {}
fn instantiate_monomorph(&self, _generics: &[Type], _library: &Library, _out: &mut Monomorphs) {
fn instantiate_monomorph(
&self,
_generics: &[GenericArgument],
_library: &Library,
_out: &mut Monomorphs,
) {
unreachable!("Cannot instantiate {} as a generic.", self.name())
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/bindgen/ir/opaque.rs
Expand Up @@ -8,8 +8,8 @@ use crate::bindgen::config::{Config, Language};
use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver;
use crate::bindgen::dependencies::Dependencies;
use crate::bindgen::ir::{
AnnotationSet, Cfg, ConditionWrite, Documentation, GenericParams, Item, ItemContainer, Path,
ToCondition, Type,
AnnotationSet, Cfg, ConditionWrite, Documentation, GenericArgument, GenericParams, Item,
ItemContainer, Path, ToCondition,
};
use crate::bindgen::library::Library;
use crate::bindgen::mangle;
Expand All @@ -35,7 +35,7 @@ impl OpaqueItem {
) -> Result<OpaqueItem, String> {
Ok(Self::new(
path,
GenericParams::new(generics),
GenericParams::load(generics)?,
Cfg::append(mod_cfg, Cfg::load(attrs)),
AnnotationSet::load(attrs).unwrap_or_else(|_| AnnotationSet::new()),
Documentation::load(attrs),
Expand Down Expand Up @@ -98,7 +98,7 @@ impl Item for OpaqueItem {

fn instantiate_monomorph(
&self,
generic_values: &[Type],
generic_values: &[GenericArgument],
library: &Library,
out: &mut Monomorphs,
) {
Expand Down