knuffel-derive-3.2.0/.cargo_vcs_info.json0000644000000001440000000000100137430ustar { "git": { "sha1": "c44c6b0c0f31ea6d1174d5d2ed41064922ea44ca" }, "path_in_vcs": "derive" }knuffel-derive-3.2.0/Cargo.toml0000644000000022250000000000100117430ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "knuffel-derive" version = "3.2.0" description = """ A derive implementation for knuffel KDL parser """ homepage = "https://github.com/tailhook/knuffel" documentation = "https://docs.rs/knuffel" readme = "README.md" keywords = [ "kdl", "configuration", ] license = "MIT/Apache-2.0" [lib] proc_macro = true [dependencies.heck] version = "0.4.1" features = ["unicode"] [dependencies.proc-macro-error] version = "1.0.4" [dependencies.proc-macro2] version = "1.0.32" [dependencies.quote] version = "1.0.10" [dependencies.syn] version = "1.0.81" features = [ "full", "extra-traits", ] [dev-dependencies.miette] version = "5.1.1" features = ["fancy"] knuffel-derive-3.2.0/Cargo.toml.orig000064400000000000000000000011611046102023000154220ustar 00000000000000[package] name = "knuffel-derive" version = "3.2.0" edition = "2021" description = """ A derive implementation for knuffel KDL parser """ license = "MIT/Apache-2.0" keywords = ["kdl", "configuration"] homepage = "https://github.com/tailhook/knuffel" documentation = "https://docs.rs/knuffel" readme = "README.md" [lib] proc_macro = true [dependencies] heck = {version="0.4.1", features=["unicode"]} syn = {version="1.0.81", features=["full", "extra-traits"]} quote = "1.0.10" proc-macro2 = "1.0.32" proc-macro-error = "1.0.4" [dev-dependencies] knuffel = { path=".." } miette = { version="5.1.1", features=["fancy"] } knuffel-derive-3.2.0/README.md000064400000000000000000000013251046102023000140140ustar 00000000000000This is derive implementation to make working with [KDL](https://kdl.dev) file format convenient that works with [knuffel] parser library. See more in the documentation of [knuffel] library itself. [knuffel]: https://docs.rs/knuffel License ======= Licensed under either of * Apache License, Version 2.0, (./LICENSE-APACHE or ) * MIT license (./LICENSE-MIT or ) at your option. Contribution ------------ Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. knuffel-derive-3.2.0/derive_decode.md000064400000000000000000000501351046102023000156430ustar 00000000000000The derive is the most interesting part of the `knuffel` libary. # Overview This trait and derive is used to decode a single node of the KDL document. There are few things that derive can be implemented for: 1. Structure with named or unnamed fields. Most of the text here is about this case. 2. A single-field [new type] wrapper around such structure `Wrapper(Inner)` where `Inner` implements `Decode` (this is a tuple struct with single argument without annotations). 3. Unit struct 4. [Enum](#enums), where each variant corresponds to a specific node name [new type]: https://doc.rust-lang.org/rust-by-example/generics/new_types.html There are three kinds of things can fit structure fields that must be annotated appropriately: [arguments](#arguments), [properties](#properties) and [children](#children). Unlike in `serde` and similar projects, non-annotated fields are not decoded from source and are filled with [`std::default::Default`]. All annotations are enclosed by `#[knuffel(..)]` attribute. Both arguments and properties can decode [scalars](#scalars). If structure only has `child` and `children` fields (see [below](#children)) it can be used as a root document (the output of [`knuffel::parse`]). Or root of the document can be `Vec where T: Decode`. [`knuffel::parse`]: fn.parse.html Note: node name is usually not used in the structure decoding node, it's matched either in parent or in an [enum](#enums). # Arguments Arguments are scalar values that are usually written on the same line with the node name and are positional, i.e. they parsed and put into structure fields in order. The two Rust attributes to parse arguments are: * `argument` -- to parse single argument * `arguments` -- to parse sequence of arguments Note: order of the structure fields matter. Fields marked as `arguments` can be used only once and cannot be followed by `argument`. For example, the following node: ```kdl node "arg1" true 1 22 333 ``` ... can be parsed into the following structure: ```rust #[derive(knuffel::Decode)] struct MyNode { #[knuffel(argument)] first: String, #[knuffel(argument)] second: bool, #[knuffel(arguments)] numbers: Vec, } ``` Arguments can be optional: ```rust #[derive(knuffel::Decode)] struct MyNode { #[knuffel(argument)] first: Option, #[knuffel(argument)] second: Option, } ``` In this case attribute may not exists: ```kdl node "arg1" // no `second` argument is okay ``` Or may be `null`: ```kdl node null null ``` Note: due to limitations of the procedural macros in Rust, optional arguments must use `Option` in this specific notation. Other variations like these: ``` use std::option::Option as Opt; #[derive(knuffel::Decode)] struct MyNode { #[knuffel(argument)] first: ::std::option::Option, #[knuffel(argument)] second: Opt, } ``` Do not work (they will always require `null` arguments). The field marked as `arguments` can have any type that implements `FromIterator where T: DecodeScalar`. See [Scalars](#scalars) and [Common Attributes](#common-attributes) for more information on decoding of values. # Properties Properties are scalar values that are usually written on the same line prepended with name and equals `=` sign. They are parsed regardless of order, although if the same argument is specified twice the latter value overrides former. The two Rust attributes to parse properties are: * `property` -- to parse single argument * `properties` -- to parse sequence of arguments Note: order of the structure fields matter. Fields marked as `properties` can be used only once and cannot be followed by `property`. For example, the following node: ```kdl node name="arg1" enabled=true a=1 b=2 c=3 ``` Can be parsed into the following structure: ```rust # use std::collections::HashMap; #[derive(knuffel::Decode)] struct MyNode { #[knuffel(property)] name: String, #[knuffel(property)] enabled: bool, #[knuffel(properties)] numbers: HashMap, } ``` Properties can be optional: ```rust #[derive(knuffel::Decode)] struct MyNode { #[knuffel(property)] name: Option, #[knuffel(property)] enabled: Option, } ``` In this case property may not exists or may be set to `null`: ```kdl node name=null ``` Note: due to limitations of the procedural macros in Rust, optional properties must use `Option` in this specific notation. Other variations like this: ```rust use std::option::Option as Opt; #[derive(knuffel::Decode)] struct MyNode { #[knuffel(property)] name: ::std::option::Option, #[knuffel(property)] enabled: Opt, } ``` Do not work (they will always require `property=null`). By default, field name is renamed to use `kebab-case` in KDL file. So field defined like this: ```rust #[derive(knuffel::Decode)] struct MyNode { #[knuffel(property)] plugin_name: String, } ``` Parses the following: ```kdl node plugin-name="my_plugin" ``` To rename a property in the source use `name=`: ```rust #[derive(knuffel::Decode)] struct MyNode { #[knuffel(property(name="pluginName"))] name: String, } ``` The field marked as `properties` can have any type that implements `FromIterator<(K, V)> where K: FromStr, V: DecodeScalar`. See [Scalars](#scalars) and [Common Attributes](#common-attributes) for more information on decoding of values. # Scalars There are additional attributes that define how scalar values are parsed: * `str` -- uses [`FromStr`](std::str::FromStr) trait. * `bytes` -- decodes binary strings, either by decoding `base64` if the `(base64)` type is specified in the source or by encoding string into `utf-8` if no type is specified. This is required since * `default` -- described in [Common Attrbites](#common-attributes) section since it applies to nodes (non-scalar values) too. All of them work on [properties](#properties) and [arguments](#arguments). ## Parsing Strings The `str` marker is very useful for types coming from other libraries that aren't supported by `knuffel` directly. For example: ```rust #[derive(knuffel::Decode)] struct Server { #[knuffel(property, str)] listen: std::net::SocketAddr, } ``` This will parse listening addresses that Rust stdlib supports, like this: ```kdl server listen="127.0.0.1:8080" ``` ## Parsing Bytes Since in Rust sequence of ints and buffer of bytes cannot be distinguished on the type level, there is a `bytes` marker that can be applied to parse scalar as byte buffer. For example: ```rust #[derive(knuffel::Decode)] struct Response { #[knuffel(argument, bytes)] body: Vec, } ``` The value of `body` can be specified in two ways. Using `base64` string (this requires `base64` feature enabled which is default): ```kdl response (base64)"SGVsbG8gd29ybGQh" ``` While using base64 allows encoding any binary data, strings may also be used and end up using utf-8 encoded in buffer. So the KDL above is equivalent to the following: ```kdl response "Hello world!" ``` The field don't have to be `Vec`, it may be any type that has `TryInto>` (and hence also `Into>`) implementation. For example [`bstr::BString`](https://docs.rs/bstr/latest/bstr/struct.BString.html) and [`bytes::Bytes`](https://docs.rs/bytes/latest/bytes/struct.Bytes.html) work too. # Children Nodes are fundamental blocks for data hierarchy in KDL. Here are some examples of nodes: ```kdl node1 "x" "y" (my_type)node2 prop="value" { node3 1 node4 2 } ``` There are four nodes in this example. Nodes typically start with identifier which is called node name. Similarly to scalars, nodes can be prepended by type name in parenthesis. The nodes `node3` and `node4` are children nodes with respect to `node2`. So when `node2` is decoded its `child` and `children` directives are interpreted to match `node3` and `node4`. The two Rust attributes to parse children are: * `child` -- to parse single child * `children` -- to parse sequence of children For example the follwing KDL: ```kdl node { version 1 plugin "xxx" datum "yyy" } ``` ... can be parsed by into the following structures: ```rust #[derive(knuffel::Decode)] enum Setting { Plugin(#[knuffel(argument)] String), Datum(#[knuffel(argument)] String), } #[derive(knuffel::Decode)] struct Version { #[knuffel(argument)] number: u32 } #[derive(knuffel::Decode)] struct MyNode { #[knuffel(child)] version: Version, #[knuffel(children)] settings: Vec } ``` There is another form of children which is `children(name="something")`, that allows filtering nodes by name: ```rust #[derive(knuffel::Decode)] struct NamedNode { #[knuffel(argument)] name: u32 } #[derive(knuffel::Decode)] struct MyNode { #[knuffel(children(name="plugin"))] plugins: Vec, #[knuffel(children(name="datum"))] data: Vec, } ``` Note: we use same node type for `plugin` and `datum` nodes. Generally nodes do not match on the actual node names, it's the job of the parent node to sort out their children into the right buckets. Also see [Enums](#enums). ## Boolean Child Fields Sometimes you want to track just the presence of the child in the node. For example this document: ```kdl plugin "first" { auto-start } plugin "second" ``` ... can be parsed into the list of the following structures: ```rust #[derive(knuffel::Decode)] struct Plugin { #[knuffel(child)] auto_start: bool, } ``` And in this case `auto-start` node may be omitted without an error even though it's not wrapped into an `Option`. No arguments, properties and children are allowed in the boolean nodes. Note: due to limitations of the procedural macros in Rust, boolean children must use `bool` in this specific notation. If you shadow `bool` type by some import the results are undefined (knuffel will still think it's bool node, but it may not work). ## Unwrapping The `unwrap` attribute for `child` allows adding extra children in the KDL document that aren't represented in the final structure, but they play important role in making document readable. It works by transforming the following: ```rust,ignore #[derive(knuffel::Decode)] struct Node { #[knuffel(child, unwrap(/* attributes */))] field: String, } ``` ... into something like this: ``` #[derive(knuffel::Decode)] struct TmpChild { #[knuffel(/* attributes */)] field: String, } #[derive(knuffel::Decode)] struct Node { #[knuffel(child)] field: TmpChild, } ``` ... and then unpacks `TmpChild` to put target type into the field. Most of the attributes can be used in place of `/* attributes */`. Including: 1. `argument` (the most common, see [below](#properties-become-children)) and `arguments` 2. `property` (usually in the form of `property(name="other_name")` to avoid repetitive KDL) and `properties` 3. `child` and `children` (see example [below](#grouping-things)) Following are some nice examples of using `unwrap`. ### Properties Become Children In nodes with many properties it might be convenient to put them into children instead. So instead of this: ```kdl plugin name="my-plugin" url="https://example.com" {} ``` ... users can write this: ```kdl plugin { name "my-plugin" url "https://example.com" } ``` Here is the respective Rust structure: ```rust #[derive(knuffel::Decode)] struct Plugin { #[knuffel(child, unwrap(argument))] name: String, #[knuffel(child, unwrap(argument))] url: String, } ``` You can read this like: `name` field parses a child that contains a single argument of type `String`. ### Grouping Things Sometimes instead of different kinds of nodes scattered around you may want to group them. So instead of this: ```kdl plugin "a" file "aa" plugin "b" file "bb" ``` You nave a KDL document like this: ```kdl plugins { plugin "a" plugin "b" } files { file "aa" file "bb" } ``` This can be parsed into the following structure: ```rust # #[derive(knuffel::Decode)] struct Plugin {} # #[derive(knuffel::Decode)] struct File {} #[derive(knuffel::Decode)] struct Document { #[knuffel(child, unwrap(children(name="plugin")))] plugins: Vec, #[knuffel(child, unwrap(children(name="file")))] files: Vec, } ``` You can read this like: `plugins` field parses a child that contains a set of children named `plugin`. ## Root Document Any structure that has only fields marked as `child` and `children` or unmarked ones, can be used as the root of the document. For example, this structure can: ```rust # #[derive(knuffel::Decode)] # struct NamedNode { #[knuffel(argument)] name: u32 } #[derive(knuffel::Decode)] struct MyNode { #[knuffel(child, unwrap(argument))] version: u32, #[knuffel(children(name="plugin"))] plugins: Vec, #[knuffel(children(name="datum"))] data: Vec, } ``` On the other hand this one can **not** because it contains a `property`: ```rust # #[derive(knuffel::Decode)] # struct NamedNode { #[knuffel(argument)] name: u32 } #[derive(knuffel::Decode)] struct MyNode { #[knuffel(property)] version: u32, #[knuffel(children(name="plugin"))] plugins: Vec, #[knuffel(children(name="datum"))] data: Vec, } ``` Note: attributes in the `unwrap` have no influence on whether structure can be used to decode document. Technically [DecodeChildren](traits/trait.DecodeChildren.html) trait will be implemented for the structures that can be used as documents. # Common Attributes ## Default `default` attribute may be applied to any [arguments](#arguments), [properties](#properties) or [children](#children). There are two forms of it. Marker attribute: ```rust #[derive(knuffel::Decode)] struct MyNode { #[knuffel(property, default)] first: String, } ``` Which means that `std::default::Default` should be used if field was not filled otherwise (i.e. no such property encountered). Another form is `default=value`: ```rust #[derive(knuffel::Decode)] struct MyNode { #[knuffel(property, default="unnamed".into())] name: String, } ``` Any Rust expression can be used in this case. Note, for optional properties `Some` should be included in the default value. And for scalar values their value can be overriden by using `null`. The definition like this: ```rust #[derive(knuffel::Decode)] struct MyNode { #[knuffel(property, default=Some("unnamed".into()))] name: Option, } ``` Parses these two nodes differently: ```kdl node name=null node ``` Will yield: ```rust # struct MyNode { name: Option } let _ = vec![ MyNode { name: None }, MyNode { name: Some(String::from("unnamed")) }, ]; ``` # Flatten Similarly to `flatten` flag in `serde`, this allows factoring out some properties or children into another structure. For example: ```rust #[derive(knuffel::Decode, Default)] struct Common { #[knuffel(child, unwrap(argument))] name: Option, #[knuffel(child, unwrap(argument))] description: Option } #[derive(knuffel::Decode)] struct Plugin { #[knuffel(flatten(child))] common: Common, #[knuffel(child, unwrap(argument))] url: String, } ``` This will parse the following: ```kdl plugin { name "my-plugin" description "Some example plugin" url "https://example.org/plugin" } ``` There are few limitations of the `flatten`: 1. All fields in target structure must be optional. 2. The target structure must implement [`Default`](std::default::Default) 3. Only children an properties can be factored out, not arguments in current implementation 4. You must specify which directives can be used in the target structure (i.e. `flatten(child, children, property, properties)`) and if `children` or `properties` are forwarded to the target structure, no more children and property attributes can be used in this structure following the `flatten` attribute. We may lift some of these limitations later. Technically [DecodePartial](traits/trait.DecodePartial.html) trait will be implemented for the strucutures that can be used with the `flatten` attribute. # Special Values ## Type Name Here is the example of the node with the type name (the name in parens): ```kdl (text)document name="New Document" { } ``` By default knuffel doesn't allow type names for nodes as these are quite rare. To allow type names on specific node and to have the name stored use `type_name` attribute: ```rust #[derive(knuffel::Decode)] struct Node { #[knuffel(type_name)] type_name: String, } ``` Type name can be optional. The field that is a target of `type_name` can be any type that implements `FromStr`. This might be used to validate node type: ```rust pub enum PluginType { Builtin, External, } impl std::str::FromStr for PluginType { type Err = Box; fn from_str(s: &str) -> Result { match s { "builtin" => Ok(PluginType::Builtin), "external" => Ok(PluginType::External), _ => Err("Plugin type name must be `builtin` or `external`")?, } } } #[derive(knuffel::Decode)] struct Node { #[knuffel(type_name)] type_name: PluginType, } ``` ## Node Name In knuffel, it's common that parent node, document or enum type checks the node name of the node, and node name is not stored or validated in the strucuture. But for the cases where you need it, it's possible to store too: ```rust #[derive(knuffel::Decode)] struct Node { #[knuffel(node_name)] node_name: String, } ``` You can use any type that implements `FromStr` to validate node name. Similarly to the example in the [type names](#type-name) section. Node name always exists so optional node_name is not supported. ## Spans The following definition: ```rust use knuffel::span::Span; // or LineSpan #[derive(knuffel::Decode)] #[knuffel(span_type=Span)] struct Node { #[knuffel(span)] span: Span, // This can be user type decoded from Span } ``` Puts position of the node in the source code into the `span` field. Span contains the whole node, starting from parenthesis that enclose type name if present otherwise node name. Includes node children if exists and semicolon or newline that ends the node (so includes any whitespace and coments before the newline if node ends by a newline, but doesn't include anything after semicolon). The span value might be different than one used for parsing. In this case, it should implement [`DecodeSpan`](traits/trait.DecodeSpan.html) trait. Independenly of whether you use custom span type, or built-in one, you have to specify `span_type` for the decoder, since there is no generic implementation of the `DecodeSpan` for any type. See [Span Type](#span-type) for more info # Enums Enums are used to differentiate nodes by name when multiple kinds of nodes are pushed to a single collection. For example, to parse the following list of actions: ```kdl create "xxx" print-string "yyy" line=2 finish ``` The following enum might be used: ```rust # #[derive(knuffel::Decode)] struct PrintString {} #[derive(knuffel::Decode)] enum Action { Create(#[knuffel(argument)] String), PrintString(PrintString), Finish, #[knuffel(skip)] InternalAction, } ``` The following variants supported: 1. Single element tuple struct without arguments (`PrintString` in example), which forwards node parsing to the inner element. 2. Normal `argument`, `arguments`, `properties`, `children` fields (`Create` example) 3. Property fields with names `property(name="xxx")` 4. Unit structs, in this case no arguments, properties and children are expected in such node 5. Variant with `skip`, cannot be deserialized and can be in any form Enum variant names are matches against node names converted into `kebab-case`. # Container Attributes ## Span Type Usually generated implemenation is for any span type: ```rust,ignore impl Decode for MyStruct { # ... } ``` But if you want to use `span` argument, it's unlikely to be possible to implement `DecodeSpan` for any type. Use use `span_type=` for implemenation of specific type: ```rust use knuffel::span::Span; // or LineSpan #[derive(knuffel::Decode)] #[knuffel(span_type=Span)] struct MyStruct { #[knuffel(span)] span: Span, } ``` This will generate implementation like this: ```rust,ignore impl Decode for MyStruct { # ... } ``` See [Spans](#spans) section for more info about decoding spans. knuffel-derive-3.2.0/derive_decode_scalar.md000064400000000000000000000011341046102023000171630ustar 00000000000000Currently `DecodeScalar` derive is only implemented for enums # Enums Only enums that contain no data are supported: ```rust #[derive(knuffel::DecodeScalar)] enum Color { Red, Blue, Green, InfraRed, } ``` This will match scalar values in `kebab-case`. For example, this node decoder: ``` # #[derive(knuffel::DecodeScalar)] # enum Color { Red, Blue, Green, InfraRed } #[derive(knuffel::Decode)] struct Document { #[knuffel(child, unwrap(arguments))] all_colors: Vec, } ``` Can be populated from the following text: ```kdl all-colors "red" "blue" "green" "infra-red" ``` knuffel-derive-3.2.0/src/definition.rs000064400000000000000000000770531046102023000160350ustar 00000000000000use std::fmt; use std::mem; use proc_macro2::{TokenStream, Span}; use proc_macro_error::emit_error; use quote::quote; use syn::ext::IdentExt; use syn::parse::{Parse, ParseStream}; use syn::punctuated::Punctuated; use syn::spanned::Spanned; use crate::kw; pub enum Definition { UnitStruct(Struct), TupleStruct(Struct), NewType(NewType), Struct(Struct), Enum(Enum), } pub enum VariantKind { Unit, Nested { option: bool }, Tuple(Struct), Named(Struct), } pub enum ArgKind { Value { option: bool }, } #[derive(Debug, Clone)] pub enum FieldMode { Argument, Property { name: Option }, Arguments, Properties, Children { name: Option }, Child, Flatten(Flatten), Span, NodeName, TypeName, } pub enum FlattenItem { Child, Property, } #[derive(Debug, Clone)] pub struct Flatten { child: bool, property: bool, } #[derive(Debug, Clone)] pub enum DecodeMode { Normal, Str, Bytes, } #[derive(Debug)] pub enum Attr { Skip, DecodeMode(DecodeMode), FieldMode(FieldMode), Unwrap(FieldAttrs), Default(Option), SpanType(syn::Type), } #[derive(Debug, Clone)] pub struct FieldAttrs { pub mode: Option, pub decode: Option<(DecodeMode, Span)>, pub unwrap: Option>, pub default: Option>, } #[derive(Debug, Clone)] pub struct VariantAttrs { pub skip: bool, } #[derive(Clone)] pub enum AttrAccess { Indexed(usize), Named(syn::Ident), } #[derive(Clone)] pub struct Field { pub span: Span, pub attr: AttrAccess, pub tmp_name: syn::Ident, } pub struct SpanField { pub field: Field, } pub struct NodeNameField { pub field: Field, } pub struct TypeNameField { pub field: Field, pub option: bool, } pub struct Arg { pub field: Field, pub kind: ArgKind, pub decode: DecodeMode, pub default: Option>, pub option: bool, } pub struct VarArgs { pub field: Field, pub decode: DecodeMode, } pub struct Prop { pub field: Field, pub name: String, pub option: bool, pub decode: DecodeMode, pub flatten: bool, pub default: Option>, } pub struct VarProps { pub field: Field, pub decode: DecodeMode, } pub enum ChildMode { Normal, Flatten, Multi, Bool, } pub struct Child { pub field: Field, pub name: String, pub option: bool, pub mode: ChildMode, pub unwrap: Option>, pub default: Option>, } pub struct VarChildren { pub field: Field, pub unwrap: Option>, } pub enum ExtraKind { Auto, } pub struct ExtraField { pub field: Field, pub kind: ExtraKind, pub option: bool, } #[derive(Clone)] pub struct TraitProps { pub span_type: Option, } pub struct Struct { pub ident: syn::Ident, pub trait_props: TraitProps, pub generics: syn::Generics, pub spans: Vec, pub node_names: Vec, pub type_names: Vec, pub arguments: Vec, pub var_args: Option, pub properties: Vec, pub var_props: Option, pub has_arguments: bool, pub has_properties: bool, pub children: Vec, pub var_children: Option, pub extra_fields: Vec, } pub struct StructBuilder { pub ident: syn::Ident, pub trait_props: TraitProps, pub generics: syn::Generics, pub spans: Vec, pub node_names: Vec, pub type_names: Vec, pub arguments: Vec, pub var_args: Option, pub properties: Vec, pub var_props: Option, pub children: Vec, pub var_children: Option, pub extra_fields: Vec, } pub struct NewType { pub ident: syn::Ident, pub trait_props: TraitProps, pub generics: syn::Generics, pub option: bool, } pub struct Variant { pub ident: syn::Ident, pub name: String, pub kind: VariantKind, } pub struct Enum { pub ident: syn::Ident, pub trait_props: TraitProps, pub generics: syn::Generics, pub variants: Vec, } impl TraitProps { fn pick_from(attrs: &mut Vec<(Attr, Span)>) -> TraitProps { let mut props = TraitProps { span_type: None, }; for attr in mem::replace(attrs, Vec::new()) { match attr.0 { Attr::SpanType(ty) => { props.span_type = Some(ty); } _ => attrs.push(attr), } } return props; } } fn err_pair(s1: &Field, s2: &Field, t1: &str, t2: &str) -> syn::Error { let mut err = syn::Error::new(s1.span, t1); err.combine(syn::Error::new(s2.span, t2)); return err; } fn is_option(ty: &syn::Type) -> bool { matches!(ty, syn::Type::Path(syn::TypePath { qself: None, path: syn::Path { leading_colon: None, segments, }, }) if segments.len() == 1 && segments[0].ident == "Option" ) } fn is_bool(ty: &syn::Type) -> bool { matches!(ty, syn::Type::Path(syn::TypePath { qself: None, path }) if path.is_ident("bool") ) } impl Variant { fn new(ident: syn::Ident, _attrs: VariantAttrs, kind: VariantKind) -> syn::Result { let name = heck::ToKebabCase::to_kebab_case(&ident.unraw().to_string()[..]); Ok(Variant { ident, name, kind, }) } } impl Enum { fn new(ident: syn::Ident, attrs: Vec, generics: syn::Generics, src_variants: impl Iterator) -> syn::Result { let mut attrs = parse_attr_list(&attrs); let trait_props = TraitProps::pick_from(&mut attrs); if !attrs.is_empty() { for (_, span) in attrs { emit_error!(span, "unexpected container attribute"); } } let mut variants = Vec::new(); for var in src_variants { let mut attrs = VariantAttrs::new(); attrs.update(parse_attr_list(&var.attrs)); if attrs.skip { continue; } let kind = match var.fields { syn::Fields::Named(n) => { Struct::new(var.ident.clone(), trait_props.clone(), generics.clone(), n.named.into_iter()) .map(VariantKind::Named)? } syn::Fields::Unnamed(u) => { let tup = Struct::new( var.ident.clone(), trait_props.clone(), generics.clone(), u.unnamed.into_iter(), )?; if tup.all_fields().len() == 1 && tup.extra_fields.len() == 1 && matches!(tup.extra_fields[0].kind, ExtraKind::Auto) { // Single tuple variant without any defition means // the first field inside is meant to be full node // parser. VariantKind::Nested { option: tup.extra_fields[0].option, } } else { VariantKind::Tuple(tup) } } syn::Fields::Unit => { VariantKind::Unit } }; variants.push(Variant::new(var.ident, attrs, kind)?); } Ok(Enum { ident, trait_props, generics, variants, }) } } impl StructBuilder { pub fn new(ident: syn::Ident, trait_props: TraitProps, generics: syn::Generics) -> Self { StructBuilder { ident, trait_props, generics, spans: Vec::new(), node_names: Vec::new(), type_names: Vec::new(), arguments: Vec::new(), var_args: None::, properties: Vec::new(), var_props: None::, children: Vec::new(), var_children: None::, extra_fields: Vec::new(), } } pub fn build(self) -> Struct { Struct { ident: self.ident, trait_props: self.trait_props, generics: self.generics, spans: self.spans, node_names: self.node_names, type_names: self.type_names, has_arguments: !self.arguments.is_empty() || self.var_args.is_some(), has_properties: !self.properties.is_empty() || self.var_props.is_some(), arguments: self.arguments, var_args: self.var_args, properties: self.properties, var_props: self.var_props, children: self.children, var_children: self.var_children, extra_fields: self.extra_fields, } } pub fn add_field(&mut self, field: Field, is_option: bool, is_bool: bool, attrs: &FieldAttrs) -> syn::Result<&mut Self> { match &attrs.mode { Some(FieldMode::Argument) => { if let Some(prev) = &self.var_args { return Err(err_pair(&field, &prev.field, "extra `argument` after capture all `arguments`", "capture all `arguments` is defined here")); } self.arguments.push(Arg { field, kind: ArgKind::Value { option: is_option }, decode: attrs.decode.as_ref().map(|(v, _)| v.clone()) .unwrap_or(DecodeMode::Normal), default: attrs.default.clone(), option: is_option, }); } Some(FieldMode::Arguments) => { if let Some(prev) = &self.var_args { return Err(err_pair(&field, &prev.field, "only single `arguments` allowed", "previous `arguments` is defined here")); } self.var_args = Some(VarArgs { field, decode: attrs.decode.as_ref().map(|(v, _)| v.clone()) .unwrap_or(DecodeMode::Normal), }); } Some(FieldMode::Property { name }) => { if let Some(prev) = &self.var_props { return Err(err_pair(&field, &prev.field, "extra `property` after capture all `properties`", "capture all `properties` is defined here")); } let name = match (name, &field.attr) { (Some(name), _) => name.clone(), (None, AttrAccess::Named(name)) => heck::ToKebabCase::to_kebab_case(&name.unraw().to_string()[..]), (None, AttrAccess::Indexed(_)) => { return Err(syn::Error::new(field.span, "property must be named, try \ `property(name=\"something\")")); } }; self.properties.push(Prop { field, name, option: is_option, decode: attrs.decode.as_ref().map(|(v, _)| v.clone()) .unwrap_or(DecodeMode::Normal), flatten: false, default: attrs.default.clone(), }); } Some(FieldMode::Properties) => { if let Some(prev) = &self.var_props { return Err(err_pair(&field, &prev.field, "only single `properties` is allowed", "previous `properties` is defined here")); } self.var_props = Some(VarProps { field, decode: attrs.decode.as_ref().map(|(v, _)| v.clone()) .clone().unwrap_or(DecodeMode::Normal), }); } Some(FieldMode::Child) => { attrs.no_decode("children"); if let Some(prev) = &self.var_children { return Err(err_pair(&field, &prev.field, "extra `child` after capture all `children`", "capture all `children` is defined here")); } let name = match &field.attr { AttrAccess::Named(n) => { heck::ToKebabCase::to_kebab_case(&n.unraw().to_string()[..]) } AttrAccess::Indexed(_) => { return Err(syn::Error::new(field.span, "`child` is not allowed for tuple structs")); } }; self.children.push(Child { name, field, option: is_option, mode: if attrs.unwrap.is_none() && is_bool { ChildMode::Bool } else { ChildMode::Normal }, unwrap: attrs.unwrap.clone(), default: attrs.default.clone(), }); } Some(FieldMode::Children { name: Some(name) }) => { attrs.no_decode("children"); if let Some(prev) = &self.var_children { return Err(err_pair(&field, &prev.field, "extra `children(name=` after capture all `children`", "capture all `children` is defined here")); } self.children.push(Child { name: name.clone(), field, option: is_option, mode: ChildMode::Multi, unwrap: attrs.unwrap.clone(), default: attrs.default.clone(), }); } Some(FieldMode::Children { name: None }) => { attrs.no_decode("children"); if let Some(prev) = &self.var_children { return Err(err_pair(&field, &prev.field, "only single catch all `children` is allowed", "previous `children` is defined here")); } self.var_children = Some(VarChildren { field, unwrap: attrs.unwrap.clone(), }); } Some(FieldMode::Flatten(flatten)) => { if is_option { return Err(syn::Error::new(field.span, "optional flatten fields are not supported yet")); } attrs.no_decode("children"); if flatten.property { if let Some(prev) = &self.var_props { return Err(err_pair(&field, &prev.field, "extra `flatten(property)` after \ capture all `properties`", "capture all `properties` is defined here")); } self.properties.push(Prop { field: field.clone(), name: "".into(), // irrelevant option: is_option, decode: DecodeMode::Normal, flatten: true, default: None, }); } if flatten.child { if let Some(prev) = &self.var_children { return Err(err_pair(&field, &prev.field, "extra `flatten(child)` after \ capture all `children`", "capture all `children` is defined here")); } self.children.push(Child { name: "".into(), // unused field: field.clone(), option: is_option, mode: ChildMode::Flatten, unwrap: None, default: None, }); } } Some(FieldMode::Span) => { attrs.no_decode("span"); self.spans.push(SpanField { field }); } Some(FieldMode::NodeName) => { attrs.no_decode("node_name"); self.node_names.push(NodeNameField { field }); } Some(FieldMode::TypeName) => { attrs.no_decode("type_name"); self.type_names.push(TypeNameField { field, option: is_option, }); } None => { self.extra_fields.push(ExtraField { field, kind: ExtraKind::Auto, option: is_option, }); } } return Ok(self); } } impl Struct { fn new(ident: syn::Ident, trait_props: TraitProps, generics: syn::Generics, fields: impl Iterator) -> syn::Result { let mut bld = StructBuilder::new(ident, trait_props, generics); for (idx, fld) in fields.enumerate() { let mut attrs = FieldAttrs::new(); attrs.update(parse_attr_list(&fld.attrs)); let field = Field::new(&fld, idx); bld.add_field(field, is_option(&fld.ty), is_bool(&fld.ty), &attrs)?; } Ok(bld.build()) } pub fn all_fields(&self) -> Vec<&Field> { let mut res = Vec::new(); res.extend(self.spans.iter().map(|a| &a.field)); res.extend(self.node_names.iter().map(|a| &a.field)); res.extend(self.type_names.iter().map(|a| &a.field)); res.extend(self.arguments.iter().map(|a| &a.field)); res.extend(self.var_args.iter().map(|a| &a.field)); res.extend(self.properties.iter().map(|p| &p.field)); res.extend(self.var_props.iter().map(|p| &p.field)); res.extend(self.children.iter().map(|c| &c.field)); res.extend(self.var_children.iter().map(|c| &c.field)); res.extend(self.extra_fields.iter().map(|f| &f.field)); return res; } } impl Parse for Definition { fn parse(input: ParseStream) -> syn::Result { let mut attrs = input.call(syn::Attribute::parse_outer)?; let ahead = input.fork(); let _vis: syn::Visibility = ahead.parse()?; let lookahead = ahead.lookahead1(); if lookahead.peek(syn::Token![struct]) { let item: syn::ItemStruct = input.parse()?; attrs.extend(item.attrs); let mut attrs = parse_attr_list(&attrs); let trait_props = TraitProps::pick_from(&mut attrs); if !attrs.is_empty() { for (_, span) in attrs { emit_error!(span, "unexpected container attribute"); } } match item.fields { syn::Fields::Named(n) => { Struct::new(item.ident, trait_props, item.generics, n.named.into_iter()) .map(Definition::Struct) } syn::Fields::Unnamed(u) => { let tup = Struct::new( item.ident.clone(), trait_props.clone(), item.generics.clone(), u.unnamed.into_iter(), )?; if tup.all_fields().len() == 1 && tup.extra_fields.len() == 1 && matches!(tup.extra_fields[0].kind, ExtraKind::Auto) { Ok(Definition::NewType(NewType { ident: item.ident, trait_props, generics: item.generics, option: tup.extra_fields[0].option, })) } else { Ok(Definition::TupleStruct(tup)) } } syn::Fields::Unit => { Struct::new(item.ident, trait_props, item.generics, Vec::new().into_iter()) .map(Definition::UnitStruct) } } } else if lookahead.peek(syn::Token![enum]) { let item: syn::ItemEnum = input.parse()?; attrs.extend(item.attrs); Enum::new(item.ident, attrs, item.generics, item.variants.into_iter()) .map(Definition::Enum) } else { Err(lookahead.error()) } } } impl FieldAttrs { fn new() -> FieldAttrs { FieldAttrs { mode: None, decode: None, unwrap: None, default: None, } } fn update(&mut self, attrs: impl IntoIterator) { use Attr::*; for (attr, span) in attrs { match attr { FieldMode(mode) => { if self.mode.is_some() { emit_error!(span, "only single attribute that defines mode of the \ field is allowed. Perhaps you mean `unwrap`?"); } self.mode = Some(mode); } Unwrap(val) => { if self.unwrap.is_some() { emit_error!(span, "`unwrap` specified twice"); } self.unwrap = Some(Box::new(val)); } DecodeMode(mode) => { if self.decode.is_some() { emit_error!(span, "only single attribute that defines parser of the \ field is allowed"); } self.decode = Some((mode, span)); } Default(value) => { if self.default.is_some() { emit_error!(span, "only single default is allowed"); } self.default = Some(value); } _ => emit_error!(span, "this attribute is not supported on fields"), } } } fn no_decode(&self, element: &str) { if let Some((mode, span)) = self.decode.as_ref() { if self.unwrap.is_some() { emit_error!(span, "decode modes are not supported on {}", element; hint= span.clone() => "try putting decode mode \ into unwrap(.., {})", mode; ); } else { emit_error!(span, "decode modes are not supported on {}", element ); } } } } impl VariantAttrs { fn new() -> VariantAttrs { VariantAttrs { skip: false, } } fn update(&mut self, attrs: impl IntoIterator) { use Attr::*; for (attr, span) in attrs { match attr { Skip => self.skip = true, _ => emit_error!(span, "not supported on enum variants"), } } } } fn parse_attr_list(attrs: &[syn::Attribute]) -> Vec<(Attr, Span)> { let mut all = Vec::new(); for attr in attrs { if matches!(attr.style, syn::AttrStyle::Outer) && attr.path.is_ident("knuffel") { match attr.parse_args_with(parse_attrs) { Ok(attrs) => all.extend(attrs), Err(e) => emit_error!(e), } } } return all; } fn parse_attrs(input: ParseStream) -> syn::Result> { Punctuated::<_, syn::Token![,]>::parse_terminated_with( input, Attr::parse) } impl Attr { fn parse(input: ParseStream) -> syn::Result<(Self, Span)> { let span = input.span(); Self::_parse(input).map(|a| (a, span)) } fn _parse(input: ParseStream) -> syn::Result { let lookahead = input.lookahead1(); if lookahead.peek(kw::argument) { let _kw: kw::argument = input.parse()?; Ok(Attr::FieldMode(FieldMode::Argument)) } else if lookahead.peek(kw::arguments) { let _kw: kw::arguments = input.parse()?; Ok(Attr::FieldMode(FieldMode::Arguments)) } else if lookahead.peek(kw::property) { let _kw: kw::property = input.parse()?; let mut name = None; if !input.is_empty() && !input.lookahead1().peek(syn::Token![,]) { let parens; syn::parenthesized!(parens in input); let lookahead = parens.lookahead1(); if lookahead.peek(kw::name) { let _kw: kw::name = parens.parse()?; let _eq: syn::Token![=] = parens.parse()?; let name_lit: syn::LitStr = parens.parse()?; name = Some(name_lit.value()); } else { return Err(lookahead.error()) } } Ok(Attr::FieldMode(FieldMode::Property { name })) } else if lookahead.peek(kw::properties) { let _kw: kw::properties = input.parse()?; Ok(Attr::FieldMode(FieldMode::Properties)) } else if lookahead.peek(kw::children) { let _kw: kw::children = input.parse()?; let mut name = None; if !input.is_empty() && !input.lookahead1().peek(syn::Token![,]) { let parens; syn::parenthesized!(parens in input); let lookahead = parens.lookahead1(); if lookahead.peek(kw::name) { let _kw: kw::name = parens.parse()?; let _eq: syn::Token![=] = parens.parse()?; let name_lit: syn::LitStr = parens.parse()?; name = Some(name_lit.value()); } else { return Err(lookahead.error()) } } Ok(Attr::FieldMode(FieldMode::Children { name })) } else if lookahead.peek(kw::child) { let _kw: kw::child = input.parse()?; Ok(Attr::FieldMode(FieldMode::Child)) } else if lookahead.peek(kw::unwrap) { let _kw: kw::unwrap = input.parse()?; let parens; syn::parenthesized!(parens in input); let mut attrs = FieldAttrs::new(); let chunk = parens.call(parse_attrs)?; attrs.update(chunk); Ok(Attr::Unwrap(attrs)) } else if lookahead.peek(kw::skip) { let _kw: kw::skip = input.parse()?; Ok(Attr::Skip) } else if lookahead.peek(kw::str) { let _kw: kw::str = input.parse()?; Ok(Attr::DecodeMode(DecodeMode::Str)) } else if lookahead.peek(kw::bytes) { let _kw: kw::bytes = input.parse()?; Ok(Attr::DecodeMode(DecodeMode::Bytes)) } else if lookahead.peek(kw::flatten) { let _kw: kw::flatten = input.parse()?; let parens; syn::parenthesized!(parens in input); let items = Punctuated:::: parse_terminated(&parens)?; let mut flatten = Flatten { child: false, property: false, }; for item in items { match item { FlattenItem::Child => flatten.child = true, FlattenItem::Property => flatten.property = true, } } Ok(Attr::FieldMode(FieldMode::Flatten(flatten))) } else if lookahead.peek(kw::default) { let _kw: kw::default = input.parse()?; if !input.is_empty() && !input.lookahead1().peek(syn::Token![,]) { let _eq: syn::Token![=] = input.parse()?; let value: syn::Expr = input.parse()?; Ok(Attr::Default(Some(value))) } else { Ok(Attr::Default(None)) } } else if lookahead.peek(kw::span) { let _kw: kw::span = input.parse()?; Ok(Attr::FieldMode(FieldMode::Span)) } else if lookahead.peek(kw::node_name) { let _kw: kw::node_name = input.parse()?; Ok(Attr::FieldMode(FieldMode::NodeName)) } else if lookahead.peek(kw::type_name) { let _kw: kw::type_name = input.parse()?; Ok(Attr::FieldMode(FieldMode::TypeName)) } else if lookahead.peek(kw::span_type) { let _kw: kw::span_type = input.parse()?; let _eq: syn::Token![=] = input.parse()?; let ty: syn::Type = input.parse()?; Ok(Attr::SpanType(ty)) } else { Err(lookahead.error()) } } } impl Parse for FlattenItem { fn parse(input: ParseStream) -> syn::Result { let lookahead = input.lookahead1(); if lookahead.peek(kw::child) { let _kw: kw::child = input.parse()?; Ok(FlattenItem::Child) } else if lookahead.peek(kw::property) { let _kw: kw::property = input.parse()?; Ok(FlattenItem::Property) } else { Err(lookahead.error()) } } } impl Field { pub fn new_named(name: &syn::Ident) -> Field { Field { span: name.span(), attr: AttrAccess::Named(name.clone()), tmp_name: name.clone(), } } fn new(field: &syn::Field, idx: usize) -> Field { field.ident.as_ref() .map(|id| Field { span: field.span(), attr: AttrAccess::Named(id.clone()), tmp_name: id.clone(), }) .unwrap_or_else(|| Field { span: field.span(), attr: AttrAccess::Indexed(idx), tmp_name: syn::Ident::new( &format!("field{}", idx), Span::mixed_site(), ), }) } pub fn from_self(&self) -> TokenStream { match &self.attr { AttrAccess::Indexed(idx) => quote!(self.#idx), AttrAccess::Named(name) => quote!(self.#name), } } pub fn is_indexed(&self) -> bool { matches!(self.attr, AttrAccess::Indexed(_)) } pub fn as_index(&self) -> Option { match &self.attr { AttrAccess::Indexed(idx) => Some(*idx), AttrAccess::Named(_) => None, } } pub fn as_assign_pair(&self) -> Option { match &self.attr { AttrAccess::Indexed(_) => None, AttrAccess::Named(n) if n == &self.tmp_name => Some(quote!(#n)), AttrAccess::Named(n) => { let tmp_name = &self.tmp_name; Some(quote!(#n: #tmp_name)) } } } } impl fmt::Display for DecodeMode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use DecodeMode::*; match self { Normal => "normal", Str => "str", Bytes => "bytes", }.fmt(f) } } knuffel-derive-3.2.0/src/kw.rs000064400000000000000000000010131046102023000143050ustar 00000000000000syn::custom_keyword!(argument); syn::custom_keyword!(arguments); syn::custom_keyword!(bytes); syn::custom_keyword!(child); syn::custom_keyword!(children); syn::custom_keyword!(default); syn::custom_keyword!(flatten); syn::custom_keyword!(name); syn::custom_keyword!(node_name); syn::custom_keyword!(properties); syn::custom_keyword!(property); syn::custom_keyword!(skip); syn::custom_keyword!(span); syn::custom_keyword!(span_type); syn::custom_keyword!(str); syn::custom_keyword!(type_name); syn::custom_keyword!(unwrap); knuffel-derive-3.2.0/src/lib.rs000064400000000000000000000025401046102023000144400ustar 00000000000000use proc_macro2::TokenStream; mod definition; mod kw; mod node; mod scalar; mod variants; use definition::Definition; use scalar::{Scalar, emit_scalar}; fn emit_decoder(def: &Definition) -> syn::Result { match def { Definition::Struct(s) => node::emit_struct(s, true), Definition::NewType(s) => node::emit_new_type(s), Definition::TupleStruct(s) => node::emit_struct(s, false), Definition::UnitStruct(s) => node::emit_struct(s, true), Definition::Enum(e) => variants::emit_enum(e), } } #[proc_macro_error::proc_macro_error] #[proc_macro_derive(Decode, attributes(knuffel))] #[doc = include_str!("../derive_decode.md")] pub fn decode_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let item = syn::parse_macro_input!(input as Definition); match emit_decoder(&item) { Ok(stream) => stream.into(), Err(e) => e.to_compile_error().into(), } } #[proc_macro_error::proc_macro_error] #[proc_macro_derive(DecodeScalar, attributes(knuffel))] #[doc = include_str!("../derive_decode_scalar.md")] pub fn decode_scalar_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let item = syn::parse_macro_input!(input as Scalar); match emit_scalar(&item) { Ok(stream) => stream.into(), Err(e) => e.to_compile_error().into(), } } knuffel-derive-3.2.0/src/node.rs000064400000000000000000001052741046102023000146270ustar 00000000000000use proc_macro2::{TokenStream, Span}; use quote::{format_ident, quote, ToTokens}; use syn::ext::IdentExt; use crate::definition::{Struct, StructBuilder, ArgKind, FieldAttrs, DecodeMode}; use crate::definition::{Child, Field, NewType, ExtraKind, ChildMode}; pub(crate) struct Common<'a> { pub object: &'a Struct, pub ctx: &'a syn::Ident, pub span_type: &'a TokenStream, } fn child_can_partial(child: &Child) -> bool { use ChildMode::*; child.option || matches!(child.mode, Bool | Flatten) } pub fn emit_struct(s: &Struct, named: bool) -> syn::Result { let s_name = &s.ident; let node = syn::Ident::new("node", Span::mixed_site()); let ctx = syn::Ident::new("ctx", Span::mixed_site()); let children = syn::Ident::new("children", Span::mixed_site()); let (_, type_gen, _) = s.generics.split_for_impl(); let mut common_generics = s.generics.clone(); let span_ty; if let Some(ty) = s.trait_props.span_type.as_ref() { span_ty = quote!(#ty); } else { if common_generics.params.is_empty() { common_generics.lt_token = Some(Default::default()); common_generics.gt_token = Some(Default::default()); } common_generics.params.push(syn::parse2(quote!(S)).unwrap()); span_ty = quote!(S); common_generics.make_where_clause().predicates.push( syn::parse2(quote!(S: ::knuffel::traits::ErrorSpan)).unwrap()); }; let trait_gen = quote!(<#span_ty>); let (impl_gen, _, bounds) = common_generics.split_for_impl(); let common = Common { object: s, ctx: &ctx, span_type: &span_ty, }; let decode_specials = decode_specials(&common, &node)?; let decode_args = decode_args(&common, &node)?; let decode_props = decode_props(&common, &node)?; let decode_children_normal = decode_children( &common, &children, Some(quote!(#node.span())))?; let assign_extra = assign_extra(&common)?; let all_fields = s.all_fields(); let struct_val = if named { let assignments = all_fields.iter() .map(|f| f.as_assign_pair().unwrap()); quote!(#s_name { #(#assignments,)* }) } else { let mut fields = all_fields.iter() .map(|f| (f.as_index().unwrap(), &f.tmp_name)) .collect::>(); fields.sort_by_key(|(idx, _)| *idx); assert_eq!(fields.iter().map(|(idx, _)| *idx).collect::>(), (0..fields.len()).collect::>(), "all tuple structure fields should be filled in"); let assignments = fields.iter().map(|(_, v)| v); quote!{ #s_name(#(#assignments),*) } }; let mut extra_traits = Vec::new(); let partial_compatible = s.spans.is_empty() && s.node_names.is_empty() && s.type_names.is_empty() && !s.has_arguments && ( s.properties.iter().all(|x| x.option || x.flatten) && s.var_props.is_none() ) && ( s.children.iter().all(child_can_partial) && s.var_children.is_none() ); if partial_compatible { let node = syn::Ident::new("node", Span::mixed_site()); let name = syn::Ident::new("name", Span::mixed_site()); let value = syn::Ident::new("value", Span::mixed_site()); let insert_child = insert_child(&common, &node)?; let insert_property = insert_property(&common, &name, &value)?; extra_traits.push(quote! { impl #impl_gen ::knuffel::traits::DecodePartial #trait_gen for #s_name #type_gen #bounds { fn insert_child(&mut self, #node: &::knuffel::ast::SpannedNode<#span_ty>, #ctx: &mut ::knuffel::decode::Context<#span_ty>) -> Result> { #insert_child } fn insert_property(&mut self, #name: &::knuffel::span::Spanned, #span_ty>, #value: &::knuffel::ast::Value<#span_ty>, #ctx: &mut ::knuffel::decode::Context<#span_ty>) -> Result> { #insert_property } } }); } if !s.has_arguments && !s.has_properties && s.spans.is_empty() && s.node_names.is_empty() && s.type_names.is_empty() { let decode_children = decode_children(&common, &children, None)?; extra_traits.push(quote! { impl #impl_gen ::knuffel::traits::DecodeChildren #trait_gen for #s_name #type_gen #bounds { fn decode_children( #children: &[::knuffel::ast::SpannedNode<#span_ty>], #ctx: &mut ::knuffel::decode::Context<#span_ty>) -> Result> { #decode_children #assign_extra Ok(#struct_val) } } }); } Ok(quote! { #(#extra_traits)* impl #impl_gen ::knuffel::Decode #trait_gen for #s_name #type_gen #bounds { fn decode_node(#node: &::knuffel::ast::SpannedNode<#span_ty>, #ctx: &mut ::knuffel::decode::Context<#span_ty>) -> Result> { #decode_specials #decode_args #decode_props let #children = #node.children.as_ref() .map(|lst| &lst[..]).unwrap_or(&[]); #decode_children_normal #assign_extra Ok(#struct_val) } } }) } pub fn emit_new_type(s: &NewType) -> syn::Result { let s_name = &s.ident; let node = syn::Ident::new("node", Span::mixed_site()); let ctx = syn::Ident::new("ctx", Span::mixed_site()); Ok(quote! { impl ::knuffel::Decode for #s_name { fn decode_node(#node: &::knuffel::ast::SpannedNode, #ctx: &mut ::knuffel::decode::Context) -> Result> { if #node.arguments.len() > 0 || #node.properties.len() > 0 || #node.children.is_some() { ::knuffel::Decode::decode_node(#node, #ctx) .map(Some) .map(#s_name) } else { Ok(#s_name(None)) } } } }) } pub(crate) fn decode_enum_item(s: &Common, s_name: impl ToTokens, node: &syn::Ident, named: bool) -> syn::Result { let children = syn::Ident::new("children", Span::mixed_site()); let decode_args = decode_args(s, node)?; let decode_props = decode_props(s, node)?; let decode_children = decode_children(s, &children, Some(quote!(#node.span())))?; let assign_extra = assign_extra(s)?; let all_fields = s.object.all_fields(); let struct_val = if named { let assignments = all_fields.iter() .map(|f| f.as_assign_pair().unwrap()); quote!(#s_name { #(#assignments,)* }) } else { let mut fields = all_fields.iter() .map(|f| (f.as_index().unwrap(), &f.tmp_name)) .collect::>(); fields.sort_by_key(|(idx, _)| *idx); assert_eq!(fields.iter().map(|(idx, _)| *idx).collect::>(), (0..fields.len()).collect::>(), "all tuple structure fields should be filled in"); let assignments = fields.iter().map(|(_, v)| v); quote!{ #s_name(#(#assignments),*) } }; Ok(quote! { #decode_args #decode_props let #children = #node.children.as_ref() .map(|lst| &lst[..]).unwrap_or(&[]); #decode_children #assign_extra Ok(#struct_val) }) } fn decode_value(val: &syn::Ident, ctx: &syn::Ident, mode: &DecodeMode, optional: bool) -> syn::Result { match mode { DecodeMode::Normal => { Ok(quote!{ ::knuffel::traits::DecodeScalar::decode(#val, #ctx) }) } DecodeMode::Str if optional => { Ok(quote![{ if let Some(typ) = &#val.type_name { #ctx.emit_error(::knuffel::errors::DecodeError::TypeName { span: typ.span().clone(), found: Some((**typ).clone()), expected: ::knuffel::errors::ExpectedType::no_type(), rust_type: "str", // TODO(tailhook) show field type }); } match *#val.literal { ::knuffel::ast::Literal::String(ref s) => { ::std::str::FromStr::from_str(s).map_err(|e| { ::knuffel::errors::DecodeError::conversion( &#val.literal, e) }) .map(Some) } ::knuffel::ast::Literal::Null => Ok(None), _ => { #ctx.emit_error( ::knuffel::errors::DecodeError::scalar_kind( ::knuffel::decode::Kind::String, &#val.literal, ) ); Ok(None) } } }]) } DecodeMode::Str => { Ok(quote![{ if let Some(typ) = &#val.type_name { #ctx.emit_error(::knuffel::errors::DecodeError::TypeName { span: typ.span().clone(), found: Some((**typ).clone()), expected: ::knuffel::errors::ExpectedType::no_type(), rust_type: "str", // TODO(tailhook) show field type }); } match *#val.literal { ::knuffel::ast::Literal::String(ref s) => { ::std::str::FromStr::from_str(s).map_err(|e| { ::knuffel::errors::DecodeError::conversion( &#val.literal, e) }) } _ => Err(::knuffel::errors::DecodeError::scalar_kind( ::knuffel::decode::Kind::String, &#val.literal, )), } }]) } DecodeMode::Bytes if optional => { Ok(quote! { if matches!(&*#val.literal, ::knuffel::ast::Literal::Null) { Ok(None) } else { match ::knuffel::decode::bytes(#val, #ctx).try_into() { Ok(v) => Ok(Some(v)), Err(e) => { #ctx.emit_error( ::knuffel::errors::DecodeError::conversion( &#val.literal, e)); Ok(None) } } } }) } DecodeMode::Bytes => { Ok(quote! { ::knuffel::decode::bytes(#val, #ctx).try_into() .map_err(|e| ::knuffel::errors::DecodeError::conversion( &#val.literal, e)) }) } } } fn decode_specials(s: &Common, node: &syn::Ident) -> syn::Result { let ctx = s.ctx; let spans = s.object.spans.iter().flat_map(|span| { let fld = &span.field.tmp_name; quote! { let #fld = ::knuffel::traits::DecodeSpan::decode_span( #node.span(), #ctx, ); } }); let node_names = s.object.node_names.iter().flat_map(|node_name| { let fld = &node_name.field.tmp_name; quote! { let #fld = #node.node_name.parse() .map_err(|e| { ::knuffel::errors::DecodeError::conversion( &#node.node_name, e) })?; } }); let type_names = s.object.type_names.iter().flat_map(|type_name| { let fld = &type_name.field.tmp_name; if type_name.option { quote! { let #fld = #node.type_name.as_ref().map(|tn| { tn.as_str() .parse() .map_err(|e| { ::knuffel::errors::DecodeError::conversion(tn, e) }) }).transpose()?; } } else { quote! { let #fld = if let Some(tn) = #node.type_name.as_ref() { tn.as_str() .parse() .map_err(|e| { ::knuffel::errors::DecodeError::conversion(tn, e) })? } else { return Err(::knuffel::errors::DecodeError::missing( #node, "type name required")); }; } } }); let validate_type = if s.object.type_names.is_empty() { Some(quote! { if let Some(type_name) = &#node.type_name { #ctx.emit_error(::knuffel::errors::DecodeError::unexpected( type_name, "type name", "no type name expected for this node")); } }) } else { None }; Ok(quote! { #(#spans)* #(#node_names)* #(#type_names)* #validate_type }) } fn decode_args(s: &Common, node: &syn::Ident) -> syn::Result { let ctx = s.ctx; let mut decoder = Vec::new(); let iter_args = syn::Ident::new("iter_args", Span::mixed_site()); decoder.push(quote! { let mut #iter_args = #node.arguments.iter(); }); for arg in &s.object.arguments { let fld = &arg.field.tmp_name; let val = syn::Ident::new("val", Span::mixed_site()); let decode_value = decode_value(&val, ctx, &arg.decode, arg.option)?; match (&arg.default, &arg.kind) { (None, ArgKind::Value { option: true }) => { decoder.push(quote! { let #fld = #iter_args.next().map(|#val| { #decode_value }).transpose()?.and_then(|v| v); }); } (None, ArgKind::Value { option: false }) => { let error = if arg.field.is_indexed() { "additional argument is required".into() } else { format!("additional argument `{}` is required", fld.unraw()) }; decoder.push(quote! { let #val = #iter_args.next().ok_or_else(|| { ::knuffel::errors::DecodeError::missing( #node, #error) })?; let #fld = #decode_value?; }); } (Some(default_value), ArgKind::Value {..}) => { let default = if let Some(expr) = default_value { quote!(#expr) } else { quote!(::std::default::Default::default()) }; decoder.push(quote! { let #fld = #iter_args.next().map(|#val| { #decode_value }).transpose()?.unwrap_or_else(|| { #default }); }); } } } if let Some(var_args) = &s.object.var_args { let fld = &var_args.field.tmp_name; let val = syn::Ident::new("val", Span::mixed_site()); let decode_value = decode_value(&val, ctx, &var_args.decode, false)?; decoder.push(quote! { let #fld = #iter_args.map(|#val| { #decode_value }).collect::>()?; }); } else { decoder.push(quote! { if let Some(val) = #iter_args.next() { return Err(::knuffel::errors::DecodeError::unexpected( &val.literal, "argument", "unexpected argument")); } }); } Ok(quote! { #(#decoder)* }) } fn decode_props(s: &Common, node: &syn::Ident) -> syn::Result { let mut declare_empty = Vec::new(); let mut match_branches = Vec::new(); let mut postprocess = Vec::new(); let ctx = s.ctx; let val = syn::Ident::new("val", Span::mixed_site()); let name = syn::Ident::new("name", Span::mixed_site()); let name_str = syn::Ident::new("name_str", Span::mixed_site()); for prop in &s.object.properties { let fld = &prop.field.tmp_name; let prop_name = &prop.name; let seen_name = format_ident!("seen_{}", fld, span = Span::mixed_site()); if prop.flatten { declare_empty.push(quote! { let mut #fld = ::std::default::Default::default(); }); match_branches.push(quote! { _ if ::knuffel::traits::DecodePartial:: insert_property(&mut #fld, #name, #val, #ctx)? => {} }); } else { let decode_value = decode_value(&val, ctx, &prop.decode, prop.option)?; declare_empty.push(quote! { let mut #fld = None; let mut #seen_name = false; }); if prop.option { match_branches.push(quote! { #prop_name => { #seen_name = true; #fld = #decode_value?; } }); } else { match_branches.push(quote! { #prop_name => { #fld = Some(#decode_value?); } }); } let req_msg = format!("property `{}` is required", prop_name); if let Some(value) = &prop.default { let default = if let Some(expr) = value { quote!(#expr) } else { quote!(::std::default::Default::default()) }; if prop.option { postprocess.push(quote! { if !#seen_name { #fld = #default; }; }); } else { postprocess.push(quote! { let #fld = #fld.unwrap_or_else(|| #default); }); } } else if !prop.option { postprocess.push(quote! { let #fld = #fld.ok_or_else(|| { ::knuffel::errors::DecodeError::missing( #node, #req_msg) })?; }); } } } if let Some(var_props) = &s.object.var_props { let fld = &var_props.field.tmp_name; let decode_value = decode_value(&val, ctx, &var_props.decode, false)?; declare_empty.push(quote! { let mut #fld = Vec::new(); }); match_branches.push(quote! { #name_str => { let converted_name = #name_str.parse() .map_err(|e| { ::knuffel::errors::DecodeError::conversion(#name, e) })?; #fld.push(( converted_name, #decode_value?, )); } }); postprocess.push(quote! { let #fld = #fld.into_iter().collect(); }); } else { match_branches.push(quote! { #name_str => { return Err(::knuffel::errors::DecodeError::unexpected( #name, "property", format!("unexpected property `{}`", #name_str.escape_default()))); } }); }; Ok(quote! { #(#declare_empty)* for (#name, #val) in #node.properties.iter() { match &***#name { #(#match_branches)* } } #(#postprocess)* }) } fn unwrap_fn(parent: &Common, func: &syn::Ident, name: &syn::Ident, attrs: &FieldAttrs) -> syn::Result { let ctx = parent.ctx; let span_ty = parent.span_type; let mut bld = StructBuilder::new( format_ident!("Wrap_{}", name, span = Span::mixed_site()), parent.object.trait_props.clone(), parent.object.generics.clone(), ); bld.add_field(Field::new_named(name), false, false, attrs)?; let object = bld.build(); let common = Common { object: &object, ctx: parent.ctx, span_type: parent.span_type, }; let node = syn::Ident::new("node", Span::mixed_site()); let children = syn::Ident::new("children", Span::mixed_site()); let decode_args = decode_args(&common, &node)?; let decode_props = decode_props(&common, &node)?; let decode_children = decode_children(&common, &children, Some(quote!(#node.span())))?; Ok(quote! { let mut #func = |#node: &::knuffel::ast::SpannedNode<#span_ty>, #ctx: &mut ::knuffel::decode::Context<#span_ty>| { #decode_args #decode_props let #children = #node.children.as_ref() .map(|lst| &lst[..]).unwrap_or(&[]); #decode_children Ok(#name) }; }) } fn decode_node(common: &Common, child_def: &Child, in_partial: bool, child: &syn::Ident) -> syn::Result { let ctx = common.ctx; let fld = &child_def.field.tmp_name; let dest = if in_partial { child_def.field.from_self() } else { quote!(#fld) }; let (init, func) = if let Some(unwrap) = &child_def.unwrap { let func = format_ident!("unwrap_{}", fld, span = Span::mixed_site()); let unwrap_fn = unwrap_fn(common, &func, fld, unwrap)?; (unwrap_fn, quote!(#func)) } else { (quote!(), quote!(::knuffel::Decode::decode_node)) }; let value = syn::Ident::new("value", Span::mixed_site()); let assign = if matches!(child_def.mode, ChildMode::Multi) { quote!(#dest.push(#value)) } else { quote!(#dest = Some(#value)) }; if in_partial { Ok(quote! { { #init let #value = #func(#child, #ctx)?; #assign; Ok(true) } }) } else { Ok(quote! { { #init match #func(#child, #ctx) { Ok(#value) => { #assign; None } Err(e) => Some(Err(e)), } } }) } } fn insert_child(s: &Common, node: &syn::Ident) -> syn::Result { let ctx = s.ctx; let mut match_branches = Vec::with_capacity(s.object.children.len()); for child_def in &s.object.children { let dest = &child_def.field.from_self(); let child_name = &child_def.name; if matches!(child_def.mode, ChildMode::Flatten) { match_branches.push(quote! { _ if ::knuffel::traits::DecodePartial ::insert_child(&mut #dest, #node, #ctx)? => Ok(true), }) } else if matches!(child_def.mode, ChildMode::Bool) { let dup_err = format!("duplicate node `{}`, single node expected", child_name.escape_default()); match_branches.push(quote! { #child_name => { ::knuffel::decode::check_flag_node(#node, #ctx); if #dest { #ctx.emit_error( ::knuffel::errors::DecodeError::unexpected( &#node.node_name, "node", #dup_err)); } else { #dest = true; } Ok(true) } }); } else { let dup_err = format!("duplicate node `{}`, single node expected", child_name.escape_default()); let decode = decode_node(s, &child_def, true, node)?; match_branches.push(quote! { #child_name => { if #dest.is_some() { #ctx.emit_error( ::knuffel::errors::DecodeError::unexpected( &#node.node_name, "node", #dup_err)); } #decode } }); } } Ok(quote! { match &**#node.node_name { #(#match_branches)* _ => Ok(false), } }) } fn insert_property(s: &Common, name: &syn::Ident, value: &syn::Ident) -> syn::Result { let ctx = s.ctx; let mut match_branches = Vec::with_capacity(s.object.children.len()); for prop in &s.object.properties { let dest = &prop.field.from_self(); let prop_name = &prop.name; if prop.flatten { match_branches.push(quote! { _ if ::knuffel::traits::DecodePartial ::insert_property(&mut #dest, #name, #value, #ctx)? => Ok(true), }); } else { let decode_value = decode_value(&value, ctx, &prop.decode, prop.option)?; if prop.option { match_branches.push(quote! { #prop_name => { #dest = #decode_value?; Ok(true) } }); } else { match_branches.push(quote! { #prop_name => { #dest = Some(#decode_value?); Ok(true) } }); } } } Ok(quote! { match &***#name { #(#match_branches)* _ => Ok(false), } }) } fn decode_children(s: &Common, children: &syn::Ident, err_span: Option) -> syn::Result { let mut declare_empty = Vec::new(); let mut match_branches = Vec::new(); let mut postprocess = Vec::new(); let ctx = s.ctx; let child = syn::Ident::new("child", Span::mixed_site()); let name_str = syn::Ident::new("name_str", Span::mixed_site()); for child_def in &s.object.children { let fld = &child_def.field.tmp_name; let child_name = &child_def.name; match child_def.mode { ChildMode::Flatten => { declare_empty.push(quote! { let mut #fld = ::std::default::Default::default(); }); match_branches.push(quote! { _ if ( match ::knuffel::traits::DecodePartial ::insert_child(&mut #fld, #child, #ctx) { Ok(true) => return None, Ok(false) => false, Err(e) => return Some(Err(e)), } ) => None, }) } ChildMode::Multi => { declare_empty.push(quote! { let mut #fld = Vec::new(); }); let decode = decode_node(s, &child_def, false, &child)?; match_branches.push(quote! { #child_name => #decode, }); if let Some(default_value) = &child_def.default { let default = if let Some(expr) = default_value { quote!(#expr) } else { quote!(::std::default::Default::default()) }; if child_def.option { postprocess.push(quote! { let #fld = if #fld.is_empty() { #default } else { Some(#fld.into_iter().collect()) }; }); } else { postprocess.push(quote! { let #fld = if #fld.is_empty() { #default } else { #fld.into_iter().collect() }; }); } } else if child_def.option { postprocess.push(quote! { let #fld = if #fld.is_empty() { None } else { Some(#fld.into_iter().collect()) }; }); } else { postprocess.push(quote! { let #fld = #fld.into_iter().collect(); }); } } ChildMode::Normal => { declare_empty.push(quote! { let mut #fld = None; }); let dup_err = format!( "duplicate node `{}`, single node expected", child_name.escape_default()); let decode = decode_node(s, &child_def, false, &child)?; match_branches.push(quote! { #child_name => { if #fld.is_some() { Some(Err( ::knuffel::errors::DecodeError::unexpected( &#child.node_name, "node", #dup_err))) } else { #decode } } }); let req_msg = format!("child node `{}` is required", child_name); if let Some(default_value) = &child_def.default { let default = if let Some(expr) = default_value { quote!(#expr) } else { quote!(::std::default::Default::default()) }; postprocess.push(quote! { let #fld = #fld.unwrap_or_else(|| #default); }); } else if !child_def.option { if let Some(span) = &err_span { postprocess.push(quote! { let #fld = #fld.ok_or_else(|| { ::knuffel::errors::DecodeError::Missing { span: #span.clone(), message: #req_msg.into(), } })?; }); } else { postprocess.push(quote! { let #fld = #fld.ok_or_else(|| { ::knuffel::errors::DecodeError::MissingNode { message: #req_msg.into(), } })?; }); } } } ChildMode::Bool => { let dup_err = format!( "duplicate node `{}`, single node expected", child_name.escape_default()); declare_empty.push(quote! { let mut #fld = false; }); match_branches.push(quote! { #child_name => { ::knuffel::decode::check_flag_node(#child, #ctx); if #fld { #ctx.emit_error( ::knuffel::errors::DecodeError::unexpected( &#child.node_name, "node", #dup_err)); } else { #fld = true; } None } }); } } } if let Some(var_children) = &s.object.var_children { let fld = &var_children.field.tmp_name; let (init, func) = if let Some(unwrap) = &var_children.unwrap { let func = format_ident!("unwrap_{}", fld, span = Span::mixed_site()); let unwrap_fn = unwrap_fn(s, &func, fld, unwrap)?; (unwrap_fn, quote!(#func)) } else { (quote!(), quote!(::knuffel::Decode::decode_node)) }; match_branches.push(quote! { _ => { #init match #func(#child, #ctx) { Ok(#child) => Some(Ok(#child)), Err(e) => Some(Err(e)), } } }); Ok(quote! { #(#declare_empty)* let #fld = #children.iter().flat_map(|#child| { match &**#child.node_name { #(#match_branches)* } }).collect::>>()?; #(#postprocess)* }) } else { match_branches.push(quote! { #name_str => { #ctx.emit_error(::knuffel::errors::DecodeError::unexpected( #child, "node", format!("unexpected node `{}`", #name_str.escape_default()))); None } }); Ok(quote! { #(#declare_empty)* #children.iter().flat_map(|#child| { match &**#child.node_name { #(#match_branches)* } }).collect::>>()?; #(#postprocess)* }) } } fn assign_extra(s: &Common) -> syn::Result { let items = s.object.extra_fields.iter().map(|fld| { match fld.kind { ExtraKind::Auto => { let name = &fld.field.tmp_name; quote!(let #name = ::std::default::Default::default();) } } }); Ok(quote!(#(#items)*)) } knuffel-derive-3.2.0/src/scalar.rs000064400000000000000000000105521046102023000151410ustar 00000000000000use proc_macro2::TokenStream; use quote::quote; use syn::ext::IdentExt; use syn::parse::{Parse, ParseStream}; use syn::spanned::Spanned; pub enum Scalar { Enum(Enum), } pub struct Enum { pub ident: syn::Ident, pub variants: Vec, } pub struct Variant { pub ident: syn::Ident, pub name: String, } impl Enum { fn new(ident: syn::Ident, _attrs: Vec, src_variants: impl Iterator) -> syn::Result { let mut variants = Vec::new(); for var in src_variants { match var.fields { syn::Fields::Unit => { let name = heck::ToKebabCase ::to_kebab_case(&var.ident.unraw().to_string()[..]); variants.push(Variant { ident: var.ident, name, }); } _ => { return Err(syn::Error::new(var.span(), "only unit variants are allowed for DecodeScalar")); } } } Ok(Enum { ident, variants, }) } } impl Parse for Scalar { fn parse(input: ParseStream) -> syn::Result { let mut attrs = input.call(syn::Attribute::parse_outer)?; let ahead = input.fork(); let _vis: syn::Visibility = ahead.parse()?; let lookahead = ahead.lookahead1(); if lookahead.peek(syn::Token![enum]) { let item: syn::ItemEnum = input.parse()?; attrs.extend(item.attrs); Enum::new(item.ident, attrs, item.variants.into_iter()) .map(Scalar::Enum) } else { Err(lookahead.error()) } } } pub fn emit_scalar(s: &Scalar) -> syn::Result { match s { Scalar::Enum(e) => { emit_enum(e) } } } pub fn emit_enum(e: &Enum) -> syn::Result { let e_name = &e.ident; let value_err = if e.variants.len() <= 3 { format!("expected one of {}", e.variants.iter() .map(|v| format!("`{}`", v.name.escape_default())) .collect::>() .join(", ")) } else { format!("expected `{}`, `{}`, or one of {} others", e.variants[0].name.escape_default(), e.variants[1].name.escape_default(), e.variants.len() - 2) }; let match_branches = e.variants.iter() .map(|var| { let name = &var.name; let ident = &var.ident; quote!(#name => Ok(#e_name::#ident)) }); Ok(quote! { impl ::knuffel::DecodeScalar for #e_name { fn raw_decode(val: &::knuffel::span::Spanned< ::knuffel::ast::Literal, S>, ctx: &mut ::knuffel::decode::Context) -> Result<#e_name, ::knuffel::errors::DecodeError> { match &**val { ::knuffel::ast::Literal::String(ref s) => { match &s[..] { #(#match_branches,)* _ => { Err(::knuffel::errors::DecodeError::conversion( val, #value_err)) } } } _ => { Err(::knuffel::errors::DecodeError::scalar_kind( ::knuffel::decode::Kind::String, &val, )) } } } fn type_check(type_name: &Option<::knuffel::span::Spanned< ::knuffel::ast::TypeName, S>>, ctx: &mut ::knuffel::decode::Context) { if let Some(typ) = type_name { ctx.emit_error(::knuffel::errors::DecodeError::TypeName { span: typ.span().clone(), found: Some((**typ).clone()), expected: ::knuffel::errors::ExpectedType::no_type(), rust_type: stringify!(#e_name), }); } } } }) } knuffel-derive-3.2.0/src/variants.rs000064400000000000000000000134401046102023000155220ustar 00000000000000use proc_macro2::{TokenStream, Span}; use quote::quote; use crate::definition::{Enum, VariantKind}; use crate::node; pub(crate) struct Common<'a> { pub object: &'a Enum, pub ctx: &'a syn::Ident, pub span_type: &'a TokenStream, } pub fn emit_enum(e: &Enum) -> syn::Result { let name = &e.ident; let node = syn::Ident::new("node", Span::mixed_site()); let ctx = syn::Ident::new("ctx", Span::mixed_site()); let (_, type_gen, _) = e.generics.split_for_impl(); let mut common_generics = e.generics.clone(); let span_ty; if let Some(ty) = e.trait_props.span_type.as_ref() { span_ty = quote!(#ty); } else { if common_generics.params.is_empty() { common_generics.lt_token = Some(Default::default()); common_generics.gt_token = Some(Default::default()); } common_generics.params.push(syn::parse2(quote!(S)).unwrap()); span_ty = quote!(S); common_generics.make_where_clause().predicates.push( syn::parse2(quote!(S: ::knuffel::traits::ErrorSpan)).unwrap()); }; let trait_gen = quote!(<#span_ty>); let (impl_gen, _, bounds) = common_generics.split_for_impl(); let common = Common { object: e, ctx: &ctx, span_type: &span_ty, }; let decode = decode(&common, &node)?; Ok(quote! { impl #impl_gen ::knuffel::Decode #trait_gen for #name #type_gen #bounds { fn decode_node(#node: &::knuffel::ast::SpannedNode<#span_ty>, #ctx: &mut ::knuffel::decode::Context<#span_ty>) -> Result> { #decode } } }) } fn decode(e: &Common, node: &syn::Ident) -> syn::Result { let ctx = e.ctx; let mut branches = Vec::with_capacity(e.object.variants.len()); let enum_name = &e.object.ident; for var in &e.object.variants { let name = &var.name; let variant_name = &var.ident; match &var.kind { VariantKind::Unit => { branches.push(quote! { #name => { for arg in &#node.arguments { #ctx.emit_error( ::knuffel::errors::DecodeError::unexpected( &arg.literal, "argument", "unexpected argument")); } for (name, _) in &#node.properties { #ctx.emit_error( ::knuffel::errors::DecodeError::unexpected( name, "property", format!("unexpected property `{}`", name.escape_default()))); } if let Some(children) = &#node.children { for child in children.iter() { #ctx.emit_error( ::knuffel::errors::DecodeError::unexpected( child, "node", format!("unexpected node `{}`", child.node_name.escape_default()) )); } } Ok(#enum_name::#variant_name) } }); } VariantKind::Nested { option: false } => { branches.push(quote! { #name => ::knuffel::Decode::decode_node(#node, #ctx) .map(#enum_name::#variant_name), }); } VariantKind::Nested { option: true } => { branches.push(quote! { #name => { if #node.arguments.len() > 0 || #node.properties.len() > 0 || #node.children.is_some() { ::knuffel::Decode::decode_node(#node, #ctx) .map(Some) .map(#enum_name::#variant_name) } else { Ok(#enum_name::#variant_name(None)) } } }); } VariantKind::Tuple(s) => { let common = node::Common { object: s, ctx, span_type: e.span_type, }; let decode = node::decode_enum_item( &common, quote!(#enum_name::#variant_name), node, false, )?; branches.push(quote! { #name => { #decode } }); } VariantKind::Named(_) => todo!(), } } // TODO(tailhook) use strsim to find similar names let err = if e.object.variants.len() <= 3 { format!("expected one of {}", e.object.variants.iter() .map(|v| format!("`{}`", v.name.escape_default())) .collect::>() .join(", ")) } else { format!("expected `{}`, `{}`, or one of {} others", e.object.variants[0].name.escape_default(), e.object.variants[1].name.escape_default(), e.object.variants.len() - 2) }; Ok(quote! { match &**#node.node_name { #(#branches)* name_str => { Err(::knuffel::errors::DecodeError::conversion( &#node.node_name, #err)) } } }) } knuffel-derive-3.2.0/tests/ast.rs000064400000000000000000000010311046102023000150260ustar 00000000000000use knuffel::span::Span; use knuffel::traits::Decode; #[derive(knuffel_derive::Decode, Debug)] #[knuffel(span_type=knuffel::span::Span)] struct AstChildren { #[knuffel(children)] children: Vec>, } fn parse>(text: &str) -> T { let mut nodes: Vec = knuffel::parse("", text).unwrap(); assert_eq!(nodes.len(), 1); nodes.remove(0) } #[test] fn parse_node_span() { let item = parse::(r#"node {a; b;}"#); assert_eq!(item.children.len(), 2); } knuffel-derive-3.2.0/tests/extra.rs000064400000000000000000000045531046102023000153760ustar 00000000000000use knuffel::span::Span; use knuffel::traits::Decode; use knuffel::ast::{TypeName, BuiltinType}; #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct Child; #[derive(knuffel_derive::Decode, Debug, PartialEq)] #[knuffel(span_type=Span)] struct NodeSpan { #[knuffel(span)] span: Span, #[knuffel(argument)] name: String, #[knuffel(children)] children: Vec, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct NodeType { #[knuffel(type_name)] type_name: String, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct NameAndType { #[knuffel(node_name)] node_name: String, #[knuffel(type_name)] type_name: Option, } fn parse>(text: &str) -> T { let mut nodes: Vec = knuffel::parse("", text).unwrap(); assert_eq!(nodes.len(), 1); nodes.remove(0) } #[test] fn parse_node_span() { assert_eq!(parse::(r#"node "hello""#), NodeSpan { span: Span(0, 12), name: "hello".into(), children: Vec::new(), }); assert_eq!(parse::(r#" node "hello" "#), NodeSpan { span: Span(3, 21), name: "hello".into(), children: Vec::new(), }); assert_eq!(parse::(r#" node "hello"; "#), NodeSpan { span: Span(3, 17), name: "hello".into(), children: Vec::new(), }); assert_eq!(parse::(r#" node "hello" { child; }"#), NodeSpan { span: Span(3, 35), name: "hello".into(), children: vec![Child], }); } #[test] fn parse_node_type() { assert_eq!(parse::(r#"(unknown)node {}"#), NodeType { type_name: "unknown".into() }); } #[test] fn parse_name_and_type() { assert_eq!(parse::(r#"(u32)nodexxx"#), NameAndType { node_name: "nodexxx".into(), type_name: Some(BuiltinType::U32.into()), }); assert_eq!(parse::(r#"yyynode /-{ }"#), NameAndType { node_name: "yyynode".into(), type_name: None, }); } knuffel-derive-3.2.0/tests/flatten.rs000064400000000000000000000036301046102023000157030ustar 00000000000000use std::fmt; use miette::Diagnostic; use knuffel::{Decode, span::Span}; use knuffel::traits::DecodeChildren; #[derive(knuffel_derive::Decode, Default, Debug, PartialEq)] struct Prop1 { #[knuffel(property)] label: Option, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct FlatProp { #[knuffel(flatten(property))] props: Prop1, } #[derive(knuffel_derive::Decode, Default, Debug, PartialEq)] struct Unwrap { #[knuffel(child, unwrap(argument))] label: Option, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct FlatChild { #[knuffel(flatten(child))] children: Unwrap, } fn parse>(text: &str) -> T { let mut nodes: Vec = knuffel::parse("", text).unwrap(); assert_eq!(nodes.len(), 1); nodes.remove(0) } fn parse_err+fmt::Debug>(text: &str) -> String { let err = knuffel::parse::>("", text).unwrap_err(); err.related().unwrap() .map(|e| e.to_string()).collect::>() .join("\n") } fn parse_doc>(text: &str) -> T { knuffel::parse("", text).unwrap() } fn parse_doc_err+fmt::Debug>(text: &str) -> String { let err = knuffel::parse::("", text).unwrap_err(); err.related().unwrap() .map(|e| e.to_string()).collect::>() .join("\n") } #[test] fn parse_flat_prop() { assert_eq!(parse::(r#"node label="hello""#), FlatProp { props: Prop1 { label: Some("hello".into()) } } ); assert_eq!(parse_err::(r#"node something="world""#), "unexpected property `something`"); } #[test] fn parse_flat_child() { assert_eq!(parse_doc::(r#"label "hello""#), FlatChild { children: Unwrap { label: Some("hello".into()) } } ); assert_eq!(parse_doc_err::(r#"something "world""#), "unexpected node `something`"); } knuffel-derive-3.2.0/tests/normal.rs000064400000000000000000000435751046102023000155520ustar 00000000000000use std::fmt; use std::collections::BTreeMap; use std::default::Default; use miette::Diagnostic; use knuffel::{Decode, span::Span}; use knuffel::traits::DecodeChildren; #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct Arg1 { #[knuffel(argument)] name: String, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct Arg1RawIdent { #[knuffel(argument)] r#type: String, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct ArgDef { #[knuffel(argument, default)] name: String, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct ArgDefValue { #[knuffel(argument, default="unnamed".into())] name: String, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct ArgDefOptValue { #[knuffel(argument, default=Some("unnamed".into()))] name: Option, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct OptArg { #[knuffel(argument)] name: Option, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct Extra { field: String, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct VarArg { #[knuffel(arguments)] params: Vec, } #[derive(knuffel_derive::Decode, Debug, PartialEq, Default)] struct Prop1 { #[knuffel(property)] label: String, } #[derive(knuffel_derive::Decode, Debug, PartialEq, Default)] struct Prop1RawIdent { #[knuffel(property)] r#type: String, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct PropDef { #[knuffel(property, default)] label: String, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct PropDefValue { #[knuffel(property, default="unknown".into())] label: String, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct PropDefOptValue { #[knuffel(property, default=Some("unknown".into()))] label: Option, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct PropNamed { #[knuffel(property(name="x"))] label: String, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct OptProp { #[knuffel(property)] label: Option, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct VarProp { #[knuffel(properties)] scores: BTreeMap, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct Children { #[knuffel(children)] children: Vec, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct FilteredChildren { #[knuffel(children(name="left"))] left: Vec, #[knuffel(children(name="right"))] right: Vec, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] enum Variant { Arg1(Arg1), Prop1(Prop1), #[knuffel(skip)] #[allow(dead_code)] Var3(u32), } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct Child { #[knuffel(child)] main: Prop1, #[knuffel(child)] extra: Option, #[knuffel(child)] flag: bool, #[knuffel(child)] унікод: Option, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct ChildDef { #[knuffel(child, default)] main: Prop1, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct ChildDefValue { #[knuffel(child, default=Prop1 { label: String::from("prop1") })] main: Prop1, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct Unwrap { #[knuffel(child, unwrap(argument))] label: String, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct UnwrapRawIdent { #[knuffel(child, unwrap(argument))] r#type: String, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct UnwrapFiltChildren { #[knuffel(children(name="labels"), unwrap(arguments))] labels: Vec>, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct UnwrapChildren { #[knuffel(children, unwrap(arguments))] labels: Vec>, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct Parse { #[knuffel(child, unwrap(argument, str))] listen: std::net::SocketAddr, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct ParseOpt { #[knuffel(property, str)] listen: Option, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct Bytes { #[knuffel(child, unwrap(argument, bytes))] data: Vec, } #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct OptBytes { #[knuffel(property, bytes)] data: Option>, } fn parse>(text: &str) -> T { let mut nodes: Vec = knuffel::parse("", text).unwrap(); assert_eq!(nodes.len(), 1); nodes.remove(0) } fn parse_err+fmt::Debug>(text: &str) -> String { let err = knuffel::parse::>("", text).unwrap_err(); err.related().unwrap() .map(|e| e.to_string()).collect::>() .join("\n") } fn parse_doc>(text: &str) -> T { knuffel::parse("", text).unwrap() } fn parse_doc_err+fmt::Debug>(text: &str) -> String { let err = knuffel::parse::("", text).unwrap_err(); err.related().unwrap() .map(|e| e.to_string()).collect::>() .join("\n") } #[test] fn parse_arg1() { assert_eq!(parse::(r#"node "hello""#), Arg1 { name: "hello".into() } ); assert_eq!(parse_err::(r#"node "hello" "world""#), "unexpected argument"); assert_eq!(parse_err::(r#"(some)node "hello""#), "no type name expected for this node"); assert_eq!(parse_err::(r#"node"#), "additional argument `name` is required"); } #[test] fn parse_arg1_raw_ident() { assert_eq!(parse::(r#"node "hello""#), Arg1RawIdent { r#type: "hello".into() } ); assert_eq!(parse_err::(r#"node "hello" "world""#), "unexpected argument"); assert_eq!(parse_err::(r#"(some)node "hello""#), "no type name expected for this node"); assert_eq!(parse_err::(r#"node"#), "additional argument `type` is required"); } #[test] fn parse_arg_default() { assert_eq!(parse::(r#"node "hello""#), ArgDef { name: "hello".into() } ); assert_eq!(parse_err::(r#"node "hello" "world""#), "unexpected argument"); assert_eq!(parse::(r#"node"#), ArgDef { name: "".into() } ); } #[test] fn parse_arg_def_value() { assert_eq!(parse::(r#"node "hello""#), ArgDefValue { name: "hello".into() } ); assert_eq!(parse_err::(r#"node "hello" "world""#), "unexpected argument"); assert_eq!(parse::(r#"node"#), ArgDefValue { name: "unnamed".into() } ); assert_eq!(parse::(r#"node "hello""#), ArgDefOptValue { name: Some("hello".into()) } ); assert_eq!(parse_err::(r#"node "hello" "world""#), "unexpected argument"); assert_eq!(parse::(r#"node"#), ArgDefOptValue { name: Some("unnamed".into()) } ); assert_eq!(parse::(r#"node null"#), ArgDefOptValue { name: None } ); } #[test] fn parse_opt_arg() { assert_eq!(parse::(r#"node "hello""#), OptArg { name: Some("hello".into()) } ); assert_eq!(parse::(r#"node"#), OptArg { name: None }); assert_eq!(parse::(r#"node null"#), OptArg { name: None }); } #[test] fn parse_prop() { assert_eq!(parse::(r#"node label="hello""#), Prop1 { label: "hello".into() } ); assert_eq!(parse_err::(r#"node label="hello" y="world""#), "unexpected property `y`"); assert_eq!(parse_err::(r#"node"#), "property `label` is required"); } #[test] fn parse_prop_raw_ident() { assert_eq!(parse::(r#"node type="hello""#), Prop1RawIdent { r#type: "hello".into() } ); assert_eq!(parse_err::(r#"node type="hello" y="world""#), "unexpected property `y`"); assert_eq!(parse_err::(r#"node"#), "property `type` is required"); } #[test] fn parse_prop_default() { assert_eq!(parse::(r#"node label="hello""#), PropDef { label: "hello".into() } ); assert_eq!(parse::(r#"node"#), PropDef { label: "".into() }); } #[test] fn parse_prop_def_value() { assert_eq!(parse::(r#"node label="hello""#), PropDefValue { label: "hello".into() } ); assert_eq!(parse::(r#"node"#), PropDefValue { label: "unknown".into() }); assert_eq!(parse::(r#"node label="hello""#), PropDefOptValue { label: Some("hello".into()) } ); assert_eq!(parse::(r#"node"#), PropDefOptValue { label: Some("unknown".into()) }); assert_eq!(parse::(r#"node label=null"#), PropDefOptValue { label: None }); } #[test] fn parse_prop_named() { assert_eq!(parse::(r#"node x="hello""#), PropNamed { label: "hello".into() } ); assert_eq!(parse_err::(r#"node label="hello" y="world""#), "unexpected property `label`"); assert_eq!(parse_err::(r#"node"#), "property `x` is required"); } #[test] fn parse_unwrap() { assert_eq!(parse::(r#"node { label "hello"; }"#), Unwrap { label: "hello".into() } ); assert_eq!(parse_err::(r#"node label="hello""#), "unexpected property `label`"); assert_eq!(parse_err::(r#"node"#), "child node `label` is required"); assert_eq!(parse_doc::(r#"label "hello""#), Unwrap { label: "hello".into() } ); } #[test] fn parse_unwrap_raw_ident() { assert_eq!(parse::(r#"node { type "hello"; }"#), UnwrapRawIdent { r#type: "hello".into() } ); assert_eq!(parse_err::(r#"node type="hello""#), "unexpected property `type`"); assert_eq!(parse_err::(r#"node"#), "child node `type` is required"); assert_eq!(parse_doc::(r#"type "hello""#), UnwrapRawIdent { r#type: "hello".into() } ); } #[test] fn parse_unwrap_filtered_children() { assert_eq!(parse::( r#"node { labels "hello" "world"; labels "oh" "my"; }"#), UnwrapFiltChildren { labels: vec![ vec!["hello".into(), "world".into()], vec!["oh".into(), "my".into()], ]}, ); } #[test] fn parse_unwrap_children() { assert_eq!(parse::( r#"node { some "hello" "world"; other "oh" "my"; }"#), UnwrapChildren { labels: vec![ vec!["hello".into(), "world".into()], vec!["oh".into(), "my".into()], ]}, ); } #[test] fn parse_opt_prop() { assert_eq!(parse::(r#"node label="hello""#), OptProp { label: Some("hello".into()) } ); assert_eq!(parse::(r#"node"#), OptProp { label: None } ); assert_eq!(parse::(r#"node label=null"#), OptProp { label: None } ); } #[test] fn parse_var_arg() { assert_eq!(parse::(r#"sum 1 2 3"#), VarArg { params: vec![1, 2, 3] } ); assert_eq!(parse::(r#"sum"#), VarArg { params: vec![] } ); } #[test] fn parse_var_prop() { let mut scores = BTreeMap::new(); scores.insert("john".into(), 13); scores.insert("jack".into(), 7); assert_eq!(parse::(r#"scores john=13 jack=7"#), VarProp { scores } ); assert_eq!(parse::(r#"scores"#), VarProp { scores: BTreeMap::new() } ); } #[test] fn parse_children() { assert_eq!(parse::(r#"parent { - "val1"; - "val2"; }"#), Children { children: vec! [ Arg1 { name: "val1".into() }, Arg1 { name: "val2".into() }, ]} ); assert_eq!(parse::(r#"parent"#), Children { children: Vec::new() } ); assert_eq!(parse_doc::(r#"- "val1"; - "val2""#), Children { children: vec! [ Arg1 { name: "val1".into() }, Arg1 { name: "val2".into() }, ]} ); assert_eq!(parse_doc::(r#""#), Children { children: Vec::new() } ); } #[test] fn parse_filtered_children() { assert_eq!(parse_doc::( r#"left "v1"; right "v2"; left "v3""#), FilteredChildren { left: vec![ OptArg { name: Some("v1".into()) }, OptArg { name: Some("v3".into()) }, ], right: vec![ OptArg { name: Some("v2".into()) }, ] }); assert_eq!(parse_doc::(r#"right; left"#), FilteredChildren { left: vec![ OptArg { name: None }, ], right: vec![ OptArg { name: None }, ] }); assert_eq!(parse_doc_err::(r#"some"#), "unexpected node `some`"); } #[test] fn parse_child() { assert_eq!(parse::(r#"parent { main label="val1"; }"#), Child { main: Prop1 { label: "val1".into() }, extra: None, flag: false, унікод: None, }); assert_eq!(parse::(r#"parent { main label="primary"; extra label="replica"; }"#), Child { main: Prop1 { label: "primary".into() }, extra: Some(Prop1 { label: "replica".into() }), flag: false, унікод: None, }); assert_eq!(parse_err::(r#"parent { something; }"#), "unexpected node `something`\n\ child node `main` is required"); assert_eq!(parse_err::(r#"parent"#), "child node `main` is required"); assert_eq!(parse_doc::(r#"main label="val1""#), Child { main: Prop1 { label: "val1".into() }, extra: None, flag: false, унікод: None, }); assert_eq!(parse_doc::(r#" main label="primary" extra label="replica" flag "#), Child { main: Prop1 { label: "primary".into() }, extra: Some(Prop1 { label: "replica".into() }), flag: true, унікод: None, }); assert_eq!(parse_doc_err::(r#"something"#), "unexpected node `something`\n\ child node `main` is required"); assert_eq!(parse_doc_err::(r#""#), "child node `main` is required"); assert_eq!(parse_doc::(r#" main label="primary" унікод label="працює" "#), Child { main: Prop1 { label: "primary".into() }, extra: None, flag: false, унікод: Some(Prop1 { label: "працює".into() }), }); } #[test] fn parse_child_def() { assert_eq!(parse::(r#"parent { main label="val1"; }"#), ChildDef { main: Prop1 { label: "val1".into() }, }); assert_eq!(parse::(r#"parent"#), ChildDef { main: Prop1 { label: "".into() }, }); } #[test] fn parse_child_def_value() { assert_eq!(parse::(r#"parent { main label="val1"; }"#), ChildDefValue { main: Prop1 { label: "val1".into() }, }); assert_eq!(parse::(r#"parent"#), ChildDefValue { main: Prop1 { label: "prop1".into() }, }); } #[test] fn parse_enum() { assert_eq!(parse::(r#"arg1 "hello""#), Variant::Arg1(Arg1 { name: "hello".into() })); assert_eq!(parse::(r#"prop1 label="hello""#), Variant::Prop1(Prop1 { label: "hello".into() })); assert_eq!(parse_err::(r#"something"#), "expected one of `arg1`, `prop1`"); } #[test] fn parse_str() { assert_eq!(parse_doc::(r#"listen "127.0.0.1:8080""#), Parse { listen: "127.0.0.1:8080".parse().unwrap() }); assert!(parse_doc_err::(r#"listen "2/3""#).contains("invalid")); assert_eq!(parse::(r#"server listen="127.0.0.1:8080""#), ParseOpt { listen: Some("127.0.0.1:8080".parse().unwrap()) }); assert!(parse_err::(r#"server listen="2/3""#).contains("invalid")); assert_eq!(parse::(r#"server listen=null"#), ParseOpt { listen: None }); } #[test] fn parse_bytes() { assert_eq!(parse_doc::(r#"data (base64)"aGVsbG8=""#), Bytes { data: b"hello".to_vec() }); assert_eq!(parse_doc::(r#"data "world""#), Bytes { data: b"world".to_vec() }); assert_eq!(parse_doc_err::(r#"data (base64)"2/3""#), "Invalid padding"); assert_eq!(parse::(r#"node data=(base64)"aGVsbG8=""#), OptBytes { data: Some(b"hello".to_vec()) }); assert_eq!(parse::(r#"node data="world""#), OptBytes { data: Some(b"world".to_vec()) }); assert_eq!(parse::(r#"node data=null"#), OptBytes { data: None }); } #[test] fn parse_extra() { assert_eq!(parse::(r#"data"#), Extra { field: "".into() }); assert_eq!(parse_err::(r#"data x=1"#), "unexpected property `x`"); } knuffel-derive-3.2.0/tests/scalar.rs000064400000000000000000000020531046102023000155110ustar 00000000000000use std::fmt; use knuffel::{Decode}; use knuffel::span::Span; use miette::Diagnostic; #[derive(knuffel::DecodeScalar, Debug, PartialEq)] enum SomeScalar { First, AnotherOption, } #[derive(knuffel::Decode, Debug, PartialEq)] struct Item { #[knuffel(argument)] value: SomeScalar, } fn parse>(text: &str) -> T { let mut nodes: Vec = knuffel::parse("", text).unwrap(); assert_eq!(nodes.len(), 1); nodes.remove(0) } fn parse_err+fmt::Debug>(text: &str) -> String { let err = knuffel::parse::>("", text).unwrap_err(); err.related().unwrap() .map(|e| e.to_string()).collect::>() .join("\n") } #[test] fn parse_some_scalar() { assert_eq!(parse::(r#"node "first""#), Item { value: SomeScalar::First } ); assert_eq!(parse::(r#"node "another-option""#), Item { value: SomeScalar::AnotherOption } ); assert_eq!(parse_err::(r#"node "test""#), "expected one of `first`, `another-option`"); } knuffel-derive-3.2.0/tests/tuples.rs000064400000000000000000000046511046102023000155660ustar 00000000000000use std::fmt; use miette::Diagnostic; use knuffel::{Decode, span::Span}; #[derive(Debug, Decode, PartialEq)] struct Unit; #[derive(Debug, Decode, PartialEq)] struct Arg(#[knuffel(argument)] u32); #[derive(Debug, Decode, PartialEq)] struct Opt(Option); #[derive(Debug, Decode, PartialEq)] struct Extra(#[knuffel(argument)] Option, u32); #[derive(Debug, Decode, PartialEq)] enum Enum { Unit, Arg(#[knuffel(argument)] u32), Opt(Option), Extra(#[knuffel(argument)] Option, u32), } fn parse>(text: &str) -> T { let mut nodes: Vec = knuffel::parse("", text).unwrap(); assert_eq!(nodes.len(), 1); nodes.remove(0) } fn parse_err+fmt::Debug>(text: &str) -> String { let err = knuffel::parse::>("", text).unwrap_err(); err.related().unwrap() .map(|e| e.to_string()).collect::>() .join("\n") } #[test] fn parse_unit() { assert_eq!(parse::(r#"node"#), Unit); assert_eq!(parse_err::(r#"node something="world""#), "unexpected property `something`"); } #[test] fn parse_arg() { assert_eq!(parse::(r#"node 123"#), Arg(123)); assert_eq!(parse_err::(r#"node something="world""#), "additional argument is required"); } #[test] fn parse_extra() { assert_eq!(parse::(r#"node "123""#), Extra(Some("123".into()), 0)); assert_eq!(parse::(r#"node"#), Extra(None, 0)); assert_eq!(parse_err::(r#"node "123" 456"#), "unexpected argument"); } #[test] fn parse_opt() { assert_eq!(parse::(r#"node 123"#), Opt(Some(Arg(123)))); assert_eq!(parse::(r#"node"#), Opt(None)); assert_eq!(parse_err::(r#"node something="world""#), "additional argument is required"); } #[test] fn parse_enum() { assert_eq!(parse::(r#"unit"#), Enum::Unit); assert_eq!(parse::(r#"arg 123"#), Enum::Arg(123)); assert_eq!(parse::(r#"opt 123"#), Enum::Opt(Some(Arg(123)))); assert_eq!(parse::(r#"opt"#), Enum::Opt(None)); assert_eq!(parse::(r#"extra"#), Enum::Extra(None, 0)); assert_eq!(parse_err::(r#"unit something="world""#), "unexpected property `something`"); assert_eq!(parse_err::(r#"other something="world""#), "expected `unit`, `arg`, or one of 2 others"); assert_eq!(parse_err::(r#"extra "hello" "world""#), "unexpected argument"); } knuffel-derive-3.2.0/tests/types.rs000064400000000000000000000016641046102023000154170ustar 00000000000000use std::path::PathBuf; use knuffel::{span::Span}; use knuffel::traits::DecodeChildren; #[derive(knuffel_derive::Decode, Debug, PartialEq)] struct Scalars { #[knuffel(child, unwrap(argument))] str: String, #[knuffel(child, unwrap(argument))] u64: u64, #[knuffel(child, unwrap(argument))] f64: f64, #[knuffel(child, unwrap(argument))] path: PathBuf, #[knuffel(child, unwrap(argument))] boolean: bool, } fn parse>(text: &str) -> T { knuffel::parse("", text).unwrap() } #[test] fn parse_enum() { assert_eq!( parse::(r#" str "hello" u64 1234 f64 16.125e+1 path "/hello/world" boolean true "#), Scalars { str: "hello".into(), u64: 1234, f64: 161.25, path: PathBuf::from("/hello/world"), boolean: true, }); }