| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
use std::collections::HashMap; |
| 6 |
use std::io::Write; |
| 7 |
|
| 8 |
use syn::ext::IdentExt; |
| 9 |
|
| 10 |
use crate::bindgen::cdecl; |
| 11 |
use crate::bindgen::config::{Config, Language, Layout}; |
| 12 |
use crate::bindgen::declarationtyperesolver::DeclarationTypeResolver; |
| 13 |
use crate::bindgen::dependencies::Dependencies; |
| 14 |
use crate::bindgen::ir::{ |
| 15 |
AnnotationSet, Cfg, ConditionWrite, Documentation, GenericPath, Path, ToCondition, Type, |
| 16 |
}; |
| 17 |
use crate::bindgen::library::Library; |
| 18 |
use crate::bindgen::monomorph::Monomorphs; |
| 19 |
use crate::bindgen::rename::{IdentifierType, RenameRule}; |
| 20 |
use crate::bindgen::reserved; |
| 21 |
use crate::bindgen::utilities::IterHelpers; |
| 22 |
use crate::bindgen::writer::{Source, SourceWriter}; |
| 23 |
|
| 24 |
#[derive(Debug, Clone)] |
| 25 |
pub struct FunctionArgument { |
| 26 |
pub name: Option<String>, |
| 27 |
pub ty: Type, |
| 28 |
pub array_length: Option<String>, |
| 29 |
} |
| 30 |
|
| 31 |
#[derive(Debug, Clone)] |
| 32 |
pub struct Function { |
| 33 |
pub path: Path, |
| 34 |
/// Path to the self-type of the function |
| 35 |
/// If the function is a method, this will contain the path of the type in the impl block |
| 36 |
pub self_type_path: Option<Path>, |
| 37 |
pub ret: Type, |
| 38 |
pub args: Vec<FunctionArgument>, |
| 39 |
pub extern_decl: bool, |
| 40 |
pub cfg: Option<Cfg>, |
| 41 |
pub annotations: AnnotationSet, |
| 42 |
pub documentation: Documentation, |
| 43 |
pub never_return: bool, |
| 44 |
} |
| 45 |
|
| 46 |
impl Function { |
| 47 |
pub fn load( |
| 48 |
path: Path, |
| 49 |
self_type_path: Option<&Path>, |
| 50 |
sig: &syn::Signature, |
| 51 |
extern_decl: bool, |
| 52 |
attrs: &[syn::Attribute], |
| 53 |
mod_cfg: Option<&Cfg>, |
| 54 |
) -> Result<Function, String> { |
| 55 |
let mut args = sig.inputs.iter().try_skip_map(|x| x.as_argument())?; |
| 56 |
|
| 57 |
let (mut ret, never_return) = Type::load_from_output(&sig.output)?; |
| 58 |
|
| 59 |
if let Some(self_path) = self_type_path { |
| 60 |
for arg in &mut args { |
| 61 |
arg.ty.replace_self_with(self_path); |
| 62 |
} |
| 63 |
ret.replace_self_with(self_path); |
| 64 |
} |
| 65 |
|
| 66 |
Ok(Function { |
| 67 |
path, |
| 68 |
self_type_path: self_type_path.cloned(), |
| 69 |
ret, |
| 70 |
args, |
| 71 |
extern_decl, |
| 72 |
cfg: Cfg::append(mod_cfg, Cfg::load(attrs)), |
| 73 |
annotations: AnnotationSet::load(attrs)?, |
| 74 |
documentation: Documentation::load(attrs), |
| 75 |
never_return, |
| 76 |
}) |
| 77 |
} |
| 78 |
|
| 79 |
pub fn swift_name(&self, config: &Config) -> Option<String> { |
| 80 |
if config.language == Language::Cython { |
| 81 |
return None; |
| 82 |
} |
| 83 |
// If the symbol name starts with the type name, separate the two components with '.' |
| 84 |
// so that Swift recognises the association between the method and the type |
| 85 |
let (ref type_prefix, ref type_name) = match self.self_type_path { |
| 86 |
Some(ref type_name) => { |
| 87 |
let type_name = type_name.to_string(); |
| 88 |
if !self.path.name().starts_with(&type_name) { |
| 89 |
return Some(self.path.to_string()); |
| 90 |
} |
| 91 |
(format!("{}.", type_name), type_name) |
| 92 |
} |
| 93 |
None => ("".to_string(), "".to_string()), |
| 94 |
}; |
| 95 |
|
| 96 |
let item_name = self |
| 97 |
.path |
| 98 |
.name() |
| 99 |
.trim_start_matches(type_name) |
| 100 |
.trim_start_matches('_'); |
| 101 |
|
| 102 |
let item_args = { |
| 103 |
let mut items = Vec::with_capacity(self.args.len()); |
| 104 |
for arg in self.args.iter() { |
| 105 |
items.push(format!("{}:", arg.name.as_ref()?.as_str())); |
| 106 |
} |
| 107 |
items.join("") |
| 108 |
}; |
| 109 |
Some(format!("{}{}({})", type_prefix, item_name, item_args)) |
| 110 |
} |
| 111 |
|
| 112 |
pub fn path(&self) -> &Path { |
| 113 |
&self.path |
| 114 |
} |
| 115 |
|
| 116 |
pub fn simplify_standard_types(&mut self, config: &Config) { |
| 117 |
self.ret.simplify_standard_types(config); |
| 118 |
for arg in &mut self.args { |
| 119 |
arg.ty.simplify_standard_types(config); |
| 120 |
} |
| 121 |
} |
| 122 |
|
| 123 |
pub fn add_dependencies(&self, library: &Library, out: &mut Dependencies) { |
| 124 |
self.ret.add_dependencies(library, out); |
| 125 |
for arg in &self.args { |
| 126 |
arg.ty.add_dependencies(library, out); |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
pub fn add_monomorphs(&self, library: &Library, out: &mut Monomorphs) { |
| 131 |
self.ret.add_monomorphs(library, out); |
| 132 |
for arg in &self.args { |
| 133 |
arg.ty.add_monomorphs(library, out); |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
pub fn mangle_paths(&mut self, monomorphs: &Monomorphs) { |
| 138 |
self.ret.mangle_paths(monomorphs); |
| 139 |
for arg in &mut self.args { |
| 140 |
arg.ty.mangle_paths(monomorphs); |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
pub fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) { |
| 145 |
self.ret.resolve_declaration_types(resolver); |
| 146 |
for arg in &mut self.args { |
| 147 |
arg.ty.resolve_declaration_types(resolver); |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
pub fn rename_for_config(&mut self, config: &Config) { |
| 152 |
// Rename the types used in arguments |
| 153 |
let generic_params = Default::default(); |
| 154 |
self.ret.rename_for_config(config, &generic_params); |
| 155 |
|
| 156 |
// Apply rename rules to argument names |
| 157 |
let rules = self |
| 158 |
.annotations |
| 159 |
.parse_atom::<RenameRule>("rename-all") |
| 160 |
.unwrap_or(config.function.rename_args); |
| 161 |
|
| 162 |
if let Some(r) = rules.not_none() { |
| 163 |
let args = std::mem::take(&mut self.args); |
| 164 |
self.args = args |
| 165 |
.into_iter() |
| 166 |
.map(|arg| { |
| 167 |
let name = arg |
| 168 |
.name |
| 169 |
.map(|n| r.apply(&n, IdentifierType::FunctionArg).into_owned()); |
| 170 |
FunctionArgument { |
| 171 |
name, |
| 172 |
ty: arg.ty, |
| 173 |
array_length: None, |
| 174 |
} |
| 175 |
}) |
| 176 |
.collect() |
| 177 |
} |
| 178 |
|
| 179 |
// Escape C/C++ reserved keywords used in argument names, and |
| 180 |
// recursively rename argument types. |
| 181 |
for arg in &mut self.args { |
| 182 |
arg.ty.rename_for_config(config, &generic_params); |
| 183 |
if let Some(ref mut name) = arg.name { |
| 184 |
reserved::escape(name); |
| 185 |
} |
| 186 |
} |
| 187 |
|
| 188 |
// Save the array length of the pointer arguments which need to use |
| 189 |
// the C-array notation |
| 190 |
if let Some(tuples) = self.annotations.list("ptrs-as-arrays") { |
| 191 |
let mut ptrs_as_arrays: HashMap<String, String> = HashMap::new(); |
| 192 |
for str_tuple in tuples { |
| 193 |
let parts: Vec<&str> = str_tuple[1..str_tuple.len() - 1] |
| 194 |
.split(';') |
| 195 |
.map(|x| x.trim()) |
| 196 |
.collect(); |
| 197 |
if parts.len() != 2 { |
| 198 |
warn!( |
| 199 |
"{:?} does not follow the correct syntax, so the annotation is being ignored", |
| 200 |
parts |
| 201 |
); |
| 202 |
continue; |
| 203 |
} |
| 204 |
ptrs_as_arrays.insert(parts[0].to_string(), parts[1].to_string()); |
| 205 |
} |
| 206 |
|
| 207 |
for arg in &mut self.args { |
| 208 |
match arg.ty { |
| 209 |
Type::Ptr { .. } => {} |
| 210 |
_ => continue, |
| 211 |
} |
| 212 |
let name = match arg.name { |
| 213 |
Some(ref name) => name, |
| 214 |
None => continue, |
| 215 |
}; |
| 216 |
arg.array_length = ptrs_as_arrays.get(name).cloned(); |
| 217 |
} |
| 218 |
} |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
impl Source for Function { |
| 223 |
fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) { |
| 224 |
fn write_1<W: Write>(func: &Function, config: &Config, out: &mut SourceWriter<W>) { |
| 225 |
let prefix = config.function.prefix(&func.annotations); |
| 226 |
let postfix = config.function.postfix(&func.annotations); |
| 227 |
|
| 228 |
let condition = func.cfg.to_condition(config); |
| 229 |
condition.write_before(config, out); |
| 230 |
|
| 231 |
func.documentation.write(config, out); |
| 232 |
|
| 233 |
if func.extern_decl { |
| 234 |
out.write("extern "); |
| 235 |
} else { |
| 236 |
if let Some(ref prefix) = prefix { |
| 237 |
write!(out, "{} ", prefix); |
| 238 |
} |
| 239 |
if func.annotations.must_use(config) { |
| 240 |
if let Some(ref anno) = config.function.must_use { |
| 241 |
write!(out, "{} ", anno); |
| 242 |
} |
| 243 |
} |
| 244 |
} |
| 245 |
cdecl::write_func(out, func, Layout::Horizontal, config); |
| 246 |
|
| 247 |
if !func.extern_decl { |
| 248 |
if let Some(ref postfix) = postfix { |
| 249 |
write!(out, " {}", postfix); |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
if let Some(ref swift_name_macro) = config.function.swift_name_macro { |
| 254 |
if let Some(swift_name) = func.swift_name(config) { |
| 255 |
write!(out, " {}({})", swift_name_macro, swift_name); |
| 256 |
} |
| 257 |
} |
| 258 |
|
| 259 |
out.write(";"); |
| 260 |
|
| 261 |
condition.write_after(config, out); |
| 262 |
} |
| 263 |
|
| 264 |
fn write_2<W: Write>(func: &Function, config: &Config, out: &mut SourceWriter<W>) { |
| 265 |
let prefix = config.function.prefix(&func.annotations); |
| 266 |
let postfix = config.function.postfix(&func.annotations); |
| 267 |
|
| 268 |
let condition = func.cfg.to_condition(config); |
| 269 |
|
| 270 |
condition.write_before(config, out); |
| 271 |
|
| 272 |
func.documentation.write(config, out); |
| 273 |
|
| 274 |
if func.extern_decl { |
| 275 |
out.write("extern "); |
| 276 |
} else { |
| 277 |
if let Some(ref prefix) = prefix { |
| 278 |
write!(out, "{}", prefix); |
| 279 |
out.new_line(); |
| 280 |
} |
| 281 |
if func.annotations.must_use(config) { |
| 282 |
if let Some(ref anno) = config.function.must_use { |
| 283 |
write!(out, "{}", anno); |
| 284 |
out.new_line(); |
| 285 |
} |
| 286 |
} |
| 287 |
} |
| 288 |
cdecl::write_func(out, func, Layout::Vertical, config); |
| 289 |
if !func.extern_decl { |
| 290 |
if let Some(ref postfix) = postfix { |
| 291 |
out.new_line(); |
| 292 |
write!(out, "{}", postfix); |
| 293 |
} |
| 294 |
} |
| 295 |
|
| 296 |
if let Some(ref swift_name_macro) = config.function.swift_name_macro { |
| 297 |
if let Some(swift_name) = func.swift_name(config) { |
| 298 |
write!(out, " {}({})", swift_name_macro, swift_name); |
| 299 |
} |
| 300 |
} |
| 301 |
|
| 302 |
out.write(";"); |
| 303 |
|
| 304 |
condition.write_after(config, out); |
| 305 |
} |
| 306 |
|
| 307 |
match config.function.args { |
| 308 |
Layout::Horizontal => write_1(self, config, out), |
| 309 |
Layout::Vertical => write_2(self, config, out), |
| 310 |
Layout::Auto => { |
| 311 |
if !out.try_write(|out| write_1(self, config, out), config.line_length) { |
| 312 |
write_2(self, config, out) |
| 313 |
} |
| 314 |
} |
| 315 |
} |
| 316 |
} |
| 317 |
} |
| 318 |
|
| 319 |
trait SynFnArgHelpers { |
| 320 |
fn as_argument(&self) -> Result<Option<FunctionArgument>, String>; |
| 321 |
} |
| 322 |
|
| 323 |
fn gen_self_type(receiver: &syn::Receiver) -> Type { |
| 324 |
let self_ty = Type::Path(GenericPath::self_path()); |
| 325 |
if receiver.reference.is_none() { |
| 326 |
return self_ty; |
| 327 |
} |
| 328 |
|
| 329 |
let is_const = receiver.mutability.is_none(); |
| 330 |
Type::Ptr { |
| 331 |
ty: Box::new(self_ty), |
| 332 |
is_const, |
| 333 |
is_nullable: false, |
| 334 |
is_ref: false, |
| 335 |
} |
| 336 |
} |
| 337 |
|
| 338 |
impl SynFnArgHelpers for syn::FnArg { |
| 339 |
fn as_argument(&self) -> Result<Option<FunctionArgument>, String> { |
| 340 |
match *self { |
| 341 |
syn::FnArg::Typed(syn::PatType { |
| 342 |
ref pat, ref ty, .. |
| 343 |
}) => { |
| 344 |
let name = match **pat { |
| 345 |
syn::Pat::Wild(..) => None, |
| 346 |
syn::Pat::Ident(syn::PatIdent { ref ident, .. }) => { |
| 347 |
Some(ident.unraw().to_string()) |
| 348 |
} |
| 349 |
_ => { |
| 350 |
return Err(format!( |
| 351 |
"Parameter has an unsupported argument name: {:?}", |
| 352 |
pat |
| 353 |
)) |
| 354 |
} |
| 355 |
}; |
| 356 |
let ty = match Type::load(ty)? { |
| 357 |
Some(x) => x, |
| 358 |
None => return Ok(None), |
| 359 |
}; |
| 360 |
if let Type::Array(..) = ty { |
| 361 |
return Err("Array as function arguments are not supported".to_owned()); |
| 362 |
} |
| 363 |
Ok(Some(FunctionArgument { |
| 364 |
name, |
| 365 |
ty, |
| 366 |
array_length: None, |
| 367 |
})) |
| 368 |
} |
| 369 |
syn::FnArg::Receiver(ref receiver) => Ok(Some(FunctionArgument { |
| 370 |
name: Some("self".to_string()), |
| 371 |
ty: gen_self_type(receiver), |
| 372 |
array_length: None, |
| 373 |
})), |
| 374 |
} |
| 375 |
} |
| 376 |
} |