echo_library/common/
boilerplate.rs

1
2pub const COMMON: &str = r#"#![allow(unused_imports)]
3use paste::paste;
4use super::*;
5#[derive(Debug, Flow)]
6pub struct WorkflowGraph {
7    edges: Vec<(usize, usize)>,
8    nodes: Vec<Box<dyn Execute>>,
9}
10
11impl WorkflowGraph {
12    pub fn new(size: usize) -> Self {
13        WorkflowGraph {
14            nodes: Vec::with_capacity(size),
15            edges: Vec::new(),
16        }
17    }
18}
19
20#[macro_export]
21macro_rules! impl_execute_trait {
22    ($ ($struct : ty), *) => {
23
24            paste!{
25                $( impl Execute for $struct {
26                    fn execute(&mut self) -> Result<(),String>{
27        self.run()
28    }
29
30    fn get_task_output(&self) -> Value {
31        self.output().clone().into()
32    }
33
34    fn set_output_to_task(&mut self, input: Value) {
35        self.setter(input)
36    }
37                }
38            )*
39        }
40    };
41}
42
43#[allow(dead_code, unused)]
44pub fn join_hashmap<T: PartialEq + std::hash::Hash + Eq + Clone, U: Clone, V: Clone>(
45    first: HashMap<T, U>,
46    second: HashMap<T, V>,
47) -> HashMap<T, (U, V)> {
48    let mut data: HashMap<T, (U, V)> = HashMap::new();
49    for (key, value) in first {
50        for (s_key, s_value) in &second {
51            if key.clone() == *s_key {
52                data.insert(key.clone(), (value.clone(), s_value.clone()));
53            }
54        }
55    }
56    data
57}
58
59#[no_mangle]
60pub unsafe extern "C" fn free_memory(ptr: *mut u8, size: u32, alignment: u32) {
61    let layout = Layout::from_size_align_unchecked(size as usize, alignment as usize);
62    alloc::alloc::dealloc(ptr, layout);
63}
64
65#[link(wasm_import_module = "host")]
66extern "C" {
67    pub fn set_output(ptr: i32, size: i32);
68}
69#[derive(Serialize, Deserialize, Debug, Clone)]
70pub struct Output {
71    pub result: Value,
72}
73
74#[no_mangle]
75pub unsafe extern "C" fn memory_alloc(size: u32, alignment: u32) -> *mut u8 {
76    let layout = Layout::from_size_align_unchecked(size as usize, alignment as usize);
77    alloc::alloc::alloc(layout)
78}
79
80"#;
81
82pub const LIB: &str =  r#"#![allow(unused_imports)]
83#![allow(unused_macros)]
84#![allow(unused_variables)]
85#![allow(dead_code)]
86#![allow(forgetting_copy_types)]
87#![allow(unused_mut)]
88#![allow(unused_must_use)]
89
90mod common;
91mod macros;
92mod traits;
93mod types;
94
95use common::*;
96use derive_enum_from_into::{EnumFrom, EnumTryInto};
97use dyn_clone::{clone_trait_object, DynClone};
98use macros::*;
99use openwhisk_rust::*;
100use paste::*;
101use serde::{Deserialize, Serialize};
102use serde_json::to_value;
103use serde_json::Value;
104use std::collections::HashMap;
105use std::convert::TryInto;
106use std::fmt::Debug;
107use traits::*;
108use types::*;
109use workflow_macro::Flow;
110extern crate alloc;
111use codec::{Decode, Encode};
112use core::alloc::Layout;
113
114#[no_mangle]
115pub fn _start(ptr: *mut u8, length: i32) {
116    let result: Value;
117    unsafe {
118        let mut vect = Vec::new();
119        for i in 1..=length {
120            if let Some(val_back) = ptr.as_ref() {
121                vect.push(val_back.clone());
122            }
123            *ptr = *ptr.add(i as usize);
124        }
125        result = serde_json::from_slice(&vect).unwrap();
126    }
127
128    let res = main(result);
129    let output = Output {
130        result: serde_json::to_value(res).unwrap(),
131    };
132    let serialized = serde_json::to_vec(&output).unwrap();
133    let size = serialized.len() as i32;
134    let ptr = serialized.as_ptr();
135    std::mem::forget(ptr);
136    unsafe {
137        set_output(ptr as i32, size);
138    }
139}
140
141"#;
142pub const TRAIT: &str =  r#"
143
144use super::*;
145
146pub trait Execute : Debug + DynClone  {
147    fn execute(&mut self)-> Result<(),String>;
148    fn get_task_output(&self)->Value;
149    fn set_output_to_task(&mut self, inp: Value);
150}
151
152clone_trait_object!(Execute);
153
154"#;
155pub const MACROS: &str =  r#"
156use super::*;
157
158#[macro_export]
159macro_rules! make_input_struct {
160    (
161        $x:ident,
162        [$(
163            $(#[$default_derive:stmt])?
164            $visibility:vis $element:ident : $ty:ty),*],
165        [$($der:ident),*]
166) => {
167        #[derive($($der),*)]
168            pub struct $x { 
169            $(
170                $(#[serde(default=$default_derive)])?
171                $visibility  $element: $ty
172            ),*
173        }
174    }
175}
176
177#[macro_export]
178macro_rules! make_main_struct {
179    (
180        $name:ident,
181        $input:ty,
182        [$($der:ident),*],
183        [$($key:ident : $val:expr),*],
184        $output_field: ident
185) => {
186        #[derive($($der),*)]
187        $(
188            #[$key = $val]
189        )*
190        pub struct $name {
191            action_name: String,
192            pub input: $input,
193            pub output: Value,
194            pub mapout: Value
195        }
196        impl $name{
197            pub fn output(&self) -> Value {
198                self.$output_field.clone()
199            }
200        }
201    }
202}
203
204#[macro_export]
205macro_rules! impl_new {
206    (
207        $name:ident,
208        $input:ident,
209        []
210    ) => {
211        impl $name{
212            pub fn new(action_name:String) -> Self{
213                Self{
214                    action_name,
215                    input: $input{
216                        ..Default::default()
217                    },
218                    ..Default::default()
219                }      
220            }
221        }
222    };
223    (
224        $name:ident,
225        $input:ident,
226        [$($element:ident : $ty:ty),*]
227    ) => {
228        impl $name{
229            pub fn new($( $element: $ty),*, action_name:String) -> Self{
230                Self{
231                    action_name,
232                    input: $input{
233                        $($element),*,
234                        ..Default::default()
235                    },
236                    ..Default::default()
237                }      
238            }
239        }
240    }
241}
242
243#[macro_export]
244macro_rules! impl_setter {
245    (
246        $name:ty,
247        [$($element:ident : $key:expr),*]
248    ) => {
249        impl $name{
250            pub fn setter(&mut self, value: Value) {
251                $(
252                    let val = value.get($key).unwrap();
253                    self.input.$element = serde_json::from_value(val.clone()).unwrap();
254                )*
255            }
256        }
257    }
258}
259
260#[macro_export]
261macro_rules! impl_map_setter {
262    (
263        $name:ty,
264        $element:ident : $key:expr,  
265        $typ_name : ty,
266        $out:expr
267    ) => {
268        impl $name {
269            pub fn setter(&mut self, val: Value) {
270                
271                    let value = val.get($key).unwrap();
272                    let value = serde_json::from_value::<Vec<$typ_name>>(value.clone()).unwrap();
273                    let mut map: HashMap<_, _> = value
274                        .iter()
275                        .map(|x| {
276                            self.input.$element = x.to_owned() as $typ_name;
277                            self.run();
278                            (x.to_owned(), self.output.get($out).unwrap().to_owned())
279                        })
280                        .collect();
281                    self.mapout = to_value(map).unwrap();
282                
283            }
284        }
285    }
286    }
287
288#[macro_export]
289macro_rules! impl_concat_setter {
290    (
291        $name:ty,
292        $input:ident
293    ) => {
294        impl $name{
295            pub fn setter(&mut self, val: Value) {
296                
297                    let val: Vec<Value> = serde_json::from_value(val).unwrap();
298                    let res = join_hashmap(
299                        serde_json::from_value(val[0].to_owned()).unwrap(),
300                        serde_json::from_value(val[1].to_owned()).unwrap(),
301                    );
302                    self.input.$input = res;
303            }
304        }
305    }
306}
307
308#[allow(unused)]
309#[macro_export]
310macro_rules! impl_combine_setter {
311    (
312        $name:ty,
313        [$(
314            $(($value_input:ident))?
315            $([$index:expr])?
316            $element:ident : $key:expr),*]
317    ) => {
318        impl $name{
319            pub fn setter(&mut self, value: Value) {
320
321                let value: Vec<Value> = serde_json::from_value(value).unwrap();
322                $(
323                    if stringify!($($value_input)*).is_empty(){
324                        let val = value[$($index)*].get($key).unwrap();
325                        self.input.$element = serde_json::from_value(val.clone()).unwrap();
326                    }else{
327                        self.input.$element = serde_json::from_value(value[$($index)*].to_owned()).unwrap();
328                    }
329                )*
330            }
331        }
332    }
333}
334
335
336"#;
337pub const CARGO: &str = r#"
338
339[package]
340name = "boilerplate"
341version = "0.0.1"
342edition = "2018"
343
344
345[lib]
346crate-type = ["cdylib"]
347
348[profile.release]
349lto = true
350codegen-units = 1
351overflow-checks = true
352# Tell `rustc` to optimize for small code size.
353opt-level = "z"
354debug = false
355
356[workspace]
357
358[dependencies]
359derive-enum-from-into = "0.1.1"
360serde_derive = "1.0.192"
361paste = "1.0.7"
362dyn-clone = "1.0.7"
363workflow_macro = "0.0.3"
364openwhisk-rust = "0.1.2"
365serde_json = { version = "1.0", features = ["raw_value"] }
366serde = { version = "1.0.192", features = ["derive"] }
367codec = { package = "parity-scale-codec", features = [
368    "derive",
369], version = "3.1.5" }
370
371"#;