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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use crate::wsdl::{SimpleType, Type, Wsdl, parse};
use case::CaseExt;
use proc_macro2::{Ident, Literal, Span, TokenStream};
use std::{fs::File, io::Write};
pub trait ToElements {
fn to_elements(&self) -> Vec<xmltree::Element>;
}
pub trait FromElement {
fn from_element(element: &xmltree::Element) -> Result<Self, crate::Error>
where
Self: Sized;
}
impl<T: ToElements> ToElements for Option<T> {
fn to_elements(&self) -> Vec<xmltree::Element> {
match self {
Some(e) => e.to_elements(),
None => vec![],
}
}
}
/*impl<T: ToElements> for Vec<T> {
fn to_elements(&self) -> Vec<xmltree::Element> {
match self {
Some(e) => e.to_elements(),
None => vec![],
}
}
}*/
#[derive(Debug)]
pub enum GenError {
Io(std::io::Error),
}
impl From<std::io::Error> for GenError {
fn from(e: std::io::Error) -> Self {
GenError::Io(e)
}
}
pub fn gen_write(path: &str, out: &str) {
let out_path = format!("{}/example.rs", out);
let v = std::fs::read(path).unwrap();
let mut output = File::create(out_path).unwrap();
let wsdl = parse(&v[..]).unwrap();
let generated = generate(&wsdl).unwrap();
output.write_all(generated.as_bytes()).unwrap();
output.flush().unwrap();
}
pub fn generate(wsdl: &Wsdl) -> Result<String, GenError> {
let target_namespace = Literal::string(&wsdl.target_namespace);
let operations = wsdl.operations.iter().map(|(name, operation)| {
let op_name = Ident::new(&name.to_snake(), Span::call_site());
let input_name = Ident::new(&operation.input.as_ref().unwrap().to_snake(), Span::call_site());
let input_type = Ident::new(&operation.input.as_ref().unwrap().to_camel(), Span::call_site());
let full_input_type = quote!{ messages::#input_type };
let op_str = Literal::string(name);
match (operation.output.as_ref(), operation.faults.as_ref()) {
(None, None) => {
quote! {
pub async fn #op_name(&self, #input_name: #full_input_type) -> Result<(), soafe::Error> {
soafe::http::one_way(&self.client, &self.base_url, #target_namespace, #op_str, &#input_name).await
}
}
},
(None, Some(_)) => quote!{},
(Some(out), None) => {
let output_type = Ident::new(out, Span::call_site());
let full_output_type = quote!{ messages::#output_type };
quote! {
pub async fn #op_name(&self, #input_name: #full_input_type) -> Result<Result<#full_output_type, ()>, soafe::Error> {
soafe::http::request_response(&self.client, &self.base_url, #target_namespace, #op_str, &#input_name).await
}
}
},
(Some(out), Some(_)) => {
let output_type = Ident::new(out, Span::call_site());
let full_output_type = quote!{ messages::#output_type };
let error_type = Ident::new(&format!("{}Error", name.to_camel()), Span::call_site());
let full_error_type = quote!{ messages::#error_type };
quote! {
pub async fn #op_name(&self, #input_name: #full_input_type)
-> Result<Result<#full_output_type, #full_error_type>, soafe::Error> {
unimplemented!()
/*let req = hyper::http::request::Builder::new()
.method("POST")
.header("Content-Type", "text/xml-SOAP")
.header("MessageType", "Call")
.body(#input_name.as_xml())?;
let response: hyper::http::Response<String> = self.client.request(req).await?;
let body = response.body().await?;
if let Ok(out) = #out_name::from_xml(body) {
Ok(Ok(out))
} else {
Ok(#err_name::from_xml(body)?)
}
*/
}
}
},
}
}).collect::<Vec<_>>();
let types = wsdl
.types
.iter()
.map(|(name, t)| {
if let Type::Complex(c) = t {
let type_name = Ident::new(&name.to_camel(), Span::call_site());
let fields = c
.fields
.iter()
.map(|(field_name, (attributes, field_type))| {
let fname = Ident::new(&field_name.to_snake(), Span::call_site());
let ft = match field_type {
SimpleType::Boolean => quote!{ bool }, //Ident::new("bool", Span::call_site()),
SimpleType::String => quote!{ String },//Ident::new("String", Span::call_site()),
SimpleType::Float => quote!{ f64 },//Ident::new("f64", Span::call_site()),
SimpleType::Int => quote!{ i64 },//Ident::new("i64", Span::call_site()),
SimpleType::DateTime => quote!{ DateTime<Utc> },//Ident::new("DateTime<Utc>", Span::call_site()),
SimpleType::Complex(s) => {
let ty = Ident::new(&s.to_camel(), Span::call_site());
quote!{ #ty }
},
};
let ft = match (attributes.min_occurs.as_ref(), attributes.max_occurs.as_ref()) {
(Some(_), Some(_)) => quote! { Vec<#ft> },
_ => quote! { #ft }
};
let ft = if attributes.nillable {
quote! { Option<#ft> }
} else {
ft
};
quote! {
pub #fname: #ft,
}
})
.collect::<Vec<_>>();
let fields_serialize_impl = c
.fields
.iter()
.map(|(field_name, (attributes, field_type))| {
let fname = Ident::new(&field_name.to_snake(), Span::call_site());
//FIXME: handle more complex types
/*let ft = match field_type {
SimpleType::Boolean => Ident::new("bool", Span::call_site()),
SimpleType::String => Ident::new("String", Span::call_site()),
SimpleType::Float => Ident::new("f64", Span::call_site()),
SimpleType::Int => Ident::new("i64", Span::call_site()),
SimpleType::DateTime => Ident::new("String", Span::call_site()),
SimpleType::Complex(s) => Ident::new(&s, Span::call_site()),
};*/
let ftype = Literal::string(field_name);
let prefix = quote! { xmltree::Element::node(#ftype) };
match (attributes.min_occurs.as_ref(), attributes.max_occurs.as_ref()) {
(Some(_), Some(_)) => if attributes.nillable {
quote! {
self.#fname.as_ref().map(|v| v.iter().map(|i| {
#prefix.with_children(i.to_elements())
}).collect()).unwrap_or_else(Vec::new)
}
} else {
quote! {
self.#fname.iter().map(|i| {
#prefix.with_children(i.to_elements())
}).collect()
}
},
_ => {
match field_type {
SimpleType::Complex(_s) => quote!{ vec![#prefix.with_children(self.#fname.to_elements())]},
_ => quote!{ vec![#prefix.with_text(self.#fname.to_string())] },
}
}
}
})
.collect::<Vec<_>>();
let serialize_impl = if fields_serialize_impl.is_empty() {
quote! {
impl soafe::generate::ToElements for #type_name {
fn to_elements(&self) -> Vec<xmltree::Element> {
vec![]
}
}
}
}else {
quote! {
impl soafe::generate::ToElements for #type_name {
fn to_elements(&self) -> Vec<xmltree::Element> {
vec![#(#fields_serialize_impl),*].drain(..).flatten().collect()
}
}
}
};
let fields_deserialize_impl = c
.fields
.iter()
.map(|(field_name, (attributes, field_type))| {
let fname = Ident::new(&field_name.to_snake(), Span::call_site());
let ftype = Literal::string(field_name);
let prefix = quote!{ #fname: element.get_at_path(&[#ftype]) };
match field_type {
SimpleType::Boolean => {
let ft = quote!{ #prefix.and_then(|e| e.as_boolean()) };
if attributes.nillable {
quote!{ #ft.ok(),}
} else {
quote!{ #ft?,}
}
},
SimpleType::String => {
let ft = quote!{ #prefix.and_then(|e| e.get_text().map(|s| s.to_string())
.ok_or(soafe::rpser::xml::Error::Empty)
) };
if attributes.nillable {
quote!{ #ft.ok(),}
} else {
quote!{ #ft?,}
}
},
SimpleType::Float => {
let ft = quote!{ #prefix.map_err(soafe::Error::from).and_then(|e| e.get_text()
.ok_or(soafe::rpser::xml::Error::Empty)
.map_err(soafe::Error::from)
.and_then(|s| s.parse().map_err(soafe::Error::from))) };
if attributes.nillable {
quote!{ #ft.ok(),}
} else {
quote!{ #ft?,}
}
},
SimpleType::Int => {
let ft = quote!{ #prefix.and_then(|e| e.as_long()) };
if attributes.nillable {
quote!{ #ft.ok(),}
} else {
quote!{ #ft?,}
}
},
SimpleType::DateTime => {
let ft = quote!{
#prefix.and_then(|e| e.get_text()
.ok_or(soafe::rpser::xml::Error::Empty)
).map_err(soafe::Error::from)
.and_then(|s|
s.parse::<soafe::internal::chrono::DateTime<soafe::internal::chrono::offset::Utc>>().map_err(soafe::Error::from))
};
if attributes.nillable {
quote!{ #ft.ok(),}
} else {
quote!{ #ft?,}
}
},
SimpleType::Complex(s) => {
let complex_type = Ident::new(&s.to_camel(), Span::call_site());
match (attributes.min_occurs.as_ref(), attributes.max_occurs.as_ref()) {
(Some(_), Some(_)) => {
let ft = quote! {
{
let mut v = vec![];
for elem in element.children.iter()
.filter_map(|c| c.as_element()) {
v.push(#complex_type::from_element(&elem)?);
}
v
},
};
if attributes.nillable {
quote!{ #fname: Some(#ft) }
} else {
quote!{ #fname: #ft }
}
},
_ => {
let ft = quote!{ #prefix.map_err(soafe::Error::from).and_then(|e| #complex_type::from_element(&e).map_err(soafe::Error::from)) };
if attributes.nillable {
quote!{ #ft.ok(),}
} else {
quote!{ #ft?,}
}
}
}
},
}
})
.collect::<Vec<_>>();
let deserialize_impl = if fields_deserialize_impl.is_empty() {
quote! {
impl soafe::generate::FromElement for #type_name {
fn from_element(_element: &xmltree::Element) -> Result<Self, soafe::Error> {
Ok(#type_name {
})
}
}
}
} else {
quote! {
impl soafe::generate::FromElement for #type_name {
fn from_element(element: &xmltree::Element) -> Result<Self, soafe::Error> {
Ok(#type_name {
#(#fields_deserialize_impl)*
})
}
}
}
};
quote! {
#[derive(Clone, Debug, Default)]
pub struct #type_name {
#(#fields)*
}
#serialize_impl
#deserialize_impl
}
} else {
panic!();
}
})
.collect::<Vec<_>>();
let messages = wsdl
.messages
.iter()
.map(|(message_name, message)| {
let mname = Ident::new(message_name, Span::call_site());
let iname = Ident::new(&message.part_element, Span::call_site());
quote! {
#[derive(Clone, Debug, Default)]
pub struct #mname(pub types::#iname);
impl soafe::generate::ToElements for #mname {
fn to_elements(&self) -> Vec<xmltree::Element> {
self.0.to_elements()
}
}
impl soafe::generate::FromElement for #mname {
fn from_element(element: &xmltree::Element) -> Result<Self, soafe::Error> {
types::#iname::from_element(element).map(#mname)
}
}
}
})
.collect::<Vec<_>>();
let service_name = Ident::new(&wsdl.name, Span::call_site());
let toks = quote! {
pub mod types {
use soafe::internal::xmltree;
use soafe::rpser::xml::*;
#[allow(unused_imports)]
use soafe::internal::chrono::{DateTime, offset::Utc};
#(#types)*
}
pub mod messages {
use soafe::internal::xmltree;
use super::types;
#(#messages)*
}
pub struct #service_name {
pub base_url: String,
pub client: soafe::internal::reqwest::Client,
}
#[allow(dead_code)]
impl #service_name {
pub fn new(base_url: String) -> Self {
Self::with_client(base_url, soafe::internal::reqwest::Client::new())
}
pub fn with_client(base_url: String, client: soafe::internal::reqwest::Client) -> Self {
#service_name {
base_url,
client,
}
}
#(#operations)*
}
};
let operation_faults = wsdl
.operations
.iter()
.filter(|(_, op)| op.faults.is_some())
.map(|(name, operation)| {
let op_error = Ident::new(&format!("{}Error", name), Span::call_site());
let faults = operation
.faults
.as_ref()
.unwrap()
.iter()
.map(|fault| {
let fault_name = Ident::new(fault, Span::call_site());
quote! {
#fault_name(#fault_name),
}
})
.collect::<Vec<_>>();
quote! {
#[derive(Clone, Debug, Default)]
pub enum #op_error {
#(#faults)*
}
}
})
.collect::<Vec<_>>();
let mut stream: TokenStream = toks;
stream.extend(operation_faults);
Ok(stream.to_string())
}
#[cfg(test)]
mod tests {
use super::*;
const WIKIPEDIA_WSDL: &[u8] = include_bytes!("../assets/wikipedia-example.wsdl");
const EXAMPLE_WSDL: &[u8] = include_bytes!("../assets/example.wsdl");
#[test]
fn example() {
let wsdl = parse(EXAMPLE_WSDL).unwrap();
println!("wsdl: {:?}", wsdl);
let res = generate(&wsdl).unwrap();
println!("generated:\n{}", res);
panic!();
}
}