Skip to content
This repository was archived by the owner on Nov 26, 2020. It is now read-only.
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions grust/generators/sys_crate.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,6 @@ def _prepare_walk(self, node, chain):
context=node)
return False
return True

def get_mapper(self):
return self._mapper
24 changes: 24 additions & 0 deletions grust/genmain.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@
from .generators.sys_crate import SysCrateWriter
from .output import FileOutput, DirectOutput
from . import __version__ as version
from .mapping import sys_crate_name
from .mapping import RawMapper

def output_file(name):
if name == '-':
Expand All @@ -53,6 +55,8 @@ def _create_arg_parser():
help='add directory to include search path')
parser.add_argument('-t', '--template',
help='name of the custom template file')
parser.add_argument('-c', '--cargo', dest='gen_cargo', action='store_true',
help='generate a Cargo build description')
return parser

def generator_main():
Expand Down Expand Up @@ -112,4 +116,24 @@ def generator_main():
if error_count > 0:
raise SystemExit(2)

if opts.gen_cargo:
if opts.template is not None:
sys.exit('can only generate cargo build description without custom template')
if not isinstance(output, FileOutput):
sys.exit('can only generate cargo build description with file output')

cargo_file = os.path.join(os.path.dirname(output.filename()), 'Cargo.toml')
cargo_template = tmpl_lookup.get_template('cargo/cargo.tmpl')

result = cargo_template.render_unicode(mapper=gen.get_mapper(),
pkgname=sys_crate_name(transformer.namespace),
version=transformer.namespace.version)

crate_output = output_file(cargo_file)

with crate_output as out:
try:
out.write(result)
except Exception:
raise SystemExit(1)
return 0
48 changes: 48 additions & 0 deletions grust/mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,7 @@ def _unwrap_call_signature_ctype(type_container):
if ctype is None:
raise MappingError('parameter {}: C type attribute is missing'.format(type_container.argname))
if (isinstance(type_container, ast.Parameter)
and not isinstance(type_container.type, ast.Array)
and type_container.direction in (ast.PARAM_DIRECTION_OUT,
ast.PARAM_DIRECTION_INOUT)
and not type_container.caller_allocates):
Expand Down Expand Up @@ -872,6 +873,53 @@ def map_field_type(self, field):
.format(field.name, typenode))
return self._map_type(field.type, nullable=True)

def _struct_field_type_is_valid(self, field_type):
if field_type is None:
return False
if isinstance(field_type, ast.Union):
return False
if isinstance(field_type, ast.Array):
return self._struct_field_type_is_valid(field_type.element_type)
if isinstance(field_type, ast.Record):
return self.struct_is_valid(field_type)
if isinstance(field_type, ast.Type) and field_type.target_giname:
if not self.node_is_mappable(field_type):
return False
if field_type.ctype is None or not field_type.ctype.endswith('*'):
crate,name = self._lookup_giname(field_type.target_giname)
return self._struct_field_type_is_valid(crate.namespace.names[name])
return True

def struct_is_valid(self, node):
if isinstance(node, ast.Union):
return False
for field in node.fields:
if field.bits is not None:
return False
if not self._struct_field_type_is_valid(field.type):
return False
return True

def node_is_mappable(self, node):
if isinstance(node, ast.Type) and node == ast.TYPE_VALIST:
return False
if isinstance(node, ast.TypeContainer):
return self.node_is_mappable(node.type)
if isinstance(node, ast.Alias):
return self.node_is_mappable(node.target)
if isinstance(node, ast.Callable):
if any([not self.node_is_mappable(param) for param in node.parameters]):
return False
return self.node_is_mappable(node.retval)
if isinstance(node, ast.List) and self.crate.local_name != 'glib':
return self.node_is_mappable(node.element_type)
if isinstance(node, ast.Array):
return self.node_is_mappable(node.element_type)
if isinstance(node, ast.Type) and node.target_giname:
crate,name = self._lookup_giname(node.target_giname)
return self.node_is_mappable(crate.namespace.names[name])
return True

def map_parameter_type(self, parameter):
"""Return the Rust FFI type syntax for a function parameter.

Expand Down
3 changes: 3 additions & 0 deletions grust/output.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ def __init__(self, filename, mode='w', encoding=None, newline=None):
'newline': newline
}

def filename(self):
return self._filename

def __enter__(self):
dirname, basename = os.path.split(self._filename)
if sys.version_info.major >= 3:
Expand Down
22 changes: 22 additions & 0 deletions grust/templates/cargo/cargo.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[package]
name = "${pkgname}"
version = "0.0.1"

[lib]
path = "lib.rs"

[dependencies.libc]
git = "https://github.com/rust-lang/libc.git"

[dependencies.grust]
git = "https://github.com/gi-rust/grust.git"

[dependencies.gtypes]
git = "https://github.com/gi-rust/gtypes.git"

% for xc in mapper.extern_crates():
% if xc.name is not 'libc':
[dependencies.${xc.name}]
path = "../${xc.name}"
% endif
% endfor
22 changes: 16 additions & 6 deletions grust/templates/sys/crate.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ def indenter(amount):
ast.Constant: constant,
ast.Record: struct,
ast.Class: struct,
ast.Union: struct,
ast.Interface: interface,
ast.Enum: enum,
ast.Bitfield: flags
Expand Down Expand Up @@ -93,8 +94,7 @@ def indenter(amount):
continue
if node.name in self.attr.ignore_names:
continue
if any(param.type == ast.TYPE_VALIST for param in node.parameters):
# Functions with a va_list parameter are usable only in C
if not mapper.node_is_mappable(node):
continue
functions.append(node)

Expand Down Expand Up @@ -180,12 +180,16 @@ extern {
raise ConsistencyError(
'C type name {} conflicts with a fundamental type'
.format(node.ctype))
if not mapper.node_is_mappable(node):
return ''
%>
pub type ${node.ctype} = ${mapper.map_aliased_type(node)};
</%def>\
##
<%def name="callback(node)">
% if mapper.node_is_mappable(node):
pub type ${node.ctype} = ${mapper.map_callback(node)};
% endif
</%def>\
##
<%def name="constant(node)">
Expand All @@ -203,11 +207,15 @@ pub struct ${node.ctype}(gpointer);
pub enum ${node.ctype} { }
% else:
#[repr(C)]
% if not mapper.struct_is_valid(node):
pub struct ${node.ctype};
Copy link
Member

Choose a reason for hiding this comment

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

This might work for objects and some boxed types, but I wouldn't like to get unusable types for copyable values. What I did in the few crate-specific templates I created in repo gi-rust/crates is suppress the unmappable structures and place manual representations in the crate template. With support for unions available in stable Rust, there will be less need for these overrides.

Bit fields could be automated too, if there is a equivalent #[repr(C)] guaranteed by the C standard.

% else:
pub struct ${node.ctype} {
% for field in node.fields:
% for field in node.fields:
${'' if field.private else 'pub '}${sanitize_ident(field.name)}: ${mapper.map_field_type(field)},
% endfor
% endfor
}
% endif
% endif
</%def>\
##
Expand Down Expand Up @@ -307,11 +315,13 @@ extern {
type=mapper.map_parameter_type(param))
for param in parameters]
%>\
% if mapper.node_is_mappable(node):
pub fn ${node.symbol}(${', '.join(param_list)})\
% if node.retval.type != ast.TYPE_NONE:
% if node.retval.type != ast.TYPE_NONE:
-> ${mapper.map_return_type(node.retval)}\
% endif
% endif
;
% endif
</%def>\
##
<%def name="cfg_attr(cfg)">\
Expand Down