1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
/*!
`def_mod!` provides a familiar syntax to the standard module declarations, but with the added benefit of being able
to easily define implementation routes and to statically verify module exports.
---
```rust
extern crate def_mod;
use def_mod::def_mod;
def_mod! {
// This has the exact same behaviour as Rust's.
mod my_mod;
// Much like the one above, it also has the same effect as Rust's.
mod my_first_mod {
// It also checks to see if a method with the type `fn(u32) -> u8` was exported.
// It will fail to compile if it finds none.
fn method(_: u32) -> u8;
// Much like the method declaration from above, this will check to see if a type was exported.
type MyStruct;
// This will also check to see if the type `MyOtherStruct` was export.
type MyOtherStruct {
// This will check if this method exists on this type. (MyOtherStruct::method)
fn method(_: u32) -> u8;
}
}
// Attributes are declared like normal.
#[cfg(windows)]
mod my_second_mod;
// When declaring an attribute, you can optionally add a path.
// This path is then used as the path attribute for the module file.
// All attributes declared with a path are treated as _mutually exclusive_.
// So a `mod` declaration is generated for each.
// This makes it a lot easier to manage cross-platform code.
// Note: attributes that don't have a path are copied to each module declaration.
#[cfg(windows)] = "sys/win/mod.rs"
#[cfg(not(windows))] = "sys/nix/mod.rs"
mod sys;
// Expands to:
#[cfg(windows)]
#[path = "sys/win/mod.rs"]
mod sys;
#[cfg(not(windows))]
#[path = "sys/nix/mod.rs"]
mod sys;
// You can also declare attributes on methods or types themselves, and they will be used when verifying the type.
// This module itself will be verified when not on a windows system.
#[cfg(not(windows))]
mod my_third_mod {
// This method will only be verified when on linux.
#[cfg(linux)]
fn interop() -> u8;
// Same with this type. It will only be verified when on a linux system
#[cfg(linux)]
type SomeStruct {
fn interop() -> u8;
}
}
}
fn main() {
}
```
NOTE: that `def_mod` uses syntax tricks to assert for types.
So that means when you use the path shorthand, it will still only check the module that is loaded, not all potential modules.
Eg, if I've got a module that has two possible impls, one for windows and one for unix.
If I compile on windows, `def_mod` can't check if the unix module has the correct symbols declared, because it's not the module that's compiled.
You would need to explicitly enable compilation of the modules you'd want to check, because you can declare
arbitrary #[cfg] attributes, there's no way in `def_mod` to do this.
It's entirely up to you.
---
In case you're curious as to what the macro generates:
A method assertion is transformed to something like:
```rust
const _VALUE: fn(u32) -> u8 = my_mod::method;
```
A type assertion is transformed into a use decl, inside their own scope:
```rust
{
use self::my_mod::Test;
// Any method assertions for the type will also be placed inside the same scope.
}
```
All of those are shoved into a method, generated by the macro.
For example, given something like:
```rust
def_mod! {
mod my_mod {
fn plus_one(value: u8) -> u8;
type MyStruct {
fn new() -> MyStruct;
}
}
}
```
It'll turn into something like this:
```rust
mod my_mod;
fn __load_my_mod() {
const _ASSERT_METHOD_0: fn(u8) -> u8 = my_mod::method;
{
use self::my_mod::MyStruct;
const _ASSERT_METHOD_1: fn() -> MyStruct = MyStruct::new;
}
}
```
*/
#![feature(proc_macro_diagnostic)]
extern crate proc_macro;
extern crate proc_macro2;
extern crate quote;
extern crate syn;
use proc_macro::TokenStream as TStream;
use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned, ToTokens};
use syn::*;
use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::synom::{Parser, Synom};
///
/// ASd `asd`
///
///
#[proc_macro]
pub fn def_mod(tokens: TStream) -> TStream {
let t = ModuleDecl::parse_all;
let declarations: Vec<ModuleDecl> = t.parse(tokens).unwrap();
let mut output = TokenStream::new();
for module in declarations {
let mut pathed_attrs = vec![];
let mut custom_attrs = vec![];
// Group the attributes that were declared with a path value.
for attr in module.attrs {
if let (attr, Some(path)) = attr {
pathed_attrs.push((attr, path));
} else {
custom_attrs.push(attr.0);
};
}
// Ghost the attr vectors, so no one can change them...
let pathed_attrs = &pathed_attrs;
let custom_attrs = &custom_attrs;
let vis = &module.vis;
let mod_token = &module.mod_token;
let module_name = &module.ident;
if pathed_attrs.is_empty() {
let t = quote_spanned! { module_name.span() =>
#(#custom_attrs)*
#vis #mod_token #module_name;
};
t.to_tokens(&mut output);
} else {
for (attr, path) in pathed_attrs {
let t = quote_spanned! { module_name.span() =>
#attr
#[path=#path]
#(#custom_attrs)*
#vis #mod_token #module_name;
};
t.to_tokens(&mut output);
}
}
// Generate a load function, if the module was declared with some items.
if let ModuleBody::Content((_brace, body)) = module.body {
let mut index: u32 = 0;
let items: Vec<TokenStream> = body.into_iter()
.map(|item| {
// Transform each item into the corresponding check.
match item {
DeclItem::Method(method_item) => {
let t = gen_method_assertion(index, module_name, method_item);
index += 1;
t
}
DeclItem::Type(type_item) => {
let attrs = &type_item.attrs;
let type_name = &type_item.ident;
let method_items = if let TypeDeclBody::Content((_brace, body)) = type_item.body {
body.into_iter()
.map(|method_item| {
let t = gen_method_assertion(index, type_name, method_item);
index += 1;
t
})
.collect()
} else {
vec![]
};
// We use the actual use declaration here to test for the type itself, as it'll fail if it doesn't exist or not exported.
// It also makes the codegen easier, because we don't have to qualify the full name type.
quote! {
#(#attrs)*
{
use self::#module_name::#type_name;
#(#method_items)*
}
}
}
}
})
.collect();
let function_name = format!("_load_{}", module_name);
let function_name = Ident::new(&function_name, Span::call_site());
let t = quote! {
#[allow(dead_code)]
fn #function_name() {
#(#items)*
}
};
t.to_tokens(&mut output);
}
}
output.into()
}
///
/// A module declaration: `mod my_mod`
///
/// The only difference between this and a normal mod is
/// the ability to add a path literal to attributes:
/// ```rust
/// #[cfg(target_os = "windows")] = "my_mod/win/mod.rs"
/// mod my_mod;
/// ```
///
#[derive(Debug)]
struct ModuleDecl {
attrs: Vec<(Attribute, Option<LitStr>)>,
vis: Visibility,
mod_token: Token![mod],
ident: Ident,
body: ModuleBody,
}
#[derive(Debug)]
enum ModuleBody {
Content((token::Brace, Vec<DeclItem>)),
Terminated(Token![;]),
}
impl ModuleDecl {
named!(parse_all -> Vec<ModuleDecl>, do_parse!(
decls: many0!(syn!(ModuleDecl)) >>
(decls)
));
}
impl Synom for ModuleDecl {
named!(parse -> Self, do_parse!(
attrs: many0!(do_parse!(
attr: call!(Attribute::parse_outer) >>
eq: option!(punct!(=)) >>
path: cond!(eq.is_some(), syn!(LitStr))>>
(attr, path)
)) >>
vis: syn!(Visibility) >>
mod_token: keyword!(mod) >>
ident: syn!(Ident) >>
body: alt! (
punct!(;) => { ModuleBody::Terminated }
|
braces!(many0!(DeclItem::parse)) => { ModuleBody::Content }
) >>
(ModuleDecl {
attrs,
vis,
mod_token,
ident,
body,
})
));
}
impl ToTokens for ModuleDecl {
fn to_tokens(&self, tokens: &mut TokenStream) {
self.vis.to_tokens(tokens);
}
}
#[derive(Debug)]
enum DeclItem {
Method(TraitItemMethod),
Type(TypeDecl),
}
#[derive(Debug)]
struct TypeDecl {
attrs: Vec<Attribute>,
ident: Ident,
body: TypeDeclBody,
}
#[derive(Debug)]
enum TypeDeclBody {
Content((token::Brace, Vec<TraitItemMethod>)),
Terminated(Token![;]),
}
impl DeclItem {
named!(parse -> Self, alt!(
syn!(TraitItemMethod) => { DeclItem::Method }
|
syn!(TypeDecl) => { DeclItem::Type }
));
}
impl Synom for TypeDecl {
named!(parse -> Self, do_parse!(
attrs: many0!(Attribute::parse_outer) >>
_type: keyword!(type) >>
ident: syn!(Ident) >>
body: alt!(
punct!(;) => { TypeDeclBody::Terminated }
|
braces!(many0!(TraitItemMethod::parse)) => { TypeDeclBody::Content }
) >>
(TypeDecl {
attrs,
ident,
body,
})
)
);
}
fn gen_method_assertion(index: u32, context: &Ident, method_item: TraitItemMethod) -> TokenStream {
if let Some(body) = method_item.default {
body.span()
.unstable()
.error("A body isn't valid here.")
.emit();
return TokenStream::new();
}
let attrs = &method_item.attrs;
let load_name = format!("_ASSERT_METHOD_{}", index);
let load_ident = Ident::new(&load_name, Span::call_site());
let (ty, path) = convert(context, method_item.sig);
quote! {
#(#attrs)*
const #load_ident: #ty = #path;
}
}
fn convert(context: &Ident, sig: MethodSig) -> (TypeBareFn, ExprPath) {
// @TODO Jezza - 19 Dec. 2018: Generic path attributes?
// println!("Context: {}", context);
// println!("Sig: {:?}", sig);
// pub struct MethodSig {
// pub constness: Option<Token![const]>,
// pub unsafety: Option<Token![unsafe]>,
// pub abi: Option<Abi>,
// pub ident: Ident,
// pub decl: FnDecl,
// }
// pub struct FnDecl {
// pub fn_token: Token![fn],
// pub generics: Generics,
// pub paren_token: token::Paren,
// pub inputs: Punctuated<FnArg, Token![,]>,
// pub variadic: Option<Token![...]>,
// pub output: ReturnType,
// }
// pub enum FnArg {
// /// Self captured by reference in a function signature: `&self` or `&mut
// /// self`.
// ///
// /// *This type is available if Syn is built with the `"full"` feature.*
// pub SelfRef(ArgSelfRef {
// pub and_token: Token![&],
// pub lifetime: Option<Lifetime>,
// pub mutability: Option<Token![mut]>,
// pub self_token: Token![self],
// }),
//
// /// Self captured by value in a function signature: `self` or `mut
// /// self`.
// ///
// /// *This type is available if Syn is built with the `"full"` feature.*
// pub SelfValue(ArgSelf {
// pub mutability: Option<Token![mut]>,
// pub self_token: Token![self],
// }),
//
// /// An explicitly typed pattern captured by a function signature.
// ///
// /// *This type is available if Syn is built with the `"full"` feature.*
// pub Captured(ArgCaptured {
// pub pat: Pat,
// pub colon_token: Token![:],
// pub ty: Type,
// }),
//
// /// A pattern whose type is inferred captured by a function signature.
// pub Inferred(Pat),
// /// A type not bound to any pattern in a function signature.
// pub Ignored(Type),
// }
// pub struct Generics {
// pub lt_token: Option<Token![<]>,
// pub params: Punctuated<GenericParam, Token![,]>,
// pub gt_token: Option<Token![>]>,
// pub where_clause: Option<WhereClause>,
// }
let MethodSig {
constness,
unsafety,
abi,
ident,
decl,
} = sig;
let FnDecl {
fn_token,
generics,
paren_token,
inputs,
variadic,
output,
} = decl;
let inputs = {
let mut values = Punctuated::new();
for arg in inputs {
let bare_fn_arg = match arg {
FnArg::SelfRef(_v) => {
continue;
}
FnArg::SelfValue(_v) => {
continue;
}
FnArg::Captured(ArgCaptured {
pat,
colon_token,
ty,
}) => {
BareFnArg {
name: None,
ty,
}
}
FnArg::Inferred(_v) => {
continue;
}
FnArg::Ignored(_v) => {
continue;
}
};
values.push(bare_fn_arg);
}
values
};
let type_bare_fn = TypeBareFn {
unsafety,
abi,
fn_token,
lifetimes: None,
paren_token,
inputs,
variadic,
output,
};
let mut segments = Punctuated::new();
segments.push(PathSegment {
ident: (*context).clone(),
arguments: PathArguments::None,
});
segments.push(PathSegment {
ident: ident.clone(),
arguments: PathArguments::None,
});
let path = Path {
leading_colon: None,
segments,
};
let path = ExprPath {
attrs: Vec::new(),
qself: None,
path,
};
// TypeBareFn {
// =pub unsafety: Option<Token![unsafe]>,
// =pub abi: Option<Abi>,
// =pub fn_token: Token![fn],
// pub lifetimes: Option<BoundLifetimes>,
// =pub paren_token: token::Paren,
// pub inputs: Punctuated<BareFnArg, Token![,]>,
// =pub variadic: Option<Token![...]>,
// =pub output: ReturnType,
// }
// pub struct BareFnArg {
// pub name: Option<(BareFnArgName, Token![:])>,
// pub ty: Type,
// }
// pub enum BareFnArgName {
// /// Argument given a name.
// Named(Ident),
// /// Argument not given a name, matched with `_`.
// Wild(Token![_]),
// }
// ExprPath {
// pub attrs: Vec<Attribute>,
// pub qself: Option<QSelf>,
// pub path: Path,
// }
// pub struct Path {
// pub leading_colon: Option<Token![::]>,
// pub segments: Punctuated<PathSegment, Token![::]>,
// }
// pub struct PathSegment {
// pub ident: Ident,
// pub arguments: PathArguments,
// }
(type_bare_fn, path)
}