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
#![doc(html_root_url = "https://movie.pzmarzly.pl")]

//! `movie_derive` - crate containing procedural macros.

extern crate proc_macro;
use proc_macro::TokenStream;

use std::collections::HashMap;

#[proc_macro]
/// Macro that generates module `ActorName`, which contains structs `Actor` and `Input`.
pub fn actor(input: TokenStream) -> TokenStream {
    actor_internal(input, false)
}
#[proc_macro]
/// This version of `actor!` will `eprintln!` how it sees the input and what code it generated.
pub fn actor_dbg(input: TokenStream) -> TokenStream {
    actor_internal(input, true)
}

// Input: "SimplestActor input : Ping , on_message : Ping => Pong ,"
fn actor_internal(input: TokenStream, debug: bool) -> TokenStream {
    let input = input.to_string();

    if debug {
        eprintln!("Input:");
        eprintln!("{}", input);
    }

    // PART ONE
    // Locate attributes inside input string

    let supported_attributes = vec![
        // attr name, default value
        ("public_visibility", ""),
        ("docs", ""),
        ("input", ""),
        ("input_derive", ""),
        ("data", ""),
        ("on_init", ""),
        ("on_message", ""),
        ("tick_interval", "100"),
        ("on_tick", ""),
        ("on_stop", ""),
        ("spawner", "std::thread::spawn"),
        ("spawner_return_type", "std::thread::JoinHandle<()>"),
        ("custom_code", ""),
    ];

    // locations = [(start, attr name, start of content), ...]
    let mut locations = vec![(0, "name", 0)];
    for attr in &supported_attributes {
        let attr = attr.0;
        // Any of the following cases may happen:
        let search_strings = &[
            format!("\n{} :\n", attr),
            format!(" {} :\n", attr),
            format!("\n{} : ", attr),
            format!(" {} : ", attr),
            format!("\n{}\n:\n", attr),
            format!(" {}\n:\n", attr),
            format!("\n{}\n: ", attr),
            format!(" {}\n: ", attr),
        ];
        for search_str in search_strings {
            let pos = input.find(search_str);
            if let Some(pos) = pos {
                locations.push((pos, attr, pos + search_str.len()));
                break;
            }
        }
    }

    // PART TWO
    // Turn array of locations to array of values

    // attrs = {
    //     "input": "Ping ,"
    //     "name": "SimplestActor",
    //     "on_message": "Ping => Pong ,",
    // }
    let mut attrs: HashMap<&str, String> = HashMap::new();

    locations.sort_unstable();

    // locations = [(start, attr name, start of content), ...]
    for i in 0..locations.len() {
        let value = if i == locations.len() - 1 {
            // We are parsing the last segment
            &input[locations[i].2..]
        } else {
            // Start of the next segment is this one's ends
            &input[locations[i].2..locations[i + 1].0]
        };
        attrs.insert(locations[i].1, value.to_string());
    }

    if debug {
        eprintln!("Parsed attributes:");
        eprintln!("{:?}", &attrs);
    }

    // PART THREE
    // Assign default values for missing optional supported attrs

    for attr in &supported_attributes {
        attrs.entry(attr.0).or_insert(attr.1.to_string());
    }

    // PART FOUR
    // Generate code

    // Prepare strings used later
    let public_visibility = if attrs["public_visibility"].contains("true") {
        "pub".to_string()
    } else {
        "".to_string()
    };
    let input_derive = if attrs["input_derive"].len() > 0 {
        format!("#[derive({})]", attrs["input_derive"])
    } else {
        "".to_string()
    };

    // TODO: Consider rewriting to quote!()
    let output = format!(
        "
        {docs}
        {public_visibility} mod {name} {{
        use super::*;

        {custom_code}

        pub struct Actor {{
            {data}
        }}

        {input_derive}
        pub enum Input {{
            {input}
        }}

        pub type Handle = movie::Handle<{spawner_return_type}, Input>;

        impl Actor {{
            pub fn start(mut self) -> Handle
            {{
                let (tx_ota, rx_ota) = std::sync::mpsc::channel(); // owner-to-actor data
                let (tx_kill, rx_kill) = std::sync::mpsc::channel(); // owner-to-actor stop requests
                let handle = {spawner}(move || {{
                    {on_init} // on_init is not separated as this is the simplest way to
                              // implement thread-local data. This may change in later (breaking)
                              // updates
                    let mut running = true;
                    while running {{
                        while let Ok(message) = rx_ota.try_recv() {{
                            use Input::*;
                            match message {{
                                {on_message}
                            }};
                        }}
                        if let Ok(_) = rx_kill.try_recv() {{
                            running = false;
                            {{
                                {on_stop}
                            }};
                        }}
                        {{
                            {on_tick}
                        }};
                        use std::thread::sleep;
                        use std::time::Duration;
                        sleep(Duration::from_millis({tick_interval}));
                    }}
                }});
                movie::Handle {{
                    join_handle: handle,
                    tx: tx_ota,
                    kill: tx_kill,
                }}
            }}
        }}
        }}",
        // attrs
        name = attrs["name"],
        docs = attrs["docs"],
        input = attrs["input"],
        data = attrs["data"],
        on_init = attrs["on_init"],
        on_message = attrs["on_message"],
        tick_interval = attrs["tick_interval"],
        on_tick = attrs["on_tick"],
        on_stop = attrs["on_stop"],
        spawner = attrs["spawner"],
        spawner_return_type = attrs["spawner_return_type"],
        custom_code = attrs["custom_code"],
        // prepared strings
        public_visibility = public_visibility,
        input_derive = input_derive,
    );
    if debug {
        eprintln!("Generated code:");
        eprintln!("{}", output);
    }
    output.parse().unwrap()
}