moxy-derive 0.0.4

derive macros for moxy crate
Documentation
use quote::quote;

use super::{DisplayOptions, DisplayOutput, Segment, SegmentKind, access};

pub struct MapStyleSyntax {
    pub pretty: bool,
}

impl MapStyleSyntax {
    pub fn render(&self, opts: &DisplayOptions) -> syn::Result<DisplayOutput> {
        let mut out = DisplayOutput::new();

        out.push(Segment::literal(
            SegmentKind::OpenDelim,
            if self.pretty { "{\n" } else { "{ " },
        ));

        for (i, f) in opts.fields.iter().enumerate() {
            let a = access(f, opts.use_self);

            if self.pretty {
                out.push(Segment::literal(SegmentKind::Assign, "    "));
            }

            out.push(Segment::literal(SegmentKind::FieldName, &f.display_name()?));
            out.push(Segment::literal(SegmentKind::Assign, ": "));
            out.push(Segment::placeholder(SegmentKind::Value, quote! { #a }));

            if self.pretty {
                out.push(Segment::literal(SegmentKind::Separator, ",\n"));
            } else if i + 1 < opts.fields.len() {
                out.push(Segment::literal(SegmentKind::Separator, ", "));
            }
        }

        out.push(Segment::literal(
            SegmentKind::CloseDelim,
            if self.pretty { "}" } else { " }" },
        ));

        Ok(out)
    }
}