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
// Warnings (other than unused variables) in doctests are promoted to errors.
#![doc(test(attr(deny(warnings))))]
#![doc(test(attr(allow(dead_code))))]
#![doc(test(attr(allow(unused_variables))))]

//! Implementation detail of the `fastly` crate.

extern crate proc_macro;
use {
    proc_macro::TokenStream,
    proc_macro2::Span,
    quote::quote_spanned,
    syn::{
        parse_macro_input, parse_quote, punctuated::Punctuated, spanned::Spanned, Attribute, Ident,
        ItemFn, ReturnType, Signature, Visibility,
    },
};

/// Main function attribute for a Compute@Edge program.
///
/// ## Usage
///
/// This attribute should be applied to a `main` function that takes a request and returns a
/// response or an error. For example:
///
/// ```rust,no_run
/// use fastly::{Body, Error, Request, RequestExt, ResponseExt};
///
/// #[fastly::main]
/// fn main(ds_req: Request<Body>) -> Result<impl ResponseExt, Error> {
///     Ok(ds_req.send("example_backend")?)
/// }
/// ```
///
/// You can apply `#[fastly::main]` to any function that takes `Request<Body>` as its sole argument,
/// and returns a `Result<impl ResponseExt, Error>`. The `impl ResponseExt` syntax means that the
/// function must return a type that implements the `fastly::ResponseExt` trait, such as
/// `Response<Body>` or `Response<String>`.
///
/// ## More Information
///
/// This is a convenience to abstract over the common usage of
/// [`fastly::downstream_request`][get-downstream] and
/// [`RequestExt::send_downstream`][send-downstream] at the beginning and end of a program's `main`
/// function.
///
/// With this macro applied we can write a function that accepts a downstream request as an
/// argument and returns a downstream response, rather than calling
/// [`fastly::downstream_request`][get-downstream] ourselves. This is equivalent to the following
/// code:
///
/// ```rust,no_run
/// use fastly::{downstream_request, Error, RequestExt, ResponseExt};
///
/// fn main() -> Result<(), Error> {
///     let ds_req = downstream_request();
///     let us_resp = ds_req.send("example_backend")?;
///     us_resp.send_downstream();
///     Ok(())
/// }
/// ```
///
/// ## Troubleshooting
///
/// As described above, `[fastly::main]` expects a function with a specific signature. While this
/// macro will attempt to provide helpful errors, procedural macros cannot typecheck your code.
/// As a result, you may see "backwards" errors if your argument types are incorrect, like this:
///
/// ```text
/// error[E0308]: mismatched types
///  --> main.rs:8:1
///   |
/// 8 | fn main(downstream_request: Request<u32>) -> Result<impl ResponseExt, Error> {
///   | ^^ expected u32, found struct `fastly::body::Body`
///   |
///   = note: expected type `http::request::Request<u32>`
///              found type `http::request::Request<fastly::body::Body>`
/// ```
///
/// In this case, be sure that you should update the signature of your `main` function, being sure
/// to use the correct `Request<Body>` type for your function argument.
///
/// [get-downstream]: https://docs.rs/fastly/0.2.0-alpha4/fastly/request/fn.downstream_request.html
/// [req]: https://docs.rs/fastly/0.2.0-alpha4/fastly/struct.Request.html
/// [send-downstream]: https://docs.rs/fastly/0.2.0-alpha4/fastly/response/trait.ResponseExt.html#method.send_downstream
#[proc_macro_attribute]
pub fn main(_: TokenStream, input: TokenStream) -> TokenStream {
    // Parse the input token stream as a free-standing function, or return an error.
    let raw_main = parse_macro_input!(input as ItemFn);

    // Check that the function signature looks okay-ish. If we have the wrong number of arguments,
    // or no return type is specified , print a friendly spanned error with the expected signature.
    if !check_impl_signature(&raw_main.sig) {
        return syn::Error::new(
            raw_main.sig.span(),
            "`fastly::main` expects a function such as:

#[fastly::main]
fn main (request: Request<Body>) -> Result<impl ResponseExt, Error> {
    ...
}
",
        )
        .to_compile_error()
        .into();
    }

    // Get the attributes, visibility, and signature of our outer function. Then, update the
    // attributes and visibility of the inner function that we will inline.
    let (attrs, vis, sig) = outer_main_info(&raw_main);
    let (name, inner_fn) = inner_fn_info(raw_main);

    // Define our raw main function, which will provide the downstream request to our main function
    // implementation as its argument, and then send the `ResponseExt` result downstream.
    let output = quote_spanned! {inner_fn.span() =>
        #(#attrs)*
        #vis
        #sig {
            #[inline(always)]
            #inner_fn
            fastly::init();
            let ds_req = fastly::downstream_request();
            match #name(ds_req) {
                Ok(ds_resp) => ds_resp.send_downstream(),
                Err(e) => {
                    fastly::http::response::Builder::new()
                        .status(fastly::http::StatusCode::INTERNAL_SERVER_ERROR)
                        .body(e.to_string())?
                        .send_downstream()
                }
            };
            Ok(())
        }
    };

    output.into()
}

/// Check if the signature of the `#[main]` function seems correct.
///
/// Unfortunately, we cannot precisely typecheck in a procedural macro attribute, because we are
/// dealing with [`TokenStream`]s. This checks that our signature takes one input, and has a return
/// type. Specific type errors are caught later, after the [`fastly_main`] macro has been expanded.
///
/// This is used by the [`fastly_main`] procedural macro attribute to help provide friendly errors
/// when given a function with the incorrect signature.
///
/// [`fastly_main`]: attr.fastly_main.html
/// [`TokenStream`]: proc_macro/struct.TokenStream.html
fn check_impl_signature(sig: &Signature) -> bool {
    if sig.inputs.iter().len() != 1 {
        false // Return false if the signature takes no inputs, or more than one input.
    } else if let ReturnType::Default = sig.output {
        false // Return false if the signature's output type is empty.
    } else {
        true
    }
}

/// Returns a 3-tuple containing the attributes, visibility, and signature of our outer `main`.
///
/// The outer main function will use the same attributes and visibility as our raw main function.
///
/// The signature of the outer function will be changed to have inputs and outputs of the form
/// `fn main() -> Result<(), fastly::Error>`. The name of the outer main will always be just that,
/// `main`.
fn outer_main_info(inner_main: &ItemFn) -> (Vec<Attribute>, Visibility, Signature) {
    let attrs = inner_main.attrs.clone();
    let vis = Visibility::Inherited;
    let sig = {
        let mut sig = inner_main.sig.clone();
        sig.ident = Ident::new("main", Span::call_site());
        sig.inputs = Punctuated::new();
        sig.output = parse_quote!(-> ::std::result::Result<(), fastly::Error>);
        sig
    };

    (attrs, vis, sig)
}

/// Prepare our inner function to be inlined into our main function.
///
/// This changes its visibility to [`Inherited`], and removes [`no_mangle`] from the attributes of
/// the inner function if it is there.
///
/// This function returns a 2-tuple of the inner function's identifier, and the function itself.
/// This identifier is used to emit code calling this function in our `main`.
///
/// [`Inherited`]: syn/enum.Visibility.html#variant.Inherited
/// [`no_mangle`]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute
fn inner_fn_info(mut inner_main: ItemFn) -> (Ident, ItemFn) {
    let name = inner_main.sig.ident.clone();
    inner_main.vis = Visibility::Inherited;
    inner_main
        .attrs
        .retain(|attr| !attr.path.is_ident("no_mangle"));
    (name, inner_main)
}