jsonforge 0.1.0

A Rust procedural macro for generating JSON schema validators from Rust types
Documentation
use proc_macro2::TokenStream;
use quote::quote;
use syn::{Ident, Visibility};

use crate::schema::types::{SchemaType, TopLevel};

use super::types::struct_def;
use super::util::make_ident;
use super::util::to_screaming_snake;

/// Generate the non-embedded output:
/// - Struct definition(s) with owned types.
/// - A `const <NAME>_JSON: &str = include_str!(...)` baked from the source file.
pub fn generate(
    vis: &Visibility,
    data_vis: &Visibility,
    name: &Ident,
    top: &TopLevel,
    manifest_relative_path: &str,
) -> TokenStream {
    let const_name = make_ident(&format!("{}_JSON", to_screaming_snake(&name.to_string())));

    let struct_ts = match top {
        TopLevel::Map { entry } => struct_def(vis, name, entry, false),
        TopLevel::Array { entry, .. } => match entry {
            SchemaType::Struct(schema) => struct_def(vis, name, schema, false),
            _ => quote! {},
        },
        TopLevel::Struct(schema) => struct_def(vis, name, schema, false),
    };

    // include_str! path is resolved relative to CARGO_MANIFEST_DIR at compile time.
    let path_lit = manifest_relative_path;

    quote! {
        #struct_ts

        #data_vis const #const_name: &'static str = ::core::include_str!(
            ::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), "/", #path_lit)
        );
    }
}