| 1 |
//! #[diplomat::attr] and other attributes |
| 2 |
|
| 3 |
use crate::ast; |
| 4 |
use crate::ast::attrs::{AttrInheritContext, DiplomatBackendAttrCfg, StandardAttribute}; |
| 5 |
use crate::hir::lowering::ErrorStore; |
| 6 |
use crate::hir::{ |
| 7 |
EnumVariant, LoweringError, Method, Mutability, OpaqueId, ReturnType, SelfType, SuccessType, |
| 8 |
Type, TypeDef, TypeId, |
| 9 |
}; |
| 10 |
use syn::Meta; |
| 11 |
|
| 12 |
pub use crate::ast::attrs::RenameAttr; |
| 13 |
|
| 14 |
/// Diplomat attribute that can be specified on items, methods, and enum variants. These |
| 15 |
/// can be used to control the codegen in a particular backend. |
| 16 |
/// |
| 17 |
/// Most of these are specified via `#[diplomat::attr(some cfg here, attrname)]`, where `some cfg here` |
| 18 |
/// can be used to pick which backends something applies to. |
| 19 |
#[non_exhaustive] |
| 20 |
#[derive(Clone, Default, Debug)] |
| 21 |
pub struct Attrs { |
| 22 |
/// "disable" this item: do not generate code for it in the backend |
| 23 |
/// |
| 24 |
/// This attribute is always inherited except to variants |
| 25 |
pub disable: bool, |
| 26 |
/// An optional namespace. None is equivalent to the root namespace. |
| 27 |
/// |
| 28 |
/// This attribute is inherited to types (and is not allowed elsewhere) |
| 29 |
pub namespace: Option<String>, |
| 30 |
/// Rename this item/method/variant |
| 31 |
/// |
| 32 |
/// This attribute is inherited except through methods and variants (and is not allowed on variants) |
| 33 |
pub rename: RenameAttr, |
| 34 |
/// Rename this item in the C ABI. This *must* be respected by backends. |
| 35 |
/// |
| 36 |
/// This attribute is inherited except through variants |
| 37 |
pub abi_rename: RenameAttr, |
| 38 |
/// This method is "special": it should generate something other than a regular method on the other side. |
| 39 |
/// This can be something like a constructor, an accessor, a stringifier etc. |
| 40 |
/// |
| 41 |
/// This attribute does not participate in inheritance and must always |
| 42 |
/// be specified on individual methods |
| 43 |
pub special_method: Option<SpecialMethod>, |
| 44 |
} |
| 45 |
|
| 46 |
/// Attributes that mark methods as "special" |
| 47 |
#[non_exhaustive] |
| 48 |
#[derive(Clone, Debug)] |
| 49 |
pub enum SpecialMethod { |
| 50 |
/// A constructor. |
| 51 |
/// |
| 52 |
/// Must return Self (or Result<Self> for backends with `fallible_constructors` enabled ) |
| 53 |
Constructor, |
| 54 |
/// A named constructor, with optional name. If the name isn't specified, it will be derived |
| 55 |
/// from the method name |
| 56 |
/// |
| 57 |
/// Must return Self (or Result<Self> for backends with `fallible_constructors` enabled ) |
| 58 |
NamedConstructor(Option<String>), |
| 59 |
|
| 60 |
/// A getter, with optional name. If the name isn't specified, it will be derived |
| 61 |
/// from the method name |
| 62 |
/// |
| 63 |
/// Must have no parameters and must return something. |
| 64 |
Getter(Option<String>), |
| 65 |
/// A setter, with optional name. If the name isn't specified, it will be derived |
| 66 |
/// from the method name |
| 67 |
/// |
| 68 |
/// Must have no return type (aside from potentially a `Result<(), _>`) and must have one parameter |
| 69 |
Setter(Option<String>), |
| 70 |
/// A stringifier. Must have no parameters and return a string (writeable) |
| 71 |
Stringifier, |
| 72 |
/// A comparison operator. Currently unsupported |
| 73 |
Comparison, |
| 74 |
/// An iterator (a type that is mutated to produce new values) |
| 75 |
Iterator, |
| 76 |
/// An iterable (a type that can produce an iterator) |
| 77 |
Iterable, |
| 78 |
/// Indexes into the type using an integer |
| 79 |
Indexer, |
| 80 |
} |
| 81 |
|
| 82 |
/// For special methods that affect type semantics, whether this type has this method. |
| 83 |
/// |
| 84 |
/// This will likely only contain a subset of special methods, but feel free to add more as needed. |
| 85 |
#[derive(Debug, Default)] |
| 86 |
#[non_exhaustive] |
| 87 |
pub struct SpecialMethodPresence { |
| 88 |
pub comparator: bool, |
| 89 |
/// If it is an iterator, the type it iterates over |
| 90 |
pub iterator: Option<SuccessType>, |
| 91 |
/// If it is an iterable, the iterator type it returns (*not* the type it iterates over, |
| 92 |
/// perform lookup on that type to access) |
| 93 |
pub iterable: Option<OpaqueId>, |
| 94 |
} |
| 95 |
|
| 96 |
/// Where the attribute was found. Some attributes are only allowed in some contexts |
| 97 |
/// (e.g. namespaces cannot be specified on methods) |
| 98 |
#[non_exhaustive] // might add module attrs in the future |
| 99 |
#[derive(Debug)] |
| 100 |
pub enum AttributeContext<'a, 'b> { |
| 101 |
Type(TypeDef<'a>), |
| 102 |
EnumVariant(&'a EnumVariant), |
| 103 |
Method(&'a Method, TypeId, &'b mut SpecialMethodPresence), |
| 104 |
Module, |
| 105 |
} |
| 106 |
|
| 107 |
impl Attrs { |
| 108 |
pub fn from_ast( |
| 109 |
ast: &ast::Attrs, |
| 110 |
validator: &(impl AttributeValidator + ?Sized), |
| 111 |
parent_attrs: &Attrs, |
| 112 |
errors: &mut ErrorStore, |
| 113 |
) -> Self { |
| 114 |
let mut this = parent_attrs.clone(); |
| 115 |
// Backends must support this since it applies to the macro/C code. |
| 116 |
// No special inheritance, was already appropriately inherited in AST |
| 117 |
this.abi_rename = ast.abi_rename.clone(); |
| 118 |
|
| 119 |
let support = validator.attrs_supported(); |
| 120 |
let backend = validator.primary_name(); |
| 121 |
for attr in &ast.attrs { |
| 122 |
let satisfies = match validator.satisfies_cfg(&attr.cfg) { |
| 123 |
Ok(satisfies) => satisfies, |
| 124 |
Err(e) => { |
| 125 |
errors.push(e); |
| 126 |
continue; |
| 127 |
} |
| 128 |
}; |
| 129 |
if satisfies { |
| 130 |
let path = attr.meta.path(); |
| 131 |
if let Some(path) = path.get_ident() { |
| 132 |
if path == "disable" { |
| 133 |
if let Meta::Path(_) = attr.meta { |
| 134 |
if this.disable { |
| 135 |
errors.push(LoweringError::Other( |
| 136 |
"Duplicate `disable` attribute".into(), |
| 137 |
)); |
| 138 |
} else if !support.disabling { |
| 139 |
errors.push(LoweringError::Other(format!( |
| 140 |
"`disable` not supported in backend {backend}" |
| 141 |
))) |
| 142 |
} else { |
| 143 |
this.disable = true; |
| 144 |
} |
| 145 |
} else { |
| 146 |
errors.push(LoweringError::Other( |
| 147 |
"`disable` must be a simple path".into(), |
| 148 |
)) |
| 149 |
} |
| 150 |
} else if path == "rename" { |
| 151 |
match RenameAttr::from_meta(&attr.meta) { |
| 152 |
Ok(rename) => { |
| 153 |
// We use the override extend mode: a single ast::Attrs |
| 154 |
// will have had these attributes inherited into the list by appending |
| 155 |
// to the end; so a later attribute in the list is more pertinent. |
| 156 |
this.rename.extend(&rename); |
| 157 |
} |
| 158 |
Err(e) => errors.push(LoweringError::Other(format!( |
| 159 |
"`rename` attr failed to parse: {e:?}" |
| 160 |
))), |
| 161 |
} |
| 162 |
} else if path == "namespace" { |
| 163 |
if !support.namespacing { |
| 164 |
errors.push(LoweringError::Other(format!( |
| 165 |
"`namespace` not supported in backend {backend}" |
| 166 |
))); |
| 167 |
continue; |
| 168 |
} |
| 169 |
match StandardAttribute::from_meta(&attr.meta) { |
| 170 |
Ok(StandardAttribute::String(s)) if s.is_empty() => { |
| 171 |
this.namespace = None |
| 172 |
} |
| 173 |
Ok(StandardAttribute::String(s)) => this.namespace = Some(s), |
| 174 |
Ok(_) | Err(_) => { |
| 175 |
errors.push(LoweringError::Other( |
| 176 |
"`namespace` must have a single string parameter".to_string(), |
| 177 |
)); |
| 178 |
continue; |
| 179 |
} |
| 180 |
} |
| 181 |
} else if path == "constructor" |
| 182 |
|| path == "stringifier" |
| 183 |
|| path == "comparison" |
| 184 |
|| path == "iterable" |
| 185 |
|| path == "iterator" |
| 186 |
|| path == "indexer" |
| 187 |
{ |
| 188 |
if let Some(ref existing) = this.special_method { |
| 189 |
errors.push(LoweringError::Other(format!( |
| 190 |
"Multiple special method markers found on the same method, found {path} and {existing:?}" |
| 191 |
))); |
| 192 |
continue; |
| 193 |
} |
| 194 |
let kind = if path == "constructor" { |
| 195 |
if !support.constructors { |
| 196 |
errors.push(LoweringError::Other(format!( |
| 197 |
"constructor not supported in backend {backend}" |
| 198 |
))) |
| 199 |
} |
| 200 |
SpecialMethod::Constructor |
| 201 |
} else if path == "stringifier" { |
| 202 |
if !support.stringifiers { |
| 203 |
errors.push(LoweringError::Other(format!( |
| 204 |
"stringifier not supported in backend {backend}" |
| 205 |
))) |
| 206 |
} |
| 207 |
SpecialMethod::Stringifier |
| 208 |
} else if path == "iterable" { |
| 209 |
if !support.iterables { |
| 210 |
errors.push(LoweringError::Other(format!( |
| 211 |
"iterable not supported in backend {backend}" |
| 212 |
))) |
| 213 |
} |
| 214 |
SpecialMethod::Iterable |
| 215 |
} else if path == "iterator" { |
| 216 |
if !support.iterators { |
| 217 |
errors.push(LoweringError::Other(format!( |
| 218 |
"iterator not supported in backend {backend}" |
| 219 |
))) |
| 220 |
} |
| 221 |
SpecialMethod::Iterator |
| 222 |
} else if path == "indexer" { |
| 223 |
if !support.indexing { |
| 224 |
errors.push(LoweringError::Other(format!( |
| 225 |
"indexing not supported in backend {backend}" |
| 226 |
))) |
| 227 |
} |
| 228 |
SpecialMethod::Indexer |
| 229 |
} else { |
| 230 |
if !support.comparators { |
| 231 |
errors.push(LoweringError::Other(format!( |
| 232 |
"comparison overload not supported in backend {backend}" |
| 233 |
))) |
| 234 |
} |
| 235 |
SpecialMethod::Comparison |
| 236 |
}; |
| 237 |
|
| 238 |
this.special_method = Some(kind); |
| 239 |
} else if path == "named_constructor" || path == "getter" || path == "setter" { |
| 240 |
if let Some(ref existing) = this.special_method { |
| 241 |
errors.push(LoweringError::Other(format!( |
| 242 |
"Multiple special method markers found on the same method, found {path} and {existing:?}" |
| 243 |
))); |
| 244 |
continue; |
| 245 |
} |
| 246 |
let kind = if path == "named_constructor" { |
| 247 |
if !support.named_constructors { |
| 248 |
errors.push(LoweringError::Other(format!( |
| 249 |
"named constructors not supported in backend {backend}" |
| 250 |
))) |
| 251 |
} |
| 252 |
SpecialMethod::NamedConstructor |
| 253 |
} else if path == "getter" { |
| 254 |
if !support.accessors { |
| 255 |
errors.push(LoweringError::Other(format!( |
| 256 |
"accessors not supported in backend {backend}" |
| 257 |
))) |
| 258 |
} |
| 259 |
SpecialMethod::Getter |
| 260 |
} else { |
| 261 |
if !support.accessors { |
| 262 |
errors.push(LoweringError::Other(format!( |
| 263 |
"accessors not supported in backend {backend}" |
| 264 |
))) |
| 265 |
} |
| 266 |
SpecialMethod::Setter |
| 267 |
}; |
| 268 |
match StandardAttribute::from_meta(&attr.meta) { |
| 269 |
Ok(StandardAttribute::String(s)) => { |
| 270 |
this.special_method = Some(kind(Some(s))) |
| 271 |
} |
| 272 |
Ok(StandardAttribute::Empty) => this.special_method = Some(kind(None)), |
| 273 |
Ok(_) | Err(_) => { |
| 274 |
errors.push(LoweringError::Other(format!( |
| 275 |
"`{path}` must have a single string parameter or no parameter", |
| 276 |
))); |
| 277 |
continue; |
| 278 |
} |
| 279 |
} |
| 280 |
} else { |
| 281 |
errors.push(LoweringError::Other(format!( |
| 282 |
"Unknown diplomat attribute {path}: expected one of: `disable, rename, namespace, constructor, stringifier, comparison, named_constructor, getter, setter, indexer`" |
| 283 |
))); |
| 284 |
} |
| 285 |
} else { |
| 286 |
errors.push(LoweringError::Other(format!( |
| 287 |
"Unknown diplomat attribute {path:?}: expected one of: `disable, rename, namespace, constructor, stringifier, comparison, named_constructor, getter, setter, indexer`" |
| 288 |
))); |
| 289 |
} |
| 290 |
} |
| 291 |
} |
| 292 |
|
| 293 |
this |
| 294 |
} |
| 295 |
|
| 296 |
/// Validate that this attribute is allowed in this context |
| 297 |
pub(crate) fn validate( |
| 298 |
&self, |
| 299 |
validator: &(impl AttributeValidator + ?Sized), |
| 300 |
mut context: AttributeContext, |
| 301 |
errors: &mut ErrorStore, |
| 302 |
) { |
| 303 |
// use an exhaustive destructure so new attributes are handled |
| 304 |
let Attrs { |
| 305 |
disable, |
| 306 |
namespace, |
| 307 |
rename: _, |
| 308 |
abi_rename: _, |
| 309 |
special_method, |
| 310 |
} = &self; |
| 311 |
|
| 312 |
if *disable && matches!(context, AttributeContext::EnumVariant(..)) { |
| 313 |
errors.push(LoweringError::Other( |
| 314 |
"`disable` cannot be used on enum variants".into(), |
| 315 |
)) |
| 316 |
} |
| 317 |
|
| 318 |
if let Some(ref special) = special_method { |
| 319 |
if let AttributeContext::Method(method, self_id, ref mut special_method_presence) = |
| 320 |
context |
| 321 |
{ |
| 322 |
match special { |
| 323 |
SpecialMethod::Constructor | SpecialMethod::NamedConstructor(..) => { |
| 324 |
if method.param_self.is_some() { |
| 325 |
errors.push(LoweringError::Other( |
| 326 |
"Constructors must not accept a self parameter".to_string(), |
| 327 |
)) |
| 328 |
} |
| 329 |
let output = method.output.success_type(); |
| 330 |
match method.output { |
| 331 |
ReturnType::Infallible(_) => (), |
| 332 |
ReturnType::Fallible(..) => { |
| 333 |
if !validator.attrs_supported().fallible_constructors { |
| 334 |
errors.push(LoweringError::Other( |
| 335 |
"This backend doesn't support fallible constructors" |
| 336 |
.to_string(), |
| 337 |
)) |
| 338 |
} |
| 339 |
} |
| 340 |
ReturnType::Nullable(..) => { |
| 341 |
errors.push(LoweringError::Other("Diplomat doesn't support turning nullable methods into constructors".to_string())); |
| 342 |
} |
| 343 |
} |
| 344 |
|
| 345 |
if let SuccessType::OutType(t) = &output { |
| 346 |
if t.id() != Some(self_id) { |
| 347 |
errors.push(LoweringError::Other( |
| 348 |
"Constructors must return Self!".to_string(), |
| 349 |
)); |
| 350 |
} |
| 351 |
} else { |
| 352 |
errors.push(LoweringError::Other( |
| 353 |
"Constructors must return Self!".to_string(), |
| 354 |
)); |
| 355 |
} |
| 356 |
} |
| 357 |
SpecialMethod::Getter(_) => { |
| 358 |
if !method.params.is_empty() { |
| 359 |
errors |
| 360 |
.push(LoweringError::Other("Getter cannot have parameters".into())); |
| 361 |
} |
| 362 |
|
| 363 |
// Currently does not forbid nullable getters, could if desired |
| 364 |
} |
| 365 |
|
| 366 |
SpecialMethod::Setter(_) => { |
| 367 |
if !matches!(method.output.success_type(), SuccessType::Unit) { |
| 368 |
errors.push(LoweringError::Other("Setters must return unit".into())); |
| 369 |
} |
| 370 |
if method.params.len() != 1 { |
| 371 |
errors.push(LoweringError::Other( |
| 372 |
"Setter must have exactly one parameter".into(), |
| 373 |
)) |
| 374 |
} |
| 375 |
|
| 376 |
// Currently does not forbid fallible setters, could if desired |
| 377 |
} |
| 378 |
SpecialMethod::Stringifier => { |
| 379 |
if !method.params.is_empty() { |
| 380 |
errors |
| 381 |
.push(LoweringError::Other("Getter cannot have parameters".into())); |
| 382 |
} |
| 383 |
if !matches!(method.output.success_type(), SuccessType::Writeable) { |
| 384 |
errors.push(LoweringError::Other( |
| 385 |
"Stringifier must return Writeable".into(), |
| 386 |
)); |
| 387 |
} |
| 388 |
} |
| 389 |
SpecialMethod::Comparison => { |
| 390 |
if method.params.len() != 1 { |
| 391 |
errors.push(LoweringError::Other( |
| 392 |
"Comparator must have single parameter".into(), |
| 393 |
)); |
| 394 |
} |
| 395 |
if special_method_presence.comparator { |
| 396 |
errors.push(LoweringError::Other( |
| 397 |
"Cannot define two comparators on the same type".into(), |
| 398 |
)); |
| 399 |
} |
| 400 |
special_method_presence.comparator = true; |
| 401 |
// In the long run we can actually support heterogeneous comparators. Not a priority right now. |
| 402 |
const COMPARATOR_ERROR: &str = |
| 403 |
"Comparator's parameter must be identical to self"; |
| 404 |
if let Some(ref selfty) = method.param_self { |
| 405 |
if let Some(param) = method.params.first() { |
| 406 |
match (&selfty.ty, ¶m.ty) { |
| 407 |
(SelfType::Opaque(p), Type::Opaque(p2)) => { |
| 408 |
if p.tcx_id != p2.tcx_id { |
| 409 |
errors.push(LoweringError::Other( |
| 410 |
COMPARATOR_ERROR.into(), |
| 411 |
)); |
| 412 |
} |
| 413 |
|
| 414 |
if p.owner.mutability != Mutability::Immutable |
| 415 |
|| p2.owner.mutability != Mutability::Immutable |
| 416 |
{ |
| 417 |
errors.push(LoweringError::Other( |
| 418 |
"comparators must accept immutable parameters" |
| 419 |
.into(), |
| 420 |
)); |
| 421 |
} |
| 422 |
|
| 423 |
if p2.optional.0 { |
| 424 |
errors.push(LoweringError::Other( |
| 425 |
"comparators must accept non-optional parameters" |
| 426 |
.into(), |
| 427 |
)); |
| 428 |
} |
| 429 |
} |
| 430 |
(SelfType::Struct(p), Type::Struct(p2)) => { |
| 431 |
if p.tcx_id != p2.tcx_id { |
| 432 |
errors.push(LoweringError::Other( |
| 433 |
COMPARATOR_ERROR.into(), |
| 434 |
)); |
| 435 |
} |
| 436 |
} |
| 437 |
(SelfType::Enum(p), Type::Enum(p2)) => { |
| 438 |
if p.tcx_id != p2.tcx_id { |
| 439 |
errors.push(LoweringError::Other( |
| 440 |
COMPARATOR_ERROR.into(), |
| 441 |
)); |
| 442 |
} |
| 443 |
} |
| 444 |
_ => { |
| 445 |
errors.push(LoweringError::Other(COMPARATOR_ERROR.into())); |
| 446 |
} |
| 447 |
} |
| 448 |
} |
| 449 |
} else { |
| 450 |
errors |
| 451 |
.push(LoweringError::Other("Comparator must be non-static".into())); |
| 452 |
} |
| 453 |
} |
| 454 |
SpecialMethod::Iterator => { |
| 455 |
if special_method_presence.iterator.is_some() { |
| 456 |
errors.push(LoweringError::Other( |
| 457 |
"Cannot mark type as iterator twice".into(), |
| 458 |
)); |
| 459 |
} |
| 460 |
if !method.params.is_empty() { |
| 461 |
errors.push(LoweringError::Other( |
| 462 |
"Iterators cannot take parameters".into(), |
| 463 |
)) |
| 464 |
} |
| 465 |
// In theory we could support struct and enum iterators. The benefit is slight: |
| 466 |
// it generates probably inefficient code whilst being rather weird when it comes to the |
| 467 |
// "structs and enums convert across the boundary" norm for backends. |
| 468 |
// |
| 469 |
// Essentially, the `&mut self` behavior won't work right. |
| 470 |
// |
| 471 |
// Furthermore, in some backends (like Dart) defining an iterator may requiring adding fields, |
| 472 |
// which may not be possible for enums, and would still be an odd-one-out field for structs.g s |
| 473 |
if let Some(this) = &method.param_self { |
| 474 |
if !matches!(this.ty, SelfType::Opaque(..)) { |
| 475 |
errors.push(LoweringError::Other( |
| 476 |
"Iterators only allowed on opaques".into(), |
| 477 |
)) |
| 478 |
} |
| 479 |
} else { |
| 480 |
errors.push(LoweringError::Other("Iterators must take self".into())) |
| 481 |
} |
| 482 |
|
| 483 |
if let ReturnType::Nullable(ref o) = method.output { |
| 484 |
if let SuccessType::Unit = o { |
| 485 |
errors.push(LoweringError::Other( |
| 486 |
"Iterator method must return something".into(), |
| 487 |
)); |
| 488 |
} |
| 489 |
special_method_presence.iterator = Some(o.clone()); |
| 490 |
} else if let ReturnType::Infallible(SuccessType::OutType( |
| 491 |
crate::hir::OutType::Opaque( |
| 492 |
ref o @ crate::hir::OpaquePath { |
| 493 |
optional: crate::hir::Optional(true), |
| 494 |
.. |
| 495 |
}, |
| 496 |
), |
| 497 |
)) = method.output |
| 498 |
{ |
| 499 |
let mut o = o.clone(); |
| 500 |
o.optional = crate::hir::Optional(false); |
| 501 |
|
| 502 |
special_method_presence.iterator = |
| 503 |
Some(SuccessType::OutType(crate::hir::OutType::Opaque(o))); |
| 504 |
} else { |
| 505 |
errors.push(LoweringError::Other( |
| 506 |
"Iterator method must return nullable value".into(), |
| 507 |
)); |
| 508 |
} |
| 509 |
} |
| 510 |
SpecialMethod::Iterable => { |
| 511 |
if special_method_presence.iterable.is_some() { |
| 512 |
errors.push(LoweringError::Other( |
| 513 |
"Cannot mark type as iterable twice".into(), |
| 514 |
)); |
| 515 |
} |
| 516 |
if !method.params.is_empty() { |
| 517 |
errors.push(LoweringError::Other( |
| 518 |
"Iterables cannot take parameters".into(), |
| 519 |
)) |
| 520 |
} |
| 521 |
if method.param_self.is_none() { |
| 522 |
errors.push(LoweringError::Other("Iterables must take self".into())) |
| 523 |
} |
| 524 |
|
| 525 |
match method.output.success_type() { |
| 526 |
SuccessType::OutType(ty) => { |
| 527 |
if let Some(TypeId::Opaque(id)) = ty.id() { |
| 528 |
special_method_presence.iterable = Some(id); |
| 529 |
} else { |
| 530 |
errors.push(LoweringError::Other( |
| 531 |
"Iterables must return a custom opaque type".into(), |
| 532 |
)) |
| 533 |
} |
| 534 |
} |
| 535 |
_ => errors.push(LoweringError::Other( |
| 536 |
"Iterables must return a custom type".into(), |
| 537 |
)), |
| 538 |
} |
| 539 |
} |
| 540 |
SpecialMethod::Indexer => { |
| 541 |
if method.params.len() != 1 { |
| 542 |
errors.push(LoweringError::Other( |
| 543 |
"Indexer must have exactly one parameter".into(), |
| 544 |
)); |
| 545 |
} |
| 546 |
|
| 547 |
if method.output.success_type().is_unit() { |
| 548 |
errors.push(LoweringError::Other("Indexer must return a value".into())); |
| 549 |
} |
| 550 |
} |
| 551 |
} |
| 552 |
} else { |
| 553 |
errors.push(LoweringError::Other(format!("Special method (type {special:?}) not allowed on non-method context {context:?}"))) |
| 554 |
} |
| 555 |
} |
| 556 |
|
| 557 |
if namespace.is_some() |
| 558 |
&& matches!( |
| 559 |
context, |
| 560 |
AttributeContext::Method(..) | AttributeContext::EnumVariant(..) |
| 561 |
) |
| 562 |
{ |
| 563 |
errors.push(LoweringError::Other( |
| 564 |
"`namespace` can only be used on types".to_string(), |
| 565 |
)); |
| 566 |
} |
| 567 |
} |
| 568 |
|
| 569 |
pub(crate) fn for_inheritance(&self, context: AttrInheritContext) -> Attrs { |
| 570 |
let rename = self.rename.attrs_for_inheritance(context, false); |
| 571 |
|
| 572 |
// Disabling shouldn't inherit to variants |
| 573 |
let disable = if context == AttrInheritContext::Variant { |
| 574 |
false |
| 575 |
} else { |
| 576 |
self.disable |
| 577 |
}; |
| 578 |
let namespace = if matches!( |
| 579 |
context, |
| 580 |
AttrInheritContext::Module | AttrInheritContext::Type |
| 581 |
) { |
| 582 |
self.namespace.clone() |
| 583 |
} else { |
| 584 |
None |
| 585 |
}; |
| 586 |
|
| 587 |
Attrs { |
| 588 |
disable, |
| 589 |
rename, |
| 590 |
namespace, |
| 591 |
// Was already inherited on the AST side |
| 592 |
abi_rename: Default::default(), |
| 593 |
// Never inherited |
| 594 |
special_method: None, |
| 595 |
} |
| 596 |
} |
| 597 |
} |
| 598 |
|
| 599 |
#[non_exhaustive] |
| 600 |
#[derive(Copy, Clone, Debug, Default)] |
| 601 |
pub struct BackendAttrSupport { |
| 602 |
pub disabling: bool, |
| 603 |
pub renaming: bool, |
| 604 |
pub namespacing: bool, |
| 605 |
pub constructors: bool, |
| 606 |
pub named_constructors: bool, |
| 607 |
pub fallible_constructors: bool, |
| 608 |
pub accessors: bool, |
| 609 |
pub stringifiers: bool, |
| 610 |
pub comparators: bool, |
| 611 |
pub memory_sharing: bool, |
| 612 |
pub iterators: bool, |
| 613 |
pub iterables: bool, |
| 614 |
pub indexing: bool, |
| 615 |
// more to be added: namespace, etc |
| 616 |
} |
| 617 |
|
| 618 |
impl BackendAttrSupport { |
| 619 |
#[cfg(test)] |
| 620 |
fn all_true() -> Self { |
| 621 |
Self { |
| 622 |
disabling: true, |
| 623 |
renaming: true, |
| 624 |
namespacing: true, |
| 625 |
constructors: true, |
| 626 |
named_constructors: true, |
| 627 |
fallible_constructors: true, |
| 628 |
accessors: true, |
| 629 |
stringifiers: true, |
| 630 |
comparators: true, |
| 631 |
memory_sharing: true, |
| 632 |
iterators: true, |
| 633 |
iterables: true, |
| 634 |
indexing: true, |
| 635 |
} |
| 636 |
} |
| 637 |
} |
| 638 |
|
| 639 |
/// Defined by backends when validating attributes |
| 640 |
pub trait AttributeValidator { |
| 641 |
/// The primary name of the backend, for use in diagnostics |
| 642 |
fn primary_name(&self) -> &str; |
| 643 |
/// Does this backend satisfy `cfg(backend_name)`? |
| 644 |
/// (Backends are allowed to satisfy multiple backend names, useful when there |
| 645 |
/// are multiple backends for a language) |
| 646 |
fn is_backend(&self, backend_name: &str) -> bool; |
| 647 |
/// does this backend satisfy cfg(name = value)? |
| 648 |
fn is_name_value(&self, name: &str, value: &str) -> Result<bool, LoweringError>; |
| 649 |
/// What backedn attrs does this support? |
| 650 |
fn attrs_supported(&self) -> BackendAttrSupport; |
| 651 |
|
| 652 |
/// Provided, checks if type satisfies a `DiplomatBackendAttrCfg` |
| 653 |
fn satisfies_cfg(&self, cfg: &DiplomatBackendAttrCfg) -> Result<bool, LoweringError> { |
| 654 |
Ok(match *cfg { |
| 655 |
DiplomatBackendAttrCfg::Not(ref c) => !self.satisfies_cfg(c)?, |
| 656 |
DiplomatBackendAttrCfg::Any(ref cs) => { |
| 657 |
for c in cs { |
| 658 |
if self.satisfies_cfg(c)? { |
| 659 |
return Ok(true); |
| 660 |
} |
| 661 |
} |
| 662 |
false |
| 663 |
} |
| 664 |
DiplomatBackendAttrCfg::All(ref cs) => { |
| 665 |
for c in cs { |
| 666 |
if !self.satisfies_cfg(c)? { |
| 667 |
return Ok(false); |
| 668 |
} |
| 669 |
} |
| 670 |
true |
| 671 |
} |
| 672 |
DiplomatBackendAttrCfg::Star => true, |
| 673 |
DiplomatBackendAttrCfg::BackendName(ref n) => self.is_backend(n), |
| 674 |
DiplomatBackendAttrCfg::NameValue(ref n, ref v) => self.is_name_value(n, v)?, |
| 675 |
}) |
| 676 |
} |
| 677 |
|
| 678 |
// Provided, constructs an attribute |
| 679 |
fn attr_from_ast( |
| 680 |
&self, |
| 681 |
ast: &ast::Attrs, |
| 682 |
parent_attrs: &Attrs, |
| 683 |
errors: &mut ErrorStore, |
| 684 |
) -> Attrs { |
| 685 |
Attrs::from_ast(ast, self, parent_attrs, errors) |
| 686 |
} |
| 687 |
|
| 688 |
// Provided: validates an attribute in the context in which it was constructed |
| 689 |
fn validate(&self, attrs: &Attrs, context: AttributeContext, errors: &mut ErrorStore) { |
| 690 |
attrs.validate(self, context, errors) |
| 691 |
} |
| 692 |
} |
| 693 |
|
| 694 |
/// A basic attribute validator |
| 695 |
#[non_exhaustive] |
| 696 |
#[derive(Default)] |
| 697 |
pub struct BasicAttributeValidator { |
| 698 |
/// The primary name of this backend (should be unique, ideally) |
| 699 |
pub backend_name: String, |
| 700 |
/// The attributes supported |
| 701 |
pub support: BackendAttrSupport, |
| 702 |
/// Additional names for this backend |
| 703 |
pub other_backend_names: Vec<String>, |
| 704 |
/// override is_name_value() |
| 705 |
#[allow(clippy::type_complexity)] // dyn fn is not that complex |
| 706 |
pub is_name_value: Option<Box<dyn Fn(&str, &str) -> bool>>, |
| 707 |
} |
| 708 |
|
| 709 |
impl BasicAttributeValidator { |
| 710 |
pub fn new(backend_name: &str) -> Self { |
| 711 |
BasicAttributeValidator { |
| 712 |
backend_name: backend_name.into(), |
| 713 |
..Self::default() |
| 714 |
} |
| 715 |
} |
| 716 |
} |
| 717 |
|
| 718 |
impl AttributeValidator for BasicAttributeValidator { |
| 719 |
fn primary_name(&self) -> &str { |
| 720 |
&self.backend_name |
| 721 |
} |
| 722 |
fn is_backend(&self, backend_name: &str) -> bool { |
| 723 |
self.backend_name == backend_name |
| 724 |
|| self.other_backend_names.iter().any(|n| n == backend_name) |
| 725 |
} |
| 726 |
fn is_name_value(&self, name: &str, value: &str) -> Result<bool, LoweringError> { |
| 727 |
Ok(if name == "supports" { |
| 728 |
// destructure so new fields are forced to be added |
| 729 |
let BackendAttrSupport { |
| 730 |
disabling, |
| 731 |
renaming, |
| 732 |
namespacing, |
| 733 |
constructors, |
| 734 |
named_constructors, |
| 735 |
fallible_constructors, |
| 736 |
accessors, |
| 737 |
stringifiers, |
| 738 |
comparators, |
| 739 |
memory_sharing, |
| 740 |
iterators, |
| 741 |
iterables, |
| 742 |
indexing, |
| 743 |
} = self.support; |
| 744 |
match value { |
| 745 |
"disabling" => disabling, |
| 746 |
"renaming" => renaming, |
| 747 |
"namespacing" => namespacing, |
| 748 |
"constructors" => constructors, |
| 749 |
"named_constructors" => named_constructors, |
| 750 |
"fallible_constructors" => fallible_constructors, |
| 751 |
"accessors" => accessors, |
| 752 |
"stringifiers" => stringifiers, |
| 753 |
"comparators" => comparators, |
| 754 |
"memory_sharing" => memory_sharing, |
| 755 |
"iterators" => iterators, |
| 756 |
"iterables" => iterables, |
| 757 |
"indexing" => indexing, |
| 758 |
_ => { |
| 759 |
return Err(LoweringError::Other(format!( |
| 760 |
"Unknown supports = value found: {value}" |
| 761 |
))) |
| 762 |
} |
| 763 |
} |
| 764 |
} else if let Some(ref nv) = self.is_name_value { |
| 765 |
nv(name, value) |
| 766 |
} else { |
| 767 |
false |
| 768 |
}) |
| 769 |
} |
| 770 |
fn attrs_supported(&self) -> BackendAttrSupport { |
| 771 |
self.support |
| 772 |
} |
| 773 |
} |
| 774 |
|
| 775 |
#[cfg(test)] |
| 776 |
mod tests { |
| 777 |
use crate::hir; |
| 778 |
use std::fmt::Write; |
| 779 |
|
| 780 |
macro_rules! uitest_lowering_attr { |
| 781 |
($($file:tt)*) => { |
| 782 |
let parsed: syn::File = syn::parse_quote! { $($file)* }; |
| 783 |
let custom_types = crate::ast::File::from(&parsed); |
| 784 |
let env = custom_types.all_types(); |
| 785 |
|
| 786 |
let mut output = String::new(); |
| 787 |
|
| 788 |
|
| 789 |
let mut attr_validator = hir::BasicAttributeValidator::new("tests"); |
| 790 |
attr_validator.support = hir::BackendAttrSupport::all_true(); |
| 791 |
match hir::TypeContext::from_ast(&env, attr_validator) { |
| 792 |
Ok(_context) => (), |
| 793 |
Err(e) => { |
| 794 |
for (ctx, err) in e { |
| 795 |
writeln!(&mut output, "Lowering error in {ctx}: {err}").unwrap(); |
| 796 |
} |
| 797 |
} |
| 798 |
}; |
| 799 |
insta::with_settings!({}, { |
| 800 |
insta::assert_snapshot!(output) |
| 801 |
}); |
| 802 |
} |
| 803 |
} |
| 804 |
|
| 805 |
#[test] |
| 806 |
fn test_comparator() { |
| 807 |
uitest_lowering_attr! { |
| 808 |
#[diplomat::bridge] |
| 809 |
mod ffi { |
| 810 |
use std::cmp; |
| 811 |
|
| 812 |
#[diplomat::opaque] |
| 813 |
struct Opaque; |
| 814 |
|
| 815 |
struct Struct { |
| 816 |
field: u8 |
| 817 |
} |
| 818 |
|
| 819 |
|
| 820 |
impl Opaque { |
| 821 |
#[diplomat::attr(*, comparison)] |
| 822 |
pub fn comparator_static(other: &Opaque) -> cmp::Ordering { |
| 823 |
todo!() |
| 824 |
} |
| 825 |
#[diplomat::attr(*, comparison)] |
| 826 |
pub fn comparator_none(&self) -> cmp::Ordering { |
| 827 |
todo!() |
| 828 |
} |
| 829 |
#[diplomat::attr(*, comparison)] |
| 830 |
pub fn comparator_othertype(other: Struct) -> cmp::Ordering { |
| 831 |
todo!() |
| 832 |
} |
| 833 |
#[diplomat::attr(*, comparison)] |
| 834 |
pub fn comparator_badreturn(&self, other: &Opaque) -> u8 { |
| 835 |
todo!() |
| 836 |
} |
| 837 |
#[diplomat::attr(*, comparison)] |
| 838 |
pub fn comparison_correct(&self, other: &Opaque) -> cmp::Ordering { |
| 839 |
todo!() |
| 840 |
} |
| 841 |
pub fn comparison_unmarked(&self, other: &Opaque) -> cmp::Ordering { |
| 842 |
todo!() |
| 843 |
} |
| 844 |
pub fn ordering_wrong(&self, other: cmp::Ordering) { |
| 845 |
todo!() |
| 846 |
} |
| 847 |
#[diplomat::attr(*, comparison)] |
| 848 |
pub fn comparison_mut(&self, other: &mut Opaque) -> cmp::Ordering { |
| 849 |
todo!() |
| 850 |
} |
| 851 |
#[diplomat::attr(*, comparison)] |
| 852 |
pub fn comparison_opt(&self, other: Option<&Opaque>) -> cmp::Ordering { |
| 853 |
todo!() |
| 854 |
} |
| 855 |
} |
| 856 |
|
| 857 |
impl Struct { |
| 858 |
#[diplomat::attr(*, comparison)] |
| 859 |
pub fn comparison_other(self, other: &Opaque) -> cmp::Ordering { |
| 860 |
todo!() |
| 861 |
} |
| 862 |
#[diplomat::attr(*, comparison)] |
| 863 |
pub fn comparison_correct(self, other: Self) -> cmp::Ordering { |
| 864 |
todo!() |
| 865 |
} |
| 866 |
} |
| 867 |
} |
| 868 |
} |
| 869 |
} |
| 870 |
|
| 871 |
#[test] |
| 872 |
fn test_iterator() { |
| 873 |
uitest_lowering_attr! { |
| 874 |
#[diplomat::bridge] |
| 875 |
mod ffi { |
| 876 |
|
| 877 |
#[diplomat::opaque] |
| 878 |
struct Opaque(Vec<u8>); |
| 879 |
#[diplomat::opaque] |
| 880 |
struct OpaqueIterator<'a>(std::slice::Iter<'a>); |
| 881 |
|
| 882 |
|
| 883 |
impl Opaque { |
| 884 |
#[diplomat::attr(*, iterable)] |
| 885 |
pub fn iterable<'a>(&'a self) -> Box<OpaqueIterator<'a>> { |
| 886 |
Box::new(OpaqueIterator(self.0.iter())) |
| 887 |
} |
| 888 |
} |
| 889 |
|
| 890 |
impl OpaqueIterator { |
| 891 |
#[diplomat::attr(*, iterator)] |
| 892 |
pub fn next(&mut self) -> Option<u8> { |
| 893 |
self.0.next() |
| 894 |
} |
| 895 |
} |
| 896 |
|
| 897 |
#[diplomat::opaque] |
| 898 |
struct Broken; |
| 899 |
|
| 900 |
impl Broken { |
| 901 |
#[diplomat::attr(*, iterable)] |
| 902 |
pub fn iterable_no_return(&self) {} |
| 903 |
#[diplomat::attr(*, iterable)] |
| 904 |
pub fn iterable_no_self() -> Box<BrokenIterator> { todo!() } |
| 905 |
|
| 906 |
#[diplomat::attr(*, iterable)] |
| 907 |
pub fn iterable_non_custom(&self) -> u8 { todo!() } |
| 908 |
} |
| 909 |
|
| 910 |
#[diplomat::opaque] |
| 911 |
struct BrokenIterator; |
| 912 |
|
| 913 |
impl BrokenIterator { |
| 914 |
#[diplomat::attr(*, iterator)] |
| 915 |
pub fn iterator_no_return(&self) {} |
| 916 |
#[diplomat::attr(*, iterator)] |
| 917 |
pub fn iterator_no_self() -> Option<u8> { todo!() } |
| 918 |
|
| 919 |
#[diplomat::attr(*, iterator)] |
| 920 |
pub fn iterator_no_option(&self) -> u8 { todo!() } |
| 921 |
} |
| 922 |
} |
| 923 |
} |
| 924 |
} |
| 925 |
} |