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
//! Aldrin code generation macros
//!
//! This crate provides a single macro as an alternative frontend to the Aldrin code generator. It
//! removes the need to generate code from a schema beforehand or as part of a `build.rs`.
//!
//! See the documentation of the [`generate!`] macro for more information and usage examples.
#![allow(clippy::needless_doctest_main)]
#![deny(missing_docs)]
#![deny(rustdoc::broken_intra_doc_links)]
extern crate proc_macro;
use aldrin_codegen::{Generator, Options, RustOptions};
use aldrin_parser::{Diagnostic, Parsed, Parser};
use proc_macro::TokenStream;
use proc_macro2::Span;
use proc_macro_error::{
abort_call_site, emit_call_site_error, emit_call_site_warning, proc_macro_error,
};
use std::env;
use std::fmt::Write;
use std::path::PathBuf;
use syn::parse::{Parse, ParseStream};
use syn::{parse_macro_input, Error, Ident, LitBool, LitStr, Result, Token};
/// Generates code from an Aldrin schema.
///
/// # Basic usage
///
/// The [`generate!`] macro takes one required argument, the path to the schema file. Paths can be
/// relative to `Cargo.toml` file. This requires building with Cargo (or more specifically, the
/// `CARGO_MANIFEST_DIR` environment variable). Building without Cargo currently supports only
/// absolute paths.
///
/// The generated code depends only the `aldrin` crate. Make sure you have it specified as a
/// dependency in your `Cargo.toml`.
///
/// ```
/// # use aldrin_macros::generate;
/// generate!("schemas/example1.aldrin");
///
/// fn main() {
/// example1::MyStruct::builder()
/// .field1(12)
/// .field2(34)
/// .build();
/// }
/// ```
///
/// This generates the module `example1` with the same content as if the stand-alone code generator
/// was used.
///
/// The module has `pub` visibility, which is not always desired, especially in library crates. A
/// common pattern is to put the generated modules inside an additional `schemas` module:
///
/// ```
/// mod schemas {
/// # use aldrin_macros::generate;
/// generate!("schemas/example1.aldrin");
/// }
/// ```
///
/// If you have only a single schema, it is occasionally convenient to put the generated code inside
/// another module (like above), but then also re-export everything into it:
///
/// ```
/// mod schema {
/// # use aldrin_macros::generate;
/// generate!("schemas/example1.aldrin");
/// pub use example1::*;
/// }
///
/// fn main() {
/// schema::MyStruct::builder() // Note `schema` instead of `example1`.
/// .field1(12)
/// .field2(34)
/// .build();
/// }
/// ```
///
/// # Multiple schemas
///
/// It is possible to pass additional paths to the macro. Code will then be generated for all of
/// them:
///
/// ```
/// # use aldrin_macros::generate;
/// generate! {
/// "schemas/example1.aldrin",
/// "schemas/example2.aldrin",
/// }
/// # fn main() {}
/// ```
///
/// Any additional options (see below) will be applied to all schemas. If this is not desired, then
/// the macro can be called multiple times instead.
///
/// # Include directories
///
/// You can specify include directories with `include = "path"`:
///
/// ```
/// # use aldrin_macros::generate;
/// generate! {
/// "schemas/example3.aldrin",
/// "schemas/example4.aldrin",
/// include = "schemas",
/// }
///
/// fn main() {
/// example3::Foo::builder()
/// .bar(example4::Bar::builder().baz(12).build())
/// .build();
/// }
/// ```
///
/// The `include` option can be repeated multiple times.
///
/// # Skipping server or client code
///
/// You can skip generating server or client code for services by setting `server = false` or
/// `client = false`. This will only affect services and types defined inside (inline structs and
/// enums), but not other top-level definitions.
///
/// Both settings default to `true`.
///
/// # Patching the generated code
///
/// You can specify additional patch files, which will be applied to the generated code. This allows
/// for arbitrary changes, such as for example custom additional derives.
///
/// Patches can only be specified when generating code for a single schema.
///
/// ```
/// # use aldrin_macros::generate;
/// generate! {
/// "schemas/example1.aldrin",
/// patch = "schemas/example1-rename.patch",
/// }
///
/// fn main() {
/// example1::MyStructRenamed::builder()
/// .field1(12)
/// .field2(34)
/// .build();
/// }
/// ```
///
/// Patches are applied in the order they are specified.
///
/// ```
/// # use aldrin_macros::generate;
/// generate! {
/// "schemas/example1.aldrin",
/// patch = "schemas/example1-rename.patch",
/// patch = "schemas/example1-rename-again.patch",
/// }
///
/// fn main() {
/// example1::MyStructRenamedAgain::builder()
/// .field1(12)
/// .field2(34)
/// .build();
/// }
/// ```
///
/// # Omitting struct builders
///
/// For every struct in the schema, usually a corresponding builder is generated as well. This can
/// be turned off by setting `struct_builders = false`.
///
/// ```
/// # use aldrin_macros::generate;
/// generate! {
/// "schemas/example1.aldrin",
/// struct_builders = false,
/// }
///
/// fn main() {
/// // example1::MyStruct::builder() and example1::MyStructBuilder are not generated
///
/// let my_struct = example1::MyStruct {
/// field1: Some(42),
/// field2: None,
/// };
/// }
/// ```
///
/// # Omitting `#[non_exhaustive]` attribute
///
/// The `#[non_exhaustive]` attribute can optionally be skipped on structs, enums, service event
/// enums and service function enums. Set one or more of:
///
/// - `struct_non_exhaustive = false`
/// - `enum_non_exhaustive = false`
/// - `event_non_exhaustive = false`
/// - `function_non_exhaustive = false`
///
/// ```
/// # use aldrin_macros::generate;
/// generate! {
/// "schemas/example1.aldrin",
/// struct_non_exhaustive = false,
/// enum_non_exhaustive = false,
/// event_non_exhaustive = false,
/// function_non_exhaustive = false,
/// }
/// ```
///
/// # Enabling introspection
///
/// To enable introspection support, pass `introspection = true` to the macro. This additionally
/// requires enabling the `introspection` Cargo feature of the `aldrin` crate.
///
/// ```
/// # use aldrin_macros::generate;
/// generate! {
/// "schemas/example1.aldrin",
/// introspection = true,
/// }
/// ```
///
/// It is also possible to conditionally enable introspection based on some Cargo feature by setting
/// `introspection_if`. This implies setting `introspection = true`. The following example will have
/// introspection code generated, but guards of the form `#[cfg(feature = "introspection")]` added.
///
/// ```
/// # use aldrin_macros::generate;
/// generate! {
/// "schemas/example1.aldrin",
/// introspection_if = "introspection",
/// }
/// ```
///
/// # Errors and warnings
///
/// Any errors and warnings from the schemas will be shown as part of the regular compiler
/// output. No code will be generated, if there are any errors in the schemas.
///
/// Warnings can currently only be emitted on nightly Rust. They are silently ignored on stable and
/// beta. Unfortunately, this may suppress important diagnostics about your schemas. You can use the
/// option `warnings_as_errors = true` to treat all warnings as errors.
///
/// On the other hand, if you are on nightly Rust and generate code for a foreign schema, which you
/// have no direct influence on, warnings may clutter your compiler output. In that case you can use
/// `suppress_warnings = true` to ignore all warnings.
///
/// In general, it is advisable to use `warnings_as_errors` for your own schemas, and
/// `suppress_warnings` for foreign schemas:
///
/// ```
/// // Own schema
/// # use aldrin_macros::generate;
/// generate! {
/// "schemas/example5.aldrin",
/// include = "schemas/foreign",
/// warnings_as_errors = true,
/// }
///
/// // Foreign schema
/// generate! {
/// "schemas/foreign/example6.aldrin",
/// suppress_warnings = true,
/// }
/// # fn main() {}
/// ```
#[proc_macro_error]
#[proc_macro]
pub fn generate(input: TokenStream) -> TokenStream {
let args = parse_macro_input!(input as Args);
let mut parser = Parser::new();
for include in args.includes {
parser.add_schema_path(include);
}
let mut modules = String::new();
let mut abort = false;
for schema in args.schemas {
let parsed = parser.parse(&schema);
for error in parsed.errors() {
let msg = format_diagnostic(error, &parsed);
emit_call_site_error!(msg);
}
if !args.suppress_warnings || args.warnings_as_errors {
for warning in parsed.warnings() {
let msg = format_diagnostic(warning, &parsed);
if args.warnings_as_errors {
emit_call_site_error!(msg);
} else {
emit_call_site_warning!(msg);
}
}
}
if !parsed.errors().is_empty() {
abort |= true;
continue;
}
let gen = Generator::new(&args.options, &parsed);
let mut rust_options = RustOptions::new();
for patch in &args.patches {
rust_options.patches.push(patch);
}
rust_options.struct_builders = args.struct_builders;
rust_options.struct_non_exhaustive = args.struct_non_exhaustive;
rust_options.enum_non_exhaustive = args.enum_non_exhaustive;
rust_options.event_non_exhaustive = args.event_non_exhaustive;
rust_options.function_non_exhaustive = args.function_non_exhaustive;
rust_options.introspection_if = args.introspection_if.as_deref();
let output = match gen.generate_rust(&rust_options) {
Ok(output) => output,
Err(e) => {
emit_call_site_error!("{}", e);
abort_call_site!("there were Aldrin schema errors");
}
};
write!(
&mut modules,
"pub mod {} {{ {} const _: &[u8] = include_bytes!(\"{}\"); ",
output.module_name,
output.module_content,
schema.display()
)
.unwrap();
for patch in &args.patches {
write!(
&mut modules,
"const _: &[u8] = include_bytes!(\"{}\"); ",
patch.display()
)
.unwrap();
}
write!(&mut modules, "}}").unwrap();
}
if abort {
abort_call_site!("there were Aldrin schema errors");
}
modules.parse().unwrap()
}
struct Args {
schemas: Vec<PathBuf>,
includes: Vec<PathBuf>,
options: Options,
warnings_as_errors: bool,
suppress_warnings: bool,
patches: Vec<PathBuf>,
struct_builders: bool,
struct_non_exhaustive: bool,
enum_non_exhaustive: bool,
event_non_exhaustive: bool,
function_non_exhaustive: bool,
introspection_if: Option<String>,
}
impl Parse for Args {
fn parse(input: ParseStream) -> Result<Self> {
let first_schema = lit_str_to_path(input.parse::<LitStr>()?);
let mut args = Args {
schemas: vec![first_schema],
includes: Vec::new(),
options: Options::default(),
warnings_as_errors: false,
suppress_warnings: false,
patches: Vec::new(),
struct_builders: true,
struct_non_exhaustive: true,
enum_non_exhaustive: true,
event_non_exhaustive: true,
function_non_exhaustive: true,
introspection_if: None,
};
// Additional schemas
while !input.is_empty() {
input.parse::<Token![,]>()?;
let lit_str = match input.parse::<LitStr>() {
Ok(lit_str) => lit_str,
Err(_) => break,
};
args.schemas.push(lit_str_to_path(lit_str));
}
// Options
while !input.is_empty() {
let opt: Ident = input.parse()?;
input.parse::<Token![=]>()?;
if opt == "include" {
let lit_str = input.parse::<LitStr>()?;
args.includes.push(lit_str_to_path(lit_str));
} else if opt == "client" {
args.options.client = input.parse::<LitBool>()?.value;
} else if opt == "server" {
args.options.server = input.parse::<LitBool>()?.value;
} else if opt == "warnings_as_errors" {
args.warnings_as_errors = input.parse::<LitBool>()?.value;
} else if opt == "suppress_warnings" {
args.suppress_warnings = input.parse::<LitBool>()?.value;
} else if opt == "patch" {
let lit_str = input.parse::<LitStr>()?;
args.patches.push(lit_str_to_path(lit_str));
} else if opt == "struct_builders" {
args.struct_builders = input.parse::<LitBool>()?.value;
} else if opt == "struct_non_exhaustive" {
args.struct_non_exhaustive = input.parse::<LitBool>()?.value;
} else if opt == "enum_non_exhaustive" {
args.enum_non_exhaustive = input.parse::<LitBool>()?.value;
} else if opt == "event_non_exhaustive" {
args.event_non_exhaustive = input.parse::<LitBool>()?.value;
} else if opt == "function_non_exhaustive" {
args.function_non_exhaustive = input.parse::<LitBool>()?.value;
} else if opt == "introspection" {
args.options.introspection = input.parse::<LitBool>()?.value;
} else if opt == "introspection_if" {
let lit_str = input.parse::<LitStr>()?;
args.introspection_if = Some(lit_str.value());
args.options.introspection = true;
} else {
return Err(Error::new_spanned(opt, "invalid option"));
}
if input.is_empty() {
break;
}
input.parse::<Token![,]>()?;
}
if (args.schemas.len() > 1) && !args.patches.is_empty() {
return Err(Error::new(
Span::call_site(),
"patches cannot be applied to multiple schemas",
));
}
Ok(args)
}
}
fn format_diagnostic<D>(d: &D, parsed: &Parsed) -> String
where
D: Diagnostic,
{
let formatted = d.format(parsed);
let mut msg = format!("{}\n", formatted.summary());
for line in formatted.lines().skip(1) {
msg.push_str(&line.to_string());
}
msg
}
fn lit_str_to_path(lit_str: LitStr) -> PathBuf {
let path = PathBuf::from(lit_str.value());
if path.is_absolute() {
path
} else {
let mut absolute = PathBuf::from(
env::var("CARGO_MANIFEST_DIR")
.expect("relative paths require CARGO_MANIFEST_DIR environment variable"),
);
absolute.push(path);
absolute
}
}