use pretty_assertions::assert_eq;
use proc_macro2::TokenStream;
use quote::quote;
use syn::{
Path, braced,
parse::{Parse, ParseStream},
};
use crate::{
Result, define, expand_definition,
instance::{Output, expand_parts},
schema::{BodySpec, macro_doc, parse_body},
template::{AUTHOR_SIGIL, Template, embed, to_snake_case},
};
struct Schema {
generator: Path,
body: BodySpec,
}
impl Parse for Schema {
fn parse(input: ParseStream) -> Result<Self> {
let generator = input.parse()?;
let content;
braced!(content in input);
let body = parse_body(&content)?;
Ok(Self { generator, body })
}
}
const LED_SCHEMA: &str = "__led_generate {
/// GPIO pin.
pin: ident,
/// Number of LEDs.
len: expr,
/// PIO resource.
pio: ident = PIO0,
/// Color curve.
gamma: expr = Gamma::Srgb,
}";
fn run(schema: &str, macro_name: &str, input: TokenStream) -> Result<TokenStream> {
let Schema { generator, body } = syn::parse_str(schema)?;
expand_parts(
macro_name,
&Output::Generator(quote!(#generator)),
&body,
input,
)
}
fn pretty(tokens: TokenStream) -> Result<String> {
Ok(prettyplease::unparse(&syn::parse2(tokens)?))
}
fn error_message(result: Result<TokenStream>) -> Option<String> {
result.err().map(|error| {
error
.into_iter()
.map(|error| error.to_string())
.collect::<Vec<_>>()
.join("\n")
})
}
#[test]
fn expand_fills_defaults_in_schema_order() -> Result<()> {
let input = quote! {
#[derive(Debug)]
pub(crate) Status { len: 1 + 2, pin: PIN_3 }
};
let doc = "Generated by `led!`.\n\n\
| Field | Value |\n| ----- | ----- |\n\
| `pin` | `PIN_3` |\n\
| `len` | `1 + 2` |\n\
| `pio` | `PIO0` (default) |\n\
| `gamma` | `Gamma::Srgb` (default) |\n";
let expected = quote! {
__led_generate! {
attrs: [#[derive(Debug)]],
vis: [pub(crate)],
name: Status,
doc: #doc,
pin: PIN_3,
len: 1 + 2,
pio: PIO0,
gamma: Gamma::Srgb,
}
};
assert_eq!(pretty(expected)?, pretty(run(LED_SCHEMA, "led", input)?)?);
Ok(())
}
#[test]
fn expand_reports_unknown_field() {
let input = quote! { Status { pin: PIN_3, length: 8 } };
assert_eq!(
error_message(run(LED_SCHEMA, "led", input)).as_deref(),
Some("unknown field `length`; expected one of `pin`, `len`, `pio`, `gamma`")
);
}
#[test]
fn expand_reports_duplicate_and_missing_together() {
let input = quote! { Status { pin: PIN_3, pin: PIN_4 } };
assert_eq!(
error_message(run(LED_SCHEMA, "led", input)).as_deref(),
Some("duplicate field `pin`\nmissing required field `len`")
);
}
#[test]
fn expand_parses_value_by_kind() {
let input = quote! { Status { pin: 3, len: 8 } };
assert_eq!(
error_message(run(LED_SCHEMA, "led", input)).as_deref(),
Some("field `pin` expects an identifier")
);
}
#[test]
fn define_emits_wrapper_and_bare_name_alias() -> Result<()> {
let input = quote! {
#[cfg(not(feature = "host"))]
pub led => __led_generate { pin: ident }
};
let doc = "\n\n# Syntax\n\n```text\n\
led! {\n [<attributes>] [<visibility>] <Name> {\n\
\x20 pin: <name>,\n\
\x20 }\n}\n```\n\n\
A *name* is an identifier, such as `GPIO8`; a *value* is any expression, \
such as `250` or a constant; a *type* is a type, such as `u8`.\n\n\
**Fields:**\n\n\
| Field | Kind | Default | Description |\n\
| ----- | ---- | ------- | ----------- |\n\
| `pin` | name | required | |\n";
let expected = quote! {
#[cfg(not(feature = "host"))]
#[doc = #doc]
#[doc(hidden)]
#[macro_export]
macro_rules! __macro_schema_wrapper_led {
($($input:tt)*) => {
$crate::__macro_schema_expand! {
macro_name: "led",
generator: { $crate::__led_generate },
schema: { pin: ident },
input: { $($input)* },
}
};
}
#[doc = ""]
#[doc = "**Syntax and fields:** [below](#syntax)."]
#[cfg(not(feature = "host"))]
#[doc(inline)]
pub use __macro_schema_wrapper_led as led;
};
assert_eq!(expected.to_string(), define(input)?.to_string());
Ok(())
}
#[test]
fn define_rejects_absolute_generator_path() {
let input = quote! { pub led => ::demo::__led_generate { pin: ident } };
assert_eq!(
error_message(define(input)).as_deref(),
Some("the generator path is relative to this crate's root; drop the leading `::`")
);
}
#[test]
fn expand_parses_wrapper_input() -> Result<()> {
let input = quote! {
macro_name: "led",
generator: { crate::__led_generate },
schema: { pin: ident },
input: { Status { pin: PIN_3 } },
};
let doc = "Generated by `led!`.\n\n| Field | Value |\n| ----- | ----- |\n| `pin` | `PIN_3` |\n";
let expected = quote! {
crate::__led_generate! {
attrs: [],
vis: [pub(self)],
name: Status,
doc: #doc,
pin: PIN_3,
}
};
assert_eq!(pretty(expected)?, pretty(crate::expand(input)?)?);
Ok(())
}
const STRIPS_SCHEMA: &str = "__strips_generate {
/// Shared bus.
bus: ident = BUS0,
/// One strip per member.
members 1..=2 {
/// Data pin.
pin: ident,
/// Channel.
dma: ident = by_index[DMA0, DMA1],
/// Optional panel geometry.
panel?: {
/// Width in pixels.
width: expr,
/// Font.
font: expr = Font::Small,
},
},
}";
#[test]
fn expand_members_with_index_defaults_and_optional_block() -> Result<()> {
let input = quote! {
pub Strips {
First { pin: P0 },
Second { panel: { width: 12 }, pin: P1 },
}
};
let group_doc = "Generated by `strips!`.\n\n\
| Field | Value |\n| ----- | ----- |\n\
| `bus` | `BUS0` (default) |\n\
\nMembers: `First`, `Second`.\n";
let first_doc = "Member `First` of `Strips`, generated by `strips!`.\n\n\
| Field | Value |\n| ----- | ----- |\n\
| `pin` | `P0` |\n\
| `dma` | `DMA0` (default) |\n\
| `panel` | `(not set)` |\n";
let second_doc = "Member `Second` of `Strips`, generated by `strips!`.\n\n\
| Field | Value |\n| ----- | ----- |\n\
| `pin` | `P1` |\n\
| `dma` | `DMA1` (default) |\n\
| `panel` | `{ width: 12, font: Font::Small }` |\n";
let expected = quote! {
__strips_generate! {
attrs: [],
vis: [pub],
name: Strips,
doc: #group_doc,
bus: BUS0,
member_count: 2,
members: [
{
index: 0,
attrs: [],
vis: [pub],
name: First,
doc: #first_doc,
pin: P0,
dma: DMA0,
panel: [],
},
{
index: 1,
attrs: [],
vis: [pub],
name: Second,
doc: #second_doc,
pin: P1,
dma: DMA1,
panel: [{ width: 12, font: Font::Small, }],
},
],
}
};
assert_eq!(
pretty(expected)?,
pretty(run(STRIPS_SCHEMA, "strips", input)?)?
);
Ok(())
}
#[test]
fn expand_reports_member_errors_together() {
let input = quote! {
Strips {
A { pin: P0, panel: { font: F } },
A { pin: P1 },
C { pin: P2 },
}
};
assert_eq!(
error_message(run(STRIPS_SCHEMA, "strips", input)).as_deref(),
Some(
"`strips!` takes 1 to 2 members; found 3\n\
duplicate member `A`\n\
missing required field `width`\n\
field `dma` has no default for member index 2; give it explicitly"
)
);
}
#[test]
fn expand_rejects_members_where_schema_has_none() {
let input = quote! { Status { pin: PIN_3, len: 1, Extra { pin: PIN_4 } } };
assert_eq!(
error_message(run(LED_SCHEMA, "led", input)).as_deref(),
Some("`Status` takes fields only; expected one of `pin`, `len`, `pio`, `gamma`")
);
}
#[test]
fn schema_rejects_by_index_outside_members() {
let input = quote! { pub bad => gen { dma: ident = by_index[A, B] } };
assert_eq!(
error_message(define(input)).as_deref(),
Some("`by_index` defaults are allowed only in member fields")
);
}
#[test]
fn schema_rejects_optional_with_default() {
let input = quote! { pub bad => gen { pin?: ident = A } };
assert_eq!(
error_message(define(input)).as_deref(),
Some("an optional (`?`) field cannot also have a default")
);
}
#[test]
fn define_documents_members_and_blocks() -> Result<()> {
let schema: Schema = syn::parse_str(STRIPS_SCHEMA)?;
let doc = macro_doc(&syn::parse_quote!(strips), &schema.body)?;
let expected = "\n\n# Syntax\n\n```text\n\
strips! {\n [<attributes>] [<visibility>] <Name> {\n\
\x20 bus: <name>, // optional, default: BUS0\n\
\x20 [<attributes>] <MemberName> { // 1 to 2 members; visibility comes from the group\n\
\x20 pin: <name>,\n\
\x20 dma: <name>, // optional, default: by member index: DMA0, DMA1\n\
\x20 panel: { // optional\n\
\x20 width: <value>,\n\
\x20 font: <value>, // optional, default: Font::Small\n\
\x20 },\n\
\x20 },\n\
\x20 }\n}\n```\n\n\
A *name* is an identifier, such as `GPIO8`; a *value* is any expression, \
such as `250` or a constant; a *type* is a type, such as `u8`.\n\n\
**Fields:**\n\n\
| Field | Kind | Default | Description |\n\
| ----- | ---- | ------- | ----------- |\n\
| `bus` | name | `BUS0` | Shared bus. |\n\
\n**Member fields** (1 to 2 members):\n\n\
One strip per member.\n\n\
| Field | Kind | Default | Description |\n\
| ----- | ---- | ------- | ----------- |\n\
| `pin` | name | required | Data pin. |\n\
| `dma` | name | by member index: `DMA0`, `DMA1` | Channel. |\n\
| `panel` | block | optional | Optional panel geometry. |\n\
| `panel.width` | value | required | Width in pixels. |\n\
| `panel.font` | value | `Font::Small` | Font. |\n";
assert_eq!(expected, doc);
Ok(())
}
#[test]
fn default_display_overrides_docs_but_not_generated_tokens() -> Result<()> {
let schema_source = "__gen {
/// Color curve.
#[default_display = \"Gamma::Srgb\"]
gamma: expr = ::demo::led_strip::Gamma::Srgb,
}";
let schema: Schema = syn::parse_str(schema_source)?;
let doc = macro_doc(&syn::parse_quote!(led), &schema.body)?;
assert!(doc.contains("gamma: <value>, // optional, default: Gamma::Srgb\n"));
assert!(doc.contains("| `gamma` | value | `Gamma::Srgb` | Color curve. |\n"));
let prose_source = "__gen {
/// Engine.
#[default_display = \"RMT where the chip has it\"]
engine: ty = Rmt,
/// Reset interval.
#[default_display = \"`60` (SPI only)\"]
reset_us: expr = 60,
}";
let prose: Schema = syn::parse_str(prose_source)?;
let prose_doc = macro_doc(&syn::parse_quote!(led), &prose.body)?;
assert!(
prose_doc.contains("engine: <type>, // optional, default: RMT where the chip has it\n")
);
assert!(prose_doc.contains("reset_us: <value>, // optional, default: 60 (SPI only)\n"));
assert!(prose_doc.contains("| `engine` | type | RMT where the chip has it | Engine. |\n"));
assert!(prose_doc.contains("| `reset_us` | value | `60` (SPI only) | Reset interval. |\n"));
let rendered = run(prose_source, "led", quote! { Strip {} })?.to_string();
assert!(rendered.contains("| `engine` | RMT where the chip has it (default) |"));
assert!(rendered.contains("| `reset_us` | `60` (SPI only) (default) |"));
let instance_doc = "Generated by `led!`.\n\n\
| Field | Value |\n| ----- | ----- |\n\
| `gamma` | `Gamma::Srgb` (default) |\n";
let expected = quote! {
__gen! {
attrs: [],
vis: [pub(self)],
name: Strip,
doc: #instance_doc,
gamma: ::demo::led_strip::Gamma::Srgb,
}
};
assert_eq!(
pretty(expected)?,
pretty(run(schema_source, "led", quote! { Strip {} })?)?
);
Ok(())
}
#[test]
fn schema_rejects_default_display_without_default() {
let input = quote! { pub bad => gen { #[default_display = "X"] pin: ident } };
assert_eq!(
error_message(define(input)).as_deref(),
Some("`default_display` needs a single default value (`= ...`)")
);
}
#[test]
fn expand_explains_colon_after_declaration_name() {
let input = quote! { Strips { First: { pin: P0 } } };
assert_eq!(
error_message(run(STRIPS_SCHEMA, "strips", input)).as_deref(),
Some("remove the `:` after `First`; declarations are written `First { ... }`")
);
}
#[test]
fn expand_rejects_member_visibility() {
let input = quote! { pub Strips { pub(crate) First { pin: P0 } } };
assert_eq!(
error_message(run(STRIPS_SCHEMA, "strips", input)).as_deref(),
Some("members take their group's visibility; remove this visibility")
);
}
#[test]
fn members_may_have_no_upper_limit() -> Result<()> {
let schema = "__lcds_generate { members 1.. { address: expr } }";
let input = quote! { Lcds { A { address: 1 }, B { address: 2 }, C { address: 3 } } };
let output = run(schema, "lcds", input)?.to_string();
assert!(output.contains("member_count : 3"), "{output}");
assert_eq!(
error_message(run(schema, "lcds", quote! { Lcds {} })).as_deref(),
Some("`lcds!` takes at least 1 member; found 0")
);
Ok(())
}
fn strips_body() -> Result<BodySpec> {
Ok(syn::parse_str::<Schema>(STRIPS_SCHEMA)?.body)
}
fn render(template: TokenStream, input: TokenStream) -> Result<TokenStream> {
let body = strips_body()?;
Template::parse(template.clone(), &body, AUTHOR_SIGIL)?;
expand_parts("strips", &Output::Template(embed(template)), &body, input)
}
fn template_error(template: TokenStream) -> Option<String> {
let body = strips_body().ok()?;
Template::parse(template, &body, AUTHOR_SIGIL)
.err()
.map(|error| error.to_string())
}
#[test]
fn const_arg_braces_only_what_needs_braces() -> Result<()> {
let template = quote! {
$for strip in $decl.members {
$if let Some(panel) = $strip.panel {
impl Grid<$const_arg($panel.width), $const_arg($upper($strip.name, _H))> for $strip.name {}
}
}
};
let input = quote! {
Strips {
Literal { pin: P0, panel: { width: 12 } },
Named { pin: P1, panel: { width: WIDTH } },
}
};
let expected = quote! {
impl Grid<12, LITERAL_H> for Literal {}
impl Grid<WIDTH, NAMED_H> for Named {}
};
assert_eq!(
expected.to_string(),
render(template.clone(), input)?.to_string()
);
let input = quote! {
Strips {
Computed { pin: P0, panel: { width: 4 * 3 } },
}
};
let expected = quote! {
impl Grid<{ (4 * 3) }, COMPUTED_H> for Computed {}
};
assert_eq!(expected.to_string(), render(template, input)?.to_string());
Ok(())
}
#[test]
fn template_renders_loops_optionals_and_identifiers() -> Result<()> {
let template = quote! {
$decl.vis struct $decl.name;
static $upper($decl.bus, _BUS): u8 = 0;
$for strip in $decl.members {
$if let Some(panel) = $strip.panel {
$decl.vis struct $ident($strip.name, Panel)([u8; $panel.width]);
} else {
$decl.vis struct $strip.name;
}
fn $snake($strip.name, _pin)() -> usize { $strip.index }
const _: $crate::Dma = $crate::Dma::$strip.dma;
}
};
let input = quote! {
pub Strips {
First { pin: P0 },
Second { pin: P1, panel: { width: 12 } },
}
};
let expected = quote! {
pub struct Strips;
static BUS0_BUS: u8 = 0;
pub struct First;
fn first_pin() -> usize { 0 }
const _: crate::Dma = crate::Dma::DMA0;
pub struct SecondPanel([u8; 12]);
fn second_pin() -> usize { 1 }
const _: crate::Dma = crate::Dma::DMA1;
};
let rendered = render(template, input)?
.to_string()
.replace("$ crate", "crate");
assert_eq!(expected.to_string(), rendered);
Ok(())
}
#[test]
fn template_errors_are_reported_at_define_time() {
let cases = [
(
quote! { $for strip in $decl.members { $strip.pnael } },
"no value `pnael` here; expected one of `name`, `vis`, `doc`, `attrs`, `index`, `pin`, `dma`, `panel`",
),
(
quote! { $decl.buss },
"no value `buss` here; expected one of `name`, `vis`, `doc`, `attrs`, `members`, `bus`",
),
(
quote! { $bus },
"unknown template value `$bus`; write `$decl.bus`",
),
(
quote! { $name },
"unknown template value `$name`; write `$decl.name`",
),
(
quote! { $for strip in $decl.members { $strp.pin } },
"unknown template value `$strp`; expected `$decl`, `$strip`",
),
(
quote! { $for strip in $decl.members { $strip.panel } },
"`$strip.panel` is optional; read it with `$if let Some(x) = ... { ... }`",
),
(
quote! { $if let Some(x) = $decl.bus {} },
"`$decl.bus` is not optional; `$if let` needs an optional field",
),
(
quote! { $for strip in $decl.bus {} },
"`$decl.bus` is not the member list; loop over `$decl.members`",
),
(
quote! { $decl.members },
"`$decl.members` is the member list; loop over it with `$for member in $decl.members { ... }`",
),
(
quote! { $decl },
"`$decl` is the declaration, not a value; name one of `name`, `vis`, `doc`, `attrs`, `members`, `bus`",
),
(
quote! { $for strip in $decl.members { $strip.members } },
"no value `members` here; expected one of `name`, `vis`, `doc`, `attrs`, `index`, `pin`, `dma`, `panel`",
),
(
quote! { $decl.index },
"no value `index` here; expected one of `name`, `vis`, `doc`, `attrs`, `members`, `bus`",
),
(
quote! { $for strip in $decl.members { $ident($strip.dma, $strip.pin) $ident($decl.doc) } },
"`$decl.doc` is not an identifier; identifier parts must be `ident` fields, `$decl.name`, `$member.name`, or `$member.index`",
),
(
quote! { $( x )* },
"`$` must start a template construct (`$value`, `$for`, `$if`, `$ident(...)`, `$const_arg(...)`) or `$crate`",
),
(
quote! { $for decl in $decl.members {} },
"`decl` is reserved in templates; choose another variable name",
),
(
quote! { $for strip in $decl.members { $for strip in $decl.members {} } },
"`$strip` is already in scope; choose another variable name",
),
];
for (template, expected) in cases {
assert_eq!(template_error(template).as_deref(), Some(expected));
}
}
#[test]
fn field_names_may_not_shadow_their_namespace_builtins() {
for (schema, expected) in [
(
"__gen { name: ident }",
"field `name` collides with the template's built-in `$decl.name`; rename the field",
),
(
"__gen { members 1.. { index: expr } }",
"field `index` collides with the template's built-in `$member.index`; rename the field",
),
] {
let body = syn::parse_str::<Schema>(schema)
.expect("schema parses")
.body;
let error = Template::parse(TokenStream::new(), &body, AUTHOR_SIGIL)
.err()
.map(|error| error.to_string());
assert_eq!(error.as_deref(), Some(expected));
}
for schema in [
"__gen { index: expr }",
"__gen { members 1.. { members: expr } }",
] {
let body = syn::parse_str::<Schema>(schema)
.expect("schema parses")
.body;
assert!(Template::parse(TokenStream::new(), &body, AUTHOR_SIGIL).is_ok());
}
}
#[test]
fn define_template_form_embeds_template_with_hash_sigils() -> Result<()> {
let input = quote! {
pub led { pin: ident } generate { struct $decl.name; const _: $crate::Pin = $crate::Pin::$decl.pin; }
};
let output = define(input)?.to_string();
assert!(
output.contains(
"template : { struct # decl . name ; const _ : $ crate :: Pin = $ crate :: Pin :: # decl . pin ; }"
),
"{output}"
);
Ok(())
}
#[test]
fn define_rejects_generate_with_generator_path() {
let input = quote! { pub led => __gen { pin: ident } generate { } };
assert_eq!(
error_message(define(input)).as_deref(),
Some("a `generate { ... }` template replaces `=> generator`; use one or the other")
);
}
#[test]
fn snake_case_splits_words_digits_and_acronyms() {
for (input, expected) in [
("Gpio0LedStrip_pin", "gpio0_led_strip_pin"),
("PIO0_BUS", "pio0_bus"),
("HTTPServer", "http_server"),
("Font4x6Trim", "font4x6_trim"),
("__Inner", "__inner"),
("LED2D_OR_LED_STRIPS", "led2d_or_led_strips"),
("Ir15Receiver", "ir15_receiver"),
] {
assert_eq!(to_snake_case(input), expected);
}
}
#[test]
fn written_doc_replaces_generated_instance_doc() -> Result<()> {
let template = quote! {
$decl.attrs #[doc = $decl.doc] $decl.vis struct $decl.name;
$for strip in $decl.members { $strip.attrs #[doc = $strip.doc] struct $strip.name; }
};
let input = quote! {
#[doc(hidden)]
pub Strips {
#[doc = "Outer macro's doc."]
First { pin: P0 },
}
};
let expected = quote! {
#[doc = r" Hand-written."] #[doc(hidden)] #[doc = ""] pub struct Strips;
#[doc = "Outer macro's doc."] #[doc = ""] struct First;
};
assert_eq!(expected.to_string(), render(template, input)?.to_string());
Ok(())
}
#[test]
fn compound_expressions_render_parenthesized() -> Result<()> {
let body = syn::parse_str::<Schema>("__gen { x: expr }")?.body;
let template = embed(quote! { $decl.x });
for (value, expected) in [
(quote!(1 + 2), quote!((1 + 2))),
(quote!(-4), quote!((-4))),
(quote!(x as u8), quote!((x as u8))),
(quote!(0..4), quote!((0..4))),
(quote!(|v| v + 1), quote!((|v| v + 1))),
(quote!(7), quote!(7)),
(quote!("label"), quote!("label")),
(quote!(crate::LIMIT), quote!(crate::LIMIT)),
(
quote!(Current::Milliamps(250)),
quote!(Current::Milliamps(250)),
),
(quote!(layout.width()), quote!(layout.width())),
(quote!(table[3].field), quote!(table[3].field)),
(quote!((1 + 2)), quote!((1 + 2))),
(quote!({ 1 + 2 }), quote!({ 1 + 2 })),
(quote!([0; 4]), quote!([0; 4])),
(quote!(concat!("a", "b")), quote!(concat!("a", "b"))),
(quote!((1 + 2).pow(2)), quote!((1 + 2).pow(2))),
(quote!(-x.abs()), quote!((-x.abs()))),
] {
let rendered = expand_parts(
"m",
&Output::Template(template.clone()),
&body,
quote!(A { x: #value }),
)?;
assert_eq!(rendered.to_string(), expected.to_string(), "for `{value}`");
}
Ok(())
}
#[test]
fn expand_definition_renders_a_template_with_dollar_crate_as_crate() -> Result<()> {
let definition = quote! {
pub led {
pin: ident,
len: expr = 8,
}
generate {
$decl.vis struct $decl.name;
impl $decl.name {
const PIN: $crate::Pin = $crate::Pin::$decl.pin;
const LEN: usize = $decl.len;
}
}
};
let expected = quote! {
pub(self) struct Status;
impl Status {
const PIN: crate::Pin = crate::Pin::PIN_3;
const LEN: usize = 8;
}
};
let call = quote! { Status { pin: PIN_3 } };
assert_eq!(
pretty(expected)?,
pretty(expand_definition(definition, call)?)?
);
Ok(())
}
#[test]
fn expand_definition_calls_a_generator_at_its_crate_path() -> Result<()> {
let definition = quote! { pub led => __led_generate { pin: ident } };
let doc = "Generated by `led!`.\n\n| Field | Value |\n| ----- | ----- |\n| `pin` | `PIN_3` |\n";
let expected = quote! {
crate::__led_generate! {
attrs: [],
vis: [pub(self)],
name: Status,
doc: #doc,
pin: PIN_3,
}
};
let call = quote! { Status { pin: PIN_3 } };
assert_eq!(
pretty(expected)?,
pretty(expand_definition(definition, call)?)?
);
Ok(())
}
#[test]
fn expand_definition_reports_call_errors() {
let definition = quote! { pub led { pin: ident } generate { struct $decl.name; } };
let call = quote! { Status { pin: PIN_3, length: 8 } };
assert_eq!(
error_message(expand_definition(definition, call)).as_deref(),
Some("unknown field `length`; expected one of `pin`")
);
}
fn alias_docs(input: TokenStream) -> Result<Vec<String>> {
let file: syn::File = syn::parse2(define(input)?)?;
let alias = file
.items
.into_iter()
.find_map(|item| match item {
syn::Item::Use(item_use) => Some(item_use),
_ => None,
})
.ok_or_else(|| syn::Error::new(proc_macro2::Span::call_site(), "no alias"))?;
Ok(alias
.attrs
.iter()
.map(|attr| match &attr.meta {
syn::Meta::NameValue(name_value) if name_value.path.is_ident("doc") => {
match &name_value.value {
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(text),
..
}) => text.value(),
other => quote!(#other).to_string(),
}
}
_ => "#[..]".to_owned(),
})
.collect())
}
#[test]
fn syntax_link_follows_the_summary_paragraph() -> Result<()> {
let docs = alias_docs(quote! {
pub led => __led_generate { pin: ident }
})?;
assert_eq!(
docs,
[
" An LED strip.",
"",
"**Syntax and fields:** [below](#syntax).",
"",
" More detail.",
"#[..]",
]
);
Ok(())
}
#[test]
fn syntax_link_comes_before_an_included_doc() -> Result<()> {
let docs = alias_docs(quote! {
#[doc = "An audio clip."]
#[doc = include_str!("clip.md")]
pub clip => __clip_generate { file: expr }
})?;
assert_eq!(
docs,
[
"An audio clip.",
"",
"**Syntax and fields:** [below](#syntax).",
"",
"include_str ! (\"clip.md\")",
"#[..]",
]
);
Ok(())
}
#[test]
fn hidden_macros_get_no_syntax_link() -> Result<()> {
let docs = alias_docs(quote! {
#[doc(hidden)]
pub __helper => __helper_generate { pin: ident }
})?;
assert_eq!(docs, [" Internal.", "#[..]", "#[..]"]);
Ok(())
}