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
#![feature(quote, plugin_registrar, rustc_private, box_syntax, stmt_expr_attributes)]

extern crate rustc_plugin;
extern crate rustc_target;
extern crate syntax;

use rustc_plugin::registry::Registry;

use rustc_target::spec::abi::Abi;
use syntax::ast::{Attribute, Ident, Item, ItemKind, MetaItem, Mod, Name, Ty, VisibilityKind};
use syntax::attr;
use syntax::codemap::Span;
use syntax::ext::base::SyntaxExtension::{MultiModifier, NormalTT};
use syntax::ext::base::{Annotatable, ExtCtxt, MacEager, MacResult, MultiItemModifier,
                        TTMacroExpander};
use syntax::feature_gate::AttributeType;
use syntax::ptr::P;
use syntax::tokenstream::TokenStream;
use syntax::edition::Edition;

use std::cell::RefCell;
use std::rc::Rc;

use std::mem;

mod codegen;
mod util;

use util::{mod_walk, rustc::*, syntax::get_fn_info};

#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
    let fn_list = Rc::new(RefCell::new(Vec::new()));

    let header_extension = HotswapHeaderExtension {
        fn_list: Rc::clone(&fn_list),
    };
    let macro_extension = HotswapMacroExtension {
        fn_list: Rc::clone(&fn_list),
    };

    // This macro is used to walk around the program modules and modify
    // the function code depending on the build type(bin or lib).
    reg.register_syntax_extension(
        Name::intern("hotswap_header"),
        MultiModifier(box header_extension),
    );

    // The user should have a `hotswap_start!` macro before using any
    // hotswapped functions, so the library can initialize all the
    // necessary stuff.
    reg.register_syntax_extension(
        Name::intern("hotswap_start"),
        NormalTT {
            expander: box macro_extension,
            def_info: None,
            allow_internal_unsafe: false,
            allow_internal_unstable: false,
            unstable_feature: None,
            edition: Edition::Edition2015
        },
    );

    // This macro is used only as a tag so the hotswap header can find out
    // which functions should be hotswapped.
    reg.register_attribute("hotswap".to_string(), AttributeType::Whitelisted);
}

pub struct HotswapFnInfo {
    name: String,
    input_types: Vec<Ty>,
    input_idents: Vec<Ident>,
    output_type: P<Ty>,
}

type HotswapFnList = Vec<HotswapFnInfo>;

struct HotswapHeaderExtension {
    fn_list: Rc<RefCell<HotswapFnList>>,
}

struct HotswapMacroExtension {
    fn_list: Rc<RefCell<HotswapFnList>>,
}

// When building a lib, we should export all functions that are tagged as `hotswap`,
// when building a bin, we should completely replace function bodies so it calls
// a dynamically loaded one that is stored in a global structure.
impl MultiItemModifier for HotswapHeaderExtension {
    fn expand(
        &self,
        cx: &mut ExtCtxt,
        _: Span,
        _: &MetaItem,
        annotatable: Annotatable,
    ) -> Vec<Annotatable> {
        if let Annotatable::Item(item) = annotatable {
            let mut item = item.into_inner();

            if let ItemKind::Mod(m) = item.node {
                item.node = ItemKind::Mod(match crate_type().as_ref() {
                    "bin" => {
                        let mut hotswap_fns = self.fn_list.borrow_mut();
                        let tmp = expand_bin_mod(cx, m, &mut hotswap_fns);
                        expand_bin_footer(cx, tmp, &mut hotswap_fns)
                    }
                    "dylib" => expand_lib_mod(cx, m),
                    _ => unimplemented!(),
                });

                // Ignore dead code in the lib build, probably there will be a lot
                // of it, including the `main` function.
                item.attrs = match crate_type().as_ref() {
                    "dylib" => expand_lib_attrs(cx, item.attrs),
                    _ => item.attrs,
                };

                return vec![Annotatable::Item(P(item))];
            }
        }

        // TODO: proper warning when the header annotation is
        // used outside a module.
        unimplemented!();
    }
}

impl TTMacroExpander for HotswapMacroExtension {
    fn expand(&self, cx: &mut ExtCtxt, _: Span, tt: TokenStream) -> Box<MacResult> {
        let hotswap_fns = self.fn_list.borrow();

        // It will be empty when there are no functions tagged as `hotswap`,
        // when `hotswap_header` was no called, and on lib builds, in all
        // those cases we shouldn't expand the hotswap initialization.
        if hotswap_fns.is_empty() {
            // Some arbitrary unsafe code to prevent unnunsed unsafe
            // warnings, also will stop the build during the lib stage,
            // if the user hasn't wrapped the macro in unsafe, instead of
            // building the lib and stopping on the bin.
            return MacEager::expr(quote_expr!(cx, {
                &*(0 as *const usize);
            }));
        }

        if !tt.is_empty() {
            // TODO: proper warning when user doesn't leave the macro
            // empty.
            unimplemented!();
        }

        MacEager::expr(codegen::macro_expansion(cx, &hotswap_fns))
    }
}

fn expand_lib_attrs(cx: &mut ExtCtxt, mut attrs: Vec<Attribute>) -> Vec<Attribute> {
    attrs.insert(0, quote_attr!(cx, #![allow(unused_imports)]));
    attrs.insert(0, quote_attr!(cx, #![allow(dead_code)]));
    attrs.insert(0, quote_attr!(cx, #![allow(unused_features)]));
    attrs
}

fn expand_lib_mod(cx: &mut ExtCtxt, m: Mod) -> Mod {
    mod_walk(m, &mut |item| {
        if attr::contains_name(&item.attrs, "hotswap") {
            match item.node {
                ItemKind::Fn(..) => return expand_lib_fn(cx, item),
                // TODO: write proper warning.
                _ => println!("warning: hotswap only works on functions"),
            }
            expand_lib_fn(cx, item)
        } else {
            item
        }
    })
}

fn expand_lib_fn(cx: &mut ExtCtxt, mut item: Item) -> Item {
    if let ItemKind::Fn(_, ref mut header, _, _) = item.node {
        // Make lib functions extern and no mangle so they can
        // be imported from the runtime.
        item.attrs.push(quote_attr!(cx, #![no_mangle]));
        item.vis.node = VisibilityKind::Public;

        mem::replace(&mut header.abi, Abi::Rust);
    }

    item
}

fn expand_bin_mod(cx: &mut ExtCtxt, m: Mod, hotswap_fns: &mut HotswapFnList) -> Mod {
    mod_walk(m, &mut |item: Item| {
        if attr::contains_name(&item.attrs, "hotswap") {
            match item.node {
                ItemKind::Fn(..) => return expand_bin_fn(cx, item, hotswap_fns),
                // TODO: write proper warning.
                _ => println!("warning: hotswap only works on functions"),
            }
        }

        item
    })
}

fn expand_bin_fn(cx: &mut ExtCtxt, mut item: Item, hotswap_fns: &mut HotswapFnList) -> Item {
    let fn_info = get_fn_info(cx, &item);

    if let ItemKind::Fn(_, _, _, ref mut block) = item.node {
        mem::replace(block, codegen::fn_body(cx, &fn_info));
    }

    hotswap_fns.push(fn_info);
    item
}

// After all the functions to be hotswapped are found, we insert a custom module
// at the end of the users main file, in which we store the external function
// pointers during runtime.
fn expand_bin_footer(cx: &mut ExtCtxt, mut m: Mod, hotswap_fns: &mut HotswapFnList) -> Mod {
    m.items
        .insert(0, quote_item!(cx, extern crate hotswap_runtime;).unwrap());
    m.items.push(codegen::runtime_mod(cx, hotswap_fns));
    m
}