1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
use anyhow::{anyhow, Context};
use darling::FromMeta;
use odata_client_codegen::{generate_module, ConstructConfig};
use proc_macro2::{Span, TokenStream};
use quote::quote;
use reqwest::Url;
use std::{fmt::Display, fs};
use syn::parse_macro_input;

// TODO: support passing in `odata_client_codegen::ConstructConfig` options
// TODO: support passing in `EntityModelFilter`

/// Procedural macro to generate OData entity model types within a module.
///
/// ---
///
/// > **N.B** The value of generating code for an API substantially lies in the access to
/// autocomplete functionality, and/or the ability to browse the API's endpoints & types. Currently,
/// rust-analyzer's support for these features with code from procedural macros is limited.
///
/// > A more productive development experience may be had by writing generated code to a file,
/// instead of using this proc macro attribute. This can be done with the
/// [`write_module_build_artifact`](odata_client_codegen::write_module_build_artifact) function.
/// This function additionally supports customisation of the generated code to some extent.
///
/// ---
///
/// The proc macro attribute should be placed on an empty module:
///
/// ```ignore
/// #[odata_client(service_url = "https://example.ru/odata_api/")]
/// mod my_entity_model {}
/// ```
///
/// (The `mod my_entity_model;` syntax, with a semicolon, can be used in nightly with
/// `#![feature(proc_macro_hygiene)]`.)
///
/// With just the `service_url` argument, the OData API's `$metadata` document will be fetch during
/// build. This document can instead be set from a local file using the `metadata_filepath`
/// argument, or inline metadata XML can be set using the `metadata_xml` argument. In either case,
/// the `service_url` argument is still required:
///
/// ```ignore
/// #[odata_client(
///     service_url = "https://example.ru/odata_api/",
///     metadata_filepath = "metadata.xml"
/// )]
/// mod entity_model_document_file {}
///
/// #[odata_client(
///     service_url = "https://example.ru/odata_api/",
///     metadata_xml = r#"
///         <?xml version="1.0" encoding="utf-8"?>
///         <edmx:Edmx Version="4.0"
///             xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx">
///             <edmx:DataServices>
///                 <Schema Namespace="My.Entity.Model"
///                     xmlns="http://docs.oasis-open.org/odata/ns/edm">
///                     [...]
///                 </Schema>
///             </edmx:DataServices>
///         </edmx:Edmx>
///     "#
/// )]
/// mod entity_model_inline_document {}
/// ```
#[proc_macro_attribute]
pub fn odata_client(
    attr: proc_macro::TokenStream,
    item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let item_mod: syn::ItemMod = parse_macro_input!(item);
    let attr_args: syn::AttributeArgs = parse_macro_input!(attr);

    let EntityModelSource {
        service_url,
        metadata_filepath,
        metadata_xml,
    } = match EntityModelSource::from_list(&attr_args) {
        Ok(m) => m,
        Err(e) => {
            return proc_macro::TokenStream::from(e.write_errors());
        }
    };

    // Allow target module to be writen as an empty inline module, as proc macro attributes on
    // non-inline modules is unstable: https://github.com/rust-lang/rust/issues/54727
    if let Some((_brace, items)) = item_mod.content {
        if !items.is_empty() {
            return to_compile_error_stream(
                "OData service target module should not contain any items (e.g. `mod Foo {}`), or \
                    should be declared without a body (e.g. `mod Foo;`)",
            );
        }
    }

    let mod_ident = item_mod.ident;

    let module_gen = match (metadata_filepath, metadata_xml) {
        (None, None) => derive_from_service_endpoint(service_url),
        (Some(filepath), None) => derive_from_metadata_xml_file(&filepath, service_url),
        (None, Some(xml_lit)) => {
            generate_module(&xml_lit, service_url, ConstructConfig::default(), None)
        }
        (Some(_), Some(_)) => {
            return syn::Error::new(
                Span::call_site(),
                "Cannot specify both `metadata_filepath` and `metadata_xml`",
            )
            .to_compile_error()
            .into();
        }
    };

    match module_gen {
        // TODO: support visibility modifiers on module declaration
        Ok(module) => quote! {
            mod #mod_ident {
                #module
            }
        }
        .into(),
        Err(e) => to_compile_error_stream(e),
    }
}

fn to_compile_error_stream(msg: impl Display) -> proc_macro::TokenStream {
    syn::Error::new(Span::call_site(), msg)
        .to_compile_error()
        .into()
}

#[derive(FromMeta)]
struct EntityModelSource {
    service_url: String,
    #[darling(default)]
    metadata_filepath: Option<String>,
    #[darling(default)]
    metadata_xml: Option<String>,
}

fn derive_from_metadata_xml_file(
    filepath: &str,
    endpoint_url: String,
) -> Result<TokenStream, anyhow::Error> {
    let xml_str = fs::read_to_string(filepath)
        .with_context(|| format!("Unable to read file at {}", filepath))?;

    generate_module(&xml_str, endpoint_url, ConstructConfig::default(), None)
}

fn derive_from_service_endpoint(endpoint_url: String) -> Result<TokenStream, anyhow::Error> {
    let metadata_document_url = get_metadata_document_url(&endpoint_url)?;

    let resp = reqwest::blocking::get(metadata_document_url.clone()).with_context(|| {
        format!(
            "Failed to fetch metadata document from '{}'",
            metadata_document_url
        )
    })?;

    let body = resp.text()?;

    generate_module(&body, endpoint_url, ConstructConfig::default(), None)
}

fn get_metadata_document_url(service_endpoint: &str) -> Result<Url, anyhow::Error> {
    let service_endpoint = Url::parse(service_endpoint)
        .with_context(|| format!("Invalid URL '{}'", service_endpoint))?;

    match service_endpoint.scheme() {
        "http" | "https" => {}
        scheme => return Err(anyhow!("Invalid URL scheme '{}'", scheme)),
    }

    if let Some(q) = service_endpoint.query() {
        if !q.is_empty() {
            return Err(anyhow!("Endpoint URL should not have query or fragment"));
        }
    }

    if let Some(f) = service_endpoint.fragment() {
        if !f.is_empty() {
            return Err(anyhow!("Endpoint URL should not have query or fragment"));
        }
    }

    let metadata_url = {
        let mut url = service_endpoint;
        url.path_segments_mut().unwrap().push("$metadata");
        url
    };

    Ok(metadata_url)
}