use super::annotations::Annotations;
use super::context::{BindgenContext, ItemId, PartialType};
use super::derive::{CanDeriveCopy, CanDeriveDebug, CanDeriveDefault};
use super::dot::DotAttributes;
use super::function::Function;
use super::item_kind::ItemKind;
use super::layout::Opaque;
use super::module::Module;
use super::template::AsNamed;
use super::traversal::{EdgeKind, Trace, Tracer};
use super::ty::{TemplateDeclaration, Type, TypeKind};
use clang;
use clang_sys;
use parse::{ClangItemParser, ClangSubItemParser, ParseError, ParseResult};
use std::cell::{Cell, RefCell};
use std::collections::BTreeSet;
use std::fmt::Write;
use std::io;
use std::iter;
use regex;
pub trait ItemCanonicalName {
fn canonical_name(&self, ctx: &BindgenContext) -> String;
}
pub trait ItemCanonicalPath {
fn namespace_aware_canonical_path(&self,
ctx: &BindgenContext)
-> Vec<String>;
fn canonical_path(&self, ctx: &BindgenContext) -> Vec<String>;
}
pub trait ItemAncestors {
fn ancestors<'a, 'b>(&self,
ctx: &'a BindgenContext<'b>)
-> ItemAncestorsIter<'a, 'b>;
}
cfg_if! {
if #[cfg(testing_only_extra_assertions)] {
type DebugOnlyItemSet = ItemSet;
} else {
struct DebugOnlyItemSet;
impl DebugOnlyItemSet {
fn new() -> Self {
DebugOnlyItemSet
}
fn contains(&self,_id: &ItemId) -> bool {
false
}
fn insert(&mut self, _id: ItemId) {}
}
}
}
pub struct ItemAncestorsIter<'a, 'b>
where 'b: 'a,
{
item: ItemId,
ctx: &'a BindgenContext<'b>,
seen: DebugOnlyItemSet,
}
impl<'a, 'b> ItemAncestorsIter<'a, 'b>
where 'b: 'a,
{
fn new(ctx: &'a BindgenContext<'b>, item: ItemId) -> Self {
ItemAncestorsIter {
item: item,
ctx: ctx,
seen: DebugOnlyItemSet::new(),
}
}
}
impl<'a, 'b> Iterator for ItemAncestorsIter<'a, 'b>
where 'b: 'a,
{
type Item = ItemId;
fn next(&mut self) -> Option<Self::Item> {
let item = self.ctx.resolve_item(self.item);
if item.parent_id() == self.item {
None
} else {
self.item = item.parent_id();
extra_assert!(!self.seen.contains(&item.id()));
self.seen.insert(item.id());
Some(item.id())
}
}
}
impl AsNamed for ItemId {
type Extra = ();
fn as_named(&self, ctx: &BindgenContext, _: &()) -> Option<ItemId> {
ctx.resolve_item(*self).as_named(ctx, &())
}
}
impl AsNamed for Item {
type Extra = ();
fn as_named(&self, ctx: &BindgenContext, _: &()) -> Option<ItemId> {
self.kind.as_named(ctx, self)
}
}
impl AsNamed for ItemKind {
type Extra = Item;
fn as_named(&self, ctx: &BindgenContext, item: &Item) -> Option<ItemId> {
match *self {
ItemKind::Type(ref ty) => ty.as_named(ctx, item),
ItemKind::Module(..) |
ItemKind::Function(..) |
ItemKind::Var(..) => None,
}
}
}
impl ItemCanonicalName for ItemId {
fn canonical_name(&self, ctx: &BindgenContext) -> String {
debug_assert!(ctx.in_codegen_phase(),
"You're not supposed to call this yet");
ctx.resolve_item(*self).canonical_name(ctx)
}
}
impl ItemCanonicalPath for ItemId {
fn namespace_aware_canonical_path(&self,
ctx: &BindgenContext)
-> Vec<String> {
debug_assert!(ctx.in_codegen_phase(),
"You're not supposed to call this yet");
ctx.resolve_item(*self).namespace_aware_canonical_path(ctx)
}
fn canonical_path(&self, ctx: &BindgenContext) -> Vec<String> {
debug_assert!(ctx.in_codegen_phase(),
"You're not supposed to call this yet");
ctx.resolve_item(*self).canonical_path(ctx)
}
}
impl ItemAncestors for ItemId {
fn ancestors<'a, 'b>(&self,
ctx: &'a BindgenContext<'b>)
-> ItemAncestorsIter<'a, 'b> {
ItemAncestorsIter::new(ctx, *self)
}
}
impl ItemAncestors for Item {
fn ancestors<'a, 'b>(&self,
ctx: &'a BindgenContext<'b>)
-> ItemAncestorsIter<'a, 'b> {
self.id().ancestors(ctx)
}
}
impl Trace for ItemId {
type Extra = ();
fn trace<T>(&self, ctx: &BindgenContext, tracer: &mut T, extra: &())
where T: Tracer,
{
ctx.resolve_item(*self).trace(ctx, tracer, extra);
}
}
impl Trace for Item {
type Extra = ();
fn trace<T>(&self, ctx: &BindgenContext, tracer: &mut T, _extra: &())
where T: Tracer,
{
if self.is_hidden(ctx) {
return;
}
match *self.kind() {
ItemKind::Type(ref ty) => {
if ty.should_be_traced_unconditionally() ||
!self.is_opaque(ctx) {
ty.trace(ctx, tracer, self);
}
}
ItemKind::Function(ref fun) => {
tracer.visit(fun.signature());
}
ItemKind::Var(ref var) => {
tracer.visit_kind(var.ty(), EdgeKind::VarType);
}
ItemKind::Module(_) => {
}
}
}
}
impl CanDeriveDebug for Item {
type Extra = ();
fn can_derive_debug(&self, ctx: &BindgenContext, _: ()) -> bool {
if self.detect_derive_debug_cycle.get() {
return true;
}
self.detect_derive_debug_cycle.set(true);
let result = ctx.options().derive_debug &&
match self.kind {
ItemKind::Type(ref ty) => {
if self.is_opaque(ctx) {
ty.layout(ctx)
.map_or(true, |l| l.opaque().can_derive_debug(ctx, ()))
} else {
ty.can_derive_debug(ctx, ())
}
}
_ => false,
};
self.detect_derive_debug_cycle.set(false);
result
}
}
impl CanDeriveDefault for Item {
type Extra = ();
fn can_derive_default(&self, ctx: &BindgenContext, _: ()) -> bool {
ctx.options().derive_default &&
match self.kind {
ItemKind::Type(ref ty) => {
if self.is_opaque(ctx) {
ty.layout(ctx)
.map_or(false,
|l| l.opaque().can_derive_default(ctx, ()))
} else {
ty.can_derive_default(ctx, ())
}
}
_ => false,
}
}
}
impl<'a> CanDeriveCopy<'a> for Item {
type Extra = ();
fn can_derive_copy(&self, ctx: &BindgenContext, _: ()) -> bool {
if self.detect_derive_copy_cycle.get() {
return true;
}
self.detect_derive_copy_cycle.set(true);
let result = match self.kind {
ItemKind::Type(ref ty) => {
if self.is_opaque(ctx) {
ty.layout(ctx)
.map_or(true, |l| l.opaque().can_derive_copy(ctx, ()))
} else {
ty.can_derive_copy(ctx, self)
}
}
_ => false,
};
self.detect_derive_copy_cycle.set(false);
result
}
fn can_derive_copy_in_array(&self, ctx: &BindgenContext, _: ()) -> bool {
match self.kind {
ItemKind::Type(ref ty) => {
if self.is_opaque(ctx) {
ty.layout(ctx)
.map_or(true, |l| {
l.opaque().can_derive_copy_in_array(ctx, ())
})
} else {
ty.can_derive_copy_in_array(ctx, self)
}
}
_ => false,
}
}
}
#[derive(Debug)]
pub struct Item {
id: ItemId,
local_id: Cell<Option<usize>>,
next_child_local_id: Cell<usize>,
canonical_name_cache: RefCell<Option<String>>,
comment: Option<String>,
annotations: Annotations,
parent_id: ItemId,
kind: ItemKind,
detect_derive_debug_cycle: Cell<bool>,
detect_derive_copy_cycle: Cell<bool>,
}
impl AsRef<ItemId> for Item {
fn as_ref(&self) -> &ItemId {
&self.id
}
}
impl Item {
pub fn new(id: ItemId,
comment: Option<String>,
annotations: Option<Annotations>,
parent_id: ItemId,
kind: ItemKind)
-> Self {
debug_assert!(id != parent_id || kind.is_module());
Item {
id: id,
local_id: Cell::new(None),
next_child_local_id: Cell::new(1),
canonical_name_cache: RefCell::new(None),
parent_id: parent_id,
comment: comment,
annotations: annotations.unwrap_or_default(),
kind: kind,
detect_derive_debug_cycle: Cell::new(false),
detect_derive_copy_cycle: Cell::new(false),
}
}
pub fn new_opaque_type(with_id: ItemId,
ty: &clang::Type,
ctx: &mut BindgenContext)
-> ItemId {
let ty = Opaque::from_clang_ty(ty);
let kind = ItemKind::Type(ty);
let parent = ctx.root_module();
ctx.add_item(Item::new(with_id, None, None, parent, kind), None, None);
with_id
}
pub fn id(&self) -> ItemId {
self.id
}
pub fn parent_id(&self) -> ItemId {
self.parent_id
}
pub fn set_parent_for_replacement(&mut self, id: ItemId) {
self.parent_id = id;
}
pub fn comment(&self) -> Option<&str> {
self.comment.as_ref().map(|c| &**c)
}
pub fn kind(&self) -> &ItemKind {
&self.kind
}
pub fn kind_mut(&mut self) -> &mut ItemKind {
&mut self.kind
}
pub fn local_id(&self, ctx: &BindgenContext) -> usize {
if self.local_id.get().is_none() {
let parent = ctx.resolve_item(self.parent_id);
let local_id = parent.next_child_local_id.get();
parent.next_child_local_id.set(local_id + 1);
self.local_id.set(Some(local_id));
}
self.local_id.get().unwrap()
}
pub fn is_toplevel(&self, ctx: &BindgenContext) -> bool {
if ctx.options().enable_cxx_namespaces && self.kind().is_module() &&
self.id() != ctx.root_module() {
return false;
}
let mut parent = self.parent_id;
loop {
let parent_item = match ctx.resolve_item_fallible(parent) {
Some(item) => item,
None => return false,
};
if parent_item.id() == ctx.root_module() {
return true;
} else if ctx.options().enable_cxx_namespaces ||
!parent_item.kind().is_module() {
return false;
}
parent = parent_item.parent_id();
}
}
pub fn expect_type(&self) -> &Type {
self.kind().expect_type()
}
pub fn as_type(&self) -> Option<&Type> {
self.kind().as_type()
}
pub fn expect_function(&self) -> &Function {
self.kind().expect_function()
}
pub fn is_module(&self) -> bool {
match self.kind {
ItemKind::Module(..) => true,
_ => false,
}
}
pub fn annotations(&self) -> &Annotations {
&self.annotations
}
pub fn is_hidden(&self, ctx: &BindgenContext) -> bool {
debug_assert!(ctx.in_codegen_phase(),
"You're not supposed to call this yet");
self.annotations.hide() ||
ctx.hidden_by_name(&self.canonical_path(ctx), self.id)
}
pub fn is_opaque(&self, ctx: &BindgenContext) -> bool {
debug_assert!(ctx.in_codegen_phase(),
"You're not supposed to call this yet");
self.annotations.opaque() ||
self.as_type().map_or(false, |ty| ty.is_opaque()) ||
ctx.opaque_by_name(&self.canonical_path(ctx))
}
pub fn is_type_ref(&self) -> bool {
self.as_type().map_or(false, |ty| ty.is_type_ref())
}
pub fn is_var(&self) -> bool {
match *self.kind() {
ItemKind::Var(..) => true,
_ => false,
}
}
pub fn name<'item, 'ctx>(&'item self,
ctx: &'item BindgenContext<'ctx>)
-> NameOptions<'item, 'ctx> {
NameOptions::new(self, ctx)
}
fn name_target(&self, ctx: &BindgenContext) -> ItemId {
let mut targets_seen = DebugOnlyItemSet::new();
let mut item = self;
loop {
extra_assert!(!targets_seen.contains(&item.id()));
targets_seen.insert(item.id());
if self.annotations().use_instead_of().is_some() {
return self.id();
}
match *item.kind() {
ItemKind::Type(ref ty) => {
match *ty.kind() {
TypeKind::ResolvedTypeRef(inner) => {
item = ctx.resolve_item(inner);
}
TypeKind::TemplateInstantiation(ref inst) => {
item = ctx.resolve_item(inst.template_definition());
}
_ => return item.id(),
}
}
_ => return item.id(),
}
}
}
fn func_name(&self) -> Option<&str> {
match *self.kind() {
ItemKind::Function(ref func) => Some(func.name()),
_ => None,
}
}
fn overload_index(&self, ctx: &BindgenContext) -> Option<usize> {
self.func_name().and_then(|func_name| {
let parent = ctx.resolve_item(self.parent_id());
if let ItemKind::Type(ref ty) = *parent.kind() {
if let TypeKind::Comp(ref ci) = *ty.kind() {
return ci.constructors()
.iter()
.position(|c| *c == self.id())
.or_else(|| {
ci.methods()
.iter()
.filter(|m| {
let item = ctx.resolve_item(m.signature());
let func = item.expect_function();
func.name() == func_name
})
.position(|m| m.signature() == self.id())
});
}
}
None
})
}
fn base_name(&self, ctx: &BindgenContext) -> String {
if let Some(path) = self.annotations().use_instead_of() {
return path.last().unwrap().clone();
}
match *self.kind() {
ItemKind::Var(ref var) => var.name().to_owned(),
ItemKind::Module(ref module) => {
module.name()
.map(ToOwned::to_owned)
.unwrap_or_else(|| {
format!("_bindgen_mod_{}", self.exposed_id(ctx))
})
}
ItemKind::Type(ref ty) => {
let name = match *ty.kind() {
TypeKind::ResolvedTypeRef(..) => panic!("should have resolved this in name_target()"),
_ => ty.name(),
};
name.map(ToOwned::to_owned)
.unwrap_or_else(|| {
format!("_bindgen_ty_{}", self.exposed_id(ctx))
})
}
ItemKind::Function(ref fun) => {
let mut name = fun.name().to_owned();
if let Some(idx) = self.overload_index(ctx) {
if idx > 0 {
write!(&mut name, "{}", idx).unwrap();
}
}
name
}
}
}
pub fn real_canonical_name(&self,
ctx: &BindgenContext,
opt: &NameOptions)
-> String {
let target = ctx.resolve_item(self.name_target(ctx));
if let Some(path) = target.annotations.use_instead_of() {
if ctx.options().enable_cxx_namespaces {
return path.last().unwrap().clone();
}
return path.join("_").to_owned();
}
let base_name = target.base_name(ctx);
if target.is_named(ctx, &()) {
return base_name;
}
let mut names: Vec<_> = target.parent_id()
.ancestors(ctx)
.filter(|id| *id != ctx.root_module())
.take_while(|id| {
!opt.within_namespaces || !ctx.resolve_item(*id).is_module()
})
.map(|id| {
let item = ctx.resolve_item(id);
let target = ctx.resolve_item(item.name_target(ctx));
target.base_name(ctx)
})
.filter(|name| !name.is_empty())
.collect();
names.reverse();
if !base_name.is_empty() {
names.push(base_name);
}
let name = names.join("_");
ctx.rust_mangle(&name).into_owned()
}
fn exposed_id(&self, ctx: &BindgenContext) -> String {
let ty_kind = self.kind().as_type().map(|t| t.kind());
if let Some(ty_kind) = ty_kind {
match *ty_kind {
TypeKind::Comp(..) |
TypeKind::Enum(..) => return self.local_id(ctx).to_string(),
_ => {}
}
}
format!("id_{}", self.id().as_usize())
}
pub fn as_module(&self) -> Option<&Module> {
match self.kind {
ItemKind::Module(ref module) => Some(module),
_ => None,
}
}
pub fn as_module_mut(&mut self) -> Option<&mut Module> {
match self.kind {
ItemKind::Module(ref mut module) => Some(module),
_ => None,
}
}
}
pub type ItemSet = BTreeSet<ItemId>;
impl DotAttributes for Item {
fn dot_attributes<W>(&self,
ctx: &BindgenContext,
out: &mut W)
-> io::Result<()>
where W: io::Write,
{
try!(writeln!(out,
"<tr><td>{:?}</td></tr>
<tr><td>name</td><td>{}</td></tr>",
self.id,
self.name(ctx).get()));
self.kind.dot_attributes(ctx, out)
}
}
impl TemplateDeclaration for ItemId {
fn self_template_params(&self,
ctx: &BindgenContext)
-> Option<Vec<ItemId>> {
ctx.resolve_item_fallible(*self)
.and_then(|item| item.self_template_params(ctx))
}
}
impl TemplateDeclaration for Item {
fn self_template_params(&self,
ctx: &BindgenContext)
-> Option<Vec<ItemId>> {
self.kind.self_template_params(ctx)
}
}
impl TemplateDeclaration for ItemKind {
fn self_template_params(&self,
ctx: &BindgenContext)
-> Option<Vec<ItemId>> {
match *self {
ItemKind::Type(ref ty) => ty.self_template_params(ctx),
ItemKind::Function(_) |
ItemKind::Module(_) |
ItemKind::Var(_) => None,
}
}
}
fn visit_child(cur: clang::Cursor,
id: ItemId,
ty: &clang::Type,
parent_id: Option<ItemId>,
ctx: &mut BindgenContext,
result: &mut Result<ItemId, ParseError>)
-> clang_sys::CXChildVisitResult {
use clang_sys::*;
if result.is_ok() {
return CXChildVisit_Break;
}
*result = Item::from_ty_with_id(id, ty, cur, parent_id, ctx);
match *result {
Ok(..) => CXChildVisit_Break,
Err(ParseError::Recurse) => {
cur.visit(|c| visit_child(c, id, ty, parent_id, ctx, result));
CXChildVisit_Continue
}
Err(ParseError::Continue) => CXChildVisit_Continue,
}
}
impl ClangItemParser for Item {
fn builtin_type(kind: TypeKind,
is_const: bool,
ctx: &mut BindgenContext)
-> ItemId {
match kind {
TypeKind::Void |
TypeKind::Int(..) |
TypeKind::Pointer(..) |
TypeKind::Float(..) => {}
_ => panic!("Unsupported builtin type"),
}
let ty = Type::new(None, None, kind, is_const);
let id = ctx.next_item_id();
let module = ctx.root_module();
ctx.add_item(Item::new(id, None, None, module, ItemKind::Type(ty)),
None,
None);
id
}
fn parse(cursor: clang::Cursor,
parent_id: Option<ItemId>,
ctx: &mut BindgenContext)
-> Result<ItemId, ParseError> {
use ir::function::Function;
use ir::module::Module;
use ir::var::Var;
use clang_sys::*;
if !cursor.is_valid() {
return Err(ParseError::Continue);
}
let comment = cursor.raw_comment();
let annotations = Annotations::new(&cursor);
let current_module = ctx.current_module();
let relevant_parent_id = parent_id.unwrap_or(current_module);
macro_rules! try_parse {
($what:ident) => {
match $what::parse(cursor, ctx) {
Ok(ParseResult::New(item, declaration)) => {
let id = ctx.next_item_id();
ctx.add_item(Item::new(id, comment, annotations,
relevant_parent_id,
ItemKind::$what(item)),
declaration,
Some(cursor));
return Ok(id);
}
Ok(ParseResult::AlreadyResolved(id)) => {
return Ok(id);
}
Err(ParseError::Recurse) => return Err(ParseError::Recurse),
Err(ParseError::Continue) => {},
}
}
}
try_parse!(Module);
try_parse!(Function);
try_parse!(Var);
{
let applicable_cursor = cursor.definition().unwrap_or(cursor);
match Item::from_ty(&applicable_cursor.cur_type(),
applicable_cursor,
parent_id,
ctx) {
Ok(ty) => return Ok(ty),
Err(ParseError::Recurse) => return Err(ParseError::Recurse),
Err(ParseError::Continue) => {}
}
}
if cursor.kind() == CXCursor_UnexposedDecl {
Err(ParseError::Recurse)
} else {
match cursor.kind() {
CXCursor_MacroDefinition |
CXCursor_MacroExpansion |
CXCursor_UsingDeclaration |
CXCursor_UsingDirective |
CXCursor_StaticAssert |
CXCursor_InclusionDirective => {
debug!("Unhandled cursor kind {:?}: {:?}",
cursor.kind(),
cursor);
}
_ => {
let spelling = cursor.spelling();
if !spelling.starts_with("operator") {
error!("Unhandled cursor kind {:?}: {:?}",
cursor.kind(),
cursor);
}
}
}
Err(ParseError::Continue)
}
}
fn from_ty_or_ref(ty: clang::Type,
location: clang::Cursor,
parent_id: Option<ItemId>,
ctx: &mut BindgenContext)
-> ItemId {
let id = ctx.next_item_id();
Self::from_ty_or_ref_with_id(id, ty, location, parent_id, ctx)
}
fn from_ty_or_ref_with_id(potential_id: ItemId,
ty: clang::Type,
location: clang::Cursor,
parent_id: Option<ItemId>,
ctx: &mut BindgenContext)
-> ItemId {
debug!("from_ty_or_ref_with_id: {:?} {:?}, {:?}, {:?}",
potential_id,
ty,
location,
parent_id);
if ctx.collected_typerefs() {
debug!("refs already collected, resolving directly");
return Item::from_ty_with_id(potential_id,
&ty,
location,
parent_id,
ctx)
.unwrap_or_else(|_| {
Item::new_opaque_type(potential_id, &ty, ctx)
});
}
if let Some(ty) = ctx.builtin_or_resolved_ty(potential_id,
parent_id,
&ty,
Some(location)) {
debug!("{:?} already resolved: {:?}", ty, location);
return ty;
}
debug!("New unresolved type reference: {:?}, {:?}", ty, location);
let is_const = ty.is_const();
let kind = TypeKind::UnresolvedTypeRef(ty, location, parent_id);
let current_module = ctx.current_module();
ctx.add_item(Item::new(potential_id,
None,
None,
parent_id.unwrap_or(current_module),
ItemKind::Type(Type::new(None,
None,
kind,
is_const))),
Some(clang::Cursor::null()),
None);
potential_id
}
fn from_ty(ty: &clang::Type,
location: clang::Cursor,
parent_id: Option<ItemId>,
ctx: &mut BindgenContext)
-> Result<ItemId, ParseError> {
let id = ctx.next_item_id();
Item::from_ty_with_id(id, ty, location, parent_id, ctx)
}
fn from_ty_with_id(id: ItemId,
ty: &clang::Type,
location: clang::Cursor,
parent_id: Option<ItemId>,
ctx: &mut BindgenContext)
-> Result<ItemId, ParseError> {
use clang_sys::*;
debug!("Item::from_ty_with_id: {:?}\n\
\tty = {:?},\n\
\tlocation = {:?}",
id,
ty,
location);
if ty.kind() == clang_sys::CXType_Unexposed ||
location.cur_type().kind() == clang_sys::CXType_Unexposed {
if ty.is_associated_type() ||
location.cur_type().is_associated_type() {
return Ok(Item::new_opaque_type(id, ty, ctx));
}
if let Some(id) = Item::named_type(Some(id), location, ctx) {
return Ok(id);
}
}
let decl = {
let decl = ty.declaration();
decl.definition().unwrap_or(decl)
};
let comment = decl.raw_comment()
.or_else(|| location.raw_comment());
let annotations = Annotations::new(&decl)
.or_else(|| Annotations::new(&location));
if let Some(ref annotations) = annotations {
if let Some(ref replaced) = annotations.use_instead_of() {
ctx.replace(replaced, id);
}
}
if let Some(ty) =
ctx.builtin_or_resolved_ty(id, parent_id, ty, Some(location)) {
return Ok(ty);
}
let mut valid_decl = decl.kind() != CXCursor_NoDeclFound;
let declaration_to_look_for = if valid_decl {
decl.canonical()
} else if location.kind() ==
CXCursor_ClassTemplate {
valid_decl = true;
location
} else {
decl
};
if valid_decl {
if let Some(partial) = ctx.currently_parsed_types()
.iter()
.find(|ty| *ty.decl() == declaration_to_look_for) {
debug!("Avoiding recursion parsing type: {:?}", ty);
return Ok(partial.id());
}
}
let current_module = ctx.current_module();
let partial_ty = PartialType::new(declaration_to_look_for, id);
if valid_decl {
ctx.begin_parsing(partial_ty);
}
let result = Type::from_clang_ty(id, ty, location, parent_id, ctx);
let relevant_parent_id = parent_id.unwrap_or(current_module);
let ret = match result {
Ok(ParseResult::AlreadyResolved(ty)) => Ok(ty),
Ok(ParseResult::New(item, declaration)) => {
ctx.add_item(Item::new(id,
comment,
annotations,
relevant_parent_id,
ItemKind::Type(item)),
declaration,
Some(location));
Ok(id)
}
Err(ParseError::Continue) => Err(ParseError::Continue),
Err(ParseError::Recurse) => {
debug!("Item::from_ty recursing in the ast");
let mut result = Err(ParseError::Recurse);
if valid_decl {
let finished = ctx.finish_parsing();
assert_eq!(*finished.decl(), declaration_to_look_for);
}
location.visit(|cur| {
visit_child(cur, id, ty, parent_id, ctx, &mut result)
});
if valid_decl {
let partial_ty = PartialType::new(declaration_to_look_for,
id);
ctx.begin_parsing(partial_ty);
}
if let Err(ParseError::Recurse) = result {
warn!("Unknown type, assuming named template type: \
id = {:?}; spelling = {}",
id,
ty.spelling());
Item::named_type(Some(id), location, ctx)
.map(Ok)
.unwrap_or(Err(ParseError::Recurse))
} else {
result
}
}
};
if valid_decl {
let partial_ty = ctx.finish_parsing();
assert_eq!(*partial_ty.decl(), declaration_to_look_for);
}
ret
}
fn named_type(with_id: Option<ItemId>,
location: clang::Cursor,
ctx: &mut BindgenContext)
-> Option<ItemId> {
let ty = location.cur_type();
debug!("Item::named_type:\n\
\twith_id = {:?},\n\
\tty = {} {:?},\n\
\tlocation: {:?}",
with_id,
ty.spelling(),
ty,
location);
if ty.kind() != clang_sys::CXType_Unexposed {
return None;
}
let ty_spelling = ty.spelling();
fn is_template_with_spelling(refd: &clang::Cursor,
spelling: &str)
-> bool {
lazy_static! {
static ref ANON_TYPE_PARAM_RE: regex::Regex =
regex::Regex::new(r"^type\-parameter\-\d+\-\d+$").unwrap();
}
if refd.kind() != clang_sys::CXCursor_TemplateTypeParameter {
return false;
}
let refd_spelling = refd.spelling();
refd_spelling == spelling ||
(refd_spelling.is_empty() && ANON_TYPE_PARAM_RE.is_match(spelling.as_ref()))
}
let definition = if is_template_with_spelling(&location,
&ty_spelling) {
location
} else if location.kind() ==
clang_sys::CXCursor_TypeRef {
match location.referenced() {
Some(refd) if is_template_with_spelling(&refd,
&ty_spelling) => refd,
_ => return None,
}
} else {
let mut definition = None;
location.visit(|child| {
let child_ty = child.cur_type();
if child_ty.kind() == clang_sys::CXCursor_TypeRef &&
child_ty.spelling() == ty_spelling {
match child.referenced() {
Some(refd) if is_template_with_spelling(&refd, &ty_spelling) => {
definition = Some(refd);
return clang_sys::CXChildVisit_Break;
}
_ => {}
}
}
clang_sys::CXChildVisit_Continue
});
if let Some(def) = definition {
def
} else {
return None;
}
};
assert!(is_template_with_spelling(&definition, &ty_spelling));
let parent = ctx.root_module();
if let Some(id) = ctx.get_named_type(&definition) {
if let Some(with_id) = with_id {
return Some(ctx.build_ty_wrapper(with_id, id, Some(parent), &ty));
} else {
return Some(id);
}
}
let name = ty_spelling.replace("const ", "")
.replace(".", "");
let id = with_id.unwrap_or_else(|| ctx.next_item_id());
let item = Item::new(id,
None,
None,
parent,
ItemKind::Type(Type::named(name)));
ctx.add_named_type(item, definition);
Some(id)
}
}
impl ItemCanonicalName for Item {
fn canonical_name(&self, ctx: &BindgenContext) -> String {
debug_assert!(ctx.in_codegen_phase(),
"You're not supposed to call this yet");
if self.canonical_name_cache.borrow().is_none() {
let in_namespace = ctx.options().enable_cxx_namespaces ||
ctx.options().disable_name_namespacing;
*self.canonical_name_cache.borrow_mut() = if in_namespace {
Some(self.name(ctx).within_namespaces().get())
} else {
Some(self.name(ctx).get())
};
}
return self.canonical_name_cache.borrow().as_ref().unwrap().clone();
}
}
impl ItemCanonicalPath for Item {
fn namespace_aware_canonical_path(&self,
ctx: &BindgenContext)
-> Vec<String> {
let path = self.canonical_path(ctx);
if ctx.options().enable_cxx_namespaces {
return path;
}
if ctx.options().disable_name_namespacing {
return vec![path.last().unwrap().clone()];
}
return vec![path[1..].join("_")];
}
fn canonical_path(&self, ctx: &BindgenContext) -> Vec<String> {
if let Some(path) = self.annotations().use_instead_of() {
let mut ret =
vec![ctx.resolve_item(ctx.root_module()).name(ctx).get()];
ret.extend_from_slice(path);
return ret;
}
let target = ctx.resolve_item(self.name_target(ctx));
let mut path: Vec<_> = target.ancestors(ctx)
.chain(iter::once(ctx.root_module()))
.map(|id| ctx.resolve_item(id))
.filter(|item| {
item.id() == target.id() ||
item.as_module().map_or(false, |module| {
!module.is_inline() ||
ctx.options().conservative_inline_namespaces
})
})
.map(|item| {
ctx.resolve_item(item.name_target(ctx))
.name(ctx)
.within_namespaces()
.get()
})
.collect();
path.reverse();
path
}
}
#[derive(Debug)]
pub struct NameOptions<'item, 'ctx>
where 'ctx: 'item,
{
item: &'item Item,
ctx: &'item BindgenContext<'ctx>,
within_namespaces: bool,
}
impl<'item, 'ctx> NameOptions<'item, 'ctx> {
pub fn new(item: &'item Item, ctx: &'item BindgenContext<'ctx>) -> Self {
NameOptions {
item: item,
ctx: ctx,
within_namespaces: false,
}
}
pub fn within_namespaces(&mut self) -> &mut Self {
self.within_namespaces = true;
self
}
pub fn get(&self) -> String {
self.item.real_canonical_name(self.ctx, self)
}
}