fix(api): first big step towards syntex

Even though there is a bug that caues {} to be used in stead of
(),
when exanding macros, which causes syntax errors that we have to
workaround, it's not a real issue.

What's happening additionally is missing hyper macros, which
now have to be expanded manually. Shouldn't be a problem,
pretty-printing when compiling is made for just that ;).

No, it's sad that `include!()` works so badly, it makes
using serde so difficult ... it's no fun i must say.

Just for stable ... I am not sure if it is worth it."
This commit is contained in:
Sebastian Thiel
2015-06-18 22:51:17 +02:00
parent 267868cea3
commit b0a41c4e78
14 changed files with 392 additions and 1294 deletions

View File

@@ -0,0 +1,17 @@
<%namespace name="util" file="../lib/util.mako"/>\
extern crate syntex;
extern crate serde_codegen;
use std::env;
use std::path::Path;
pub fn main() {
let out_dir = env::var_os("OUT_DIR").unwrap();
let src = Path::new("src/lib.rs.in");
let dst = Path::new(&out_dir).join("lib.rs");
let mut registry = syntex::Registry::new();
serde_codegen::register(&mut registry);
registry.expand("${util.crate_name()}", &src, &dst).unwrap();
}

134
src/mako/api/lib.rs.in.mako Normal file
View File

@@ -0,0 +1,134 @@
<%namespace name="lib" file="lib/lib.mako"/>\
<%namespace name="util" file="../lib/util.mako"/>\
<%namespace name="rbuild" file="lib/rbuild.mako"/>\
<%namespace name="mbuild" file="lib/mbuild.mako"/>\
<%namespace name="schema" file="lib/schema.mako"/>\
<%
from util import (new_context, rust_comment, rust_doc_comment, rust_module_doc_comment,
rb_type, hub_type, mangle_ident, hub_type_params_s, hub_type_bounds,
rb_type_params_s, find_fattest_resource, HUB_TYPE_PARAMETERS, METHODS_RESOURCE,
UNUSED_TYPE_MARKER, schema_markers)
c = new_context(schemas, resources, context.get('methods'))
hub_type = hub_type(c.schemas, util.canonical_name())
ht_params = hub_type_params_s()
default_user_agent = "google-api-rust-client/" + cargo.build_version
%>\
<%block filter="rust_comment">\
<%util:gen_info source="${self.uri}" />\
</%block>
#[macro_use]
extern crate hyper;
extern crate serde;
extern crate yup_oauth2 as oauth2;
extern crate mime;
extern crate url;
mod cmn;
use std::collections::HashMap;
use std::cell::RefCell;
use std::borrow::BorrowMut;
use std::default::Default;
use std::collections::BTreeMap;
use serde::json;
use std::io;
use std::fs;
use std::thread::sleep_ms;
pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part,
ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder,
Resource, ErrorResponse, remove_json_null_values};
// ##############
// UTILITIES ###
// ############
${lib.scope_enum()}
// ########
// HUB ###
// ######
/// Central instance to access all ${hub_type} related resource activities
///
/// # Examples
///
/// Instantiate a new hub
///
<%block filter="rust_doc_comment">\
${lib.hub_usage_example(c)}\
</%block>
pub struct ${hub_type}${ht_params} {
client: RefCell<C>,
auth: RefCell<A>,
_user_agent: String,
}
impl<'a, ${', '.join(HUB_TYPE_PARAMETERS)}> Hub for ${hub_type}${ht_params} {}
impl<'a, ${', '.join(HUB_TYPE_PARAMETERS)}> ${hub_type}${ht_params}
where ${', '.join(hub_type_bounds())} {
pub fn new(client: C, authenticator: A) -> ${hub_type}${ht_params} {
${hub_type} {
client: RefCell::new(client),
auth: RefCell::new(authenticator),
_user_agent: "${default_user_agent}".to_string(),
}
}
% for resource in sorted(c.rta_map.keys()):
pub fn ${mangle_ident(resource)}(&'a self) -> ${rb_type(resource)}${rb_type_params_s(resource, c)} {
${rb_type(resource)} { hub: &self }
}
% endfor
/// Set the user-agent header field to use in all requests to the server.
/// It defaults to `${default_user_agent}`.
///
/// Returns the previously set user-agent.
pub fn user_agent(&mut self, agent_name: String) -> String {
let prev = self._user_agent.clone();
self._user_agent = agent_name;
prev
}
}
% if c.schemas:
// ############
// SCHEMAS ###
// ##########
% for s in c.schemas.values():
% if UNUSED_TYPE_MARKER not in schema_markers(s, c, transitive=True):
${schema.new(s, c)}
% endif
% endfor
% endif
// ###################
// MethodBuilders ###
// #################
% for resource in c.rta_map:
${rbuild.new(resource, c)}
% endfor
// ###################
// CallBuilders ###
// #################
% for resource, methods in c.rta_map.iteritems():
% for method in methods:
${mbuild.new(resource, method, c)}
% endfor ## method in methods
% endfor ## resource, methods

View File

@@ -1,19 +1,9 @@
<%namespace name="lib" file="lib/lib.mako"/>\
<%namespace name="util" file="../lib/util.mako"/>\
<%namespace name="rbuild" file="lib/rbuild.mako"/>\
<%namespace name="mbuild" file="lib/mbuild.mako"/>\
<%namespace name="schema" file="lib/schema.mako"/>\
<%
from util import (new_context, rust_comment, rust_doc_comment, rust_module_doc_comment,
rb_type, hub_type, mangle_ident, hub_type_params_s, hub_type_bounds,
rb_type_params_s, find_fattest_resource, HUB_TYPE_PARAMETERS, METHODS_RESOURCE,
UNUSED_TYPE_MARKER, schema_markers)
from util import (new_context, rust_comment, rust_module_doc_comment)
c = new_context(schemas, resources, context.get('methods'))
hub_type = hub_type(c.schemas, util.canonical_name())
ht_params = hub_type_params_s()
default_user_agent = "google-api-rust-client/" + cargo.build_version
%>\
<%block filter="rust_comment">\
<%util:gen_info source="${self.uri}" />\
@@ -22,124 +12,11 @@
<%block filter="rust_module_doc_comment">\
${lib.docs(c)}
</%block>
// Unused attributes happen thanks to defined, but unused structures
// We don't warn about this, as depending on the API, some data structures or facilities are never used.
// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any
// unused imports in fully featured APIs. Same with unused_mut ... .
#![allow(unused_imports, unused_mut, dead_code)]
// Required for serde annotations
#![feature(custom_derive, custom_attribute, plugin, slice_patterns)]
#![plugin(serde_macros)]
#[macro_use]
extern crate hyper;
extern crate serde;
extern crate yup_oauth2 as oauth2;
extern crate mime;
extern crate url;
extern crate json_tools;
mod cmn;
use std::collections::HashMap;
use std::cell::RefCell;
use std::borrow::BorrowMut;
use std::default::Default;
use std::collections::BTreeMap;
use serde::json;
use std::io;
use std::fs;
use std::thread::sleep_ms;
pub use cmn::{MultiPartReader, ToParts, MethodInfo, Result, Error, CallBuilder, Hub, ReadSeek, Part, ResponseResult, RequestValue, NestedType, Delegate, DefaultDelegate, MethodsBuilder, Resource, ErrorResponse};
// ##############
// UTILITIES ###
// ############
${lib.scope_enum()}
// ########
// HUB ###
// ######
/// Central instance to access all ${hub_type} related resource activities
///
/// # Examples
///
/// Instantiate a new hub
///
<%block filter="rust_doc_comment">\
${lib.hub_usage_example(c)}\
</%block>
pub struct ${hub_type}${ht_params} {
client: RefCell<C>,
auth: RefCell<A>,
_user_agent: String,
}
impl<'a, ${', '.join(HUB_TYPE_PARAMETERS)}> Hub for ${hub_type}${ht_params} {}
impl<'a, ${', '.join(HUB_TYPE_PARAMETERS)}> ${hub_type}${ht_params}
where ${', '.join(hub_type_bounds())} {
pub fn new(client: C, authenticator: A) -> ${hub_type}${ht_params} {
${hub_type} {
client: RefCell::new(client),
auth: RefCell::new(authenticator),
_user_agent: "${default_user_agent}".to_string(),
}
}
% for resource in sorted(c.rta_map.keys()):
pub fn ${mangle_ident(resource)}(&'a self) -> ${rb_type(resource)}${rb_type_params_s(resource, c)} {
${rb_type(resource)} { hub: &self }
}
% endfor
/// Set the user-agent header field to use in all requests to the server.
/// It defaults to `${default_user_agent}`.
///
/// Returns the previously set user-agent.
pub fn user_agent(&mut self, agent_name: String) -> String {
let prev = self._user_agent.clone();
self._user_agent = agent_name;
prev
}
}
% if c.schemas:
// ############
// SCHEMAS ###
// ##########
% for s in c.schemas.values():
% if UNUSED_TYPE_MARKER not in schema_markers(s, c, transitive=True):
${schema.new(s, c)}
% endif
% endfor
% endif
// ###################
// MethodBuilders ###
// #################
% for resource in c.rta_map:
${rbuild.new(resource, c)}
% endfor
// ###################
// CallBuilders ###
// #################
% for resource, methods in c.rta_map.iteritems():
% for method in methods:
${mbuild.new(resource, method, c)}
% endfor ## method in methods
% endfor ## resource, methods
include!(concat!(env!("OUT_DIR"), "/lib.rs"));

View File

@@ -483,9 +483,6 @@ match result {
% if URL_ENCODE in special_cases:
use url::percent_encoding::{percent_encode, FORM_URLENCODED_ENCODE_SET};
% endif
% if request_value:
use json_tools::{TokenReader, Lexer, BufferType, TokenType, FilterTypedKeyValuePairs, IteratorExt};
% endif
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, UserAgent, Location};
let mut dd = DefaultDelegate;
@@ -665,13 +662,11 @@ else {
let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default());
let mut request_value_reader =
{
let json_cache = json::to_string(&self.${property(REQUEST_VALUE_PROPERTY_NAME)}).unwrap();
let mut mem_dst = io::Cursor::new(Vec::with_capacity(json_cache.len()));
io::copy(&mut Lexer::new(json_cache.bytes(), BufferType::Span)
.filter_key_value_by_type(TokenType::Null)
.reader(Some(&json_cache)), &mut mem_dst).unwrap();
mem_dst.seek(io::SeekFrom::Start(0)).unwrap();
mem_dst
let mut value = json::value::to_value(&self.${property(REQUEST_VALUE_PROPERTY_NAME)});
remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();