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
#![deny(missing_docs)]
//! This template crate uses and defines a [DisplayAs] trait, which
//! allows a type to be displayed in a particular format.
//!
//! # Overview
//!
//! This crate defines three things that you need be aware of in order
//! to use it: the [Format] trait, which defines a markup language or
//! other format, the [DisplayAs] trait which is implemented for any
//! type that can be converted into some [Format], and finally the
//! template language and macros which allow you to conveniently
//! implement [DisplayAs] for your own types.  I will describe each of
//! these concepts in order.  (**FIXME** I should also have a
//! quick-start...)
//!
//! ## [Format]
//!
//! There are a number of predefined Formats (and I can easily add
//! more if there are user requests), so the focus here will be on
//! using these Formats, rather than on defining your own (which also
//! isn't too hard).  A format is a zero-size type that has a rule for
//! escaping strings and an associated MIME type.  The builtin formats
//! include [HTML], [LaTeX], and [Math] (which is math-mode LaTeX).
//!
//! ## [DisplayAs]`<F>`
//!
//! The `[DisplayAs]<F: Format>` trait is entirely analogous to the [Display](std::fmt::Display) trait
//! in the standard library, except that it is parametrized by a
//! [Format] so you can have different representations for the same
//! type in different formats.  This also makes it harder to
//! accidentally include the wrong representation in your output.
//!
//! Most of the primitive types already have [DisplayAs] implemented
//! for the included Formats.  If you encounter a type that you wish
//! had [DisplayAs] implemented for a given format, just let me know.
//! You can manually implement [DisplayAs] for any of your own types
//! (it's not worse than implementing [Display](std::fmt::Display)) but that isn't how
//! you are intended to do things (except perhaps in very simple
//! cases, like a wrapper around an integer).  Instead you will want
//! to use a template to implement [DisplayAs] for your own types.
//!
//! ## Templates!
//!
//! There are two template macros that you can use.  If you just want
//! to get a string out of one or more [DisplayAs] objects, you will
//! use something like `format_as!(HTML, "hello world" value)`.  If
//! you want to implement [DisplayAs], you will use the attribute
//! [with_template!].  In these examples I will use
//! [format_as!] because that makes it easy to write testable
//! documentation.  But in practice you will most likely primarily use
//! the [with_template] attribute.
//!
//! ### String literals
//!
//! The first thing you can include in a template is a string literal,
//! which is treated literally.
//!
//! ```
//! use display_as::{HTML, format_as};
//! assert_eq!(&format_as!(HTML, "Treat this literally <" ),
//!            "Treat this literally <");
//! ```
//!
//! ### Expressions
//!
//! String literals are essential to representing some other [Format].
//! To include your data in the output, you can include any expression
//! that yields a type with [DisplayAs]`<F>` where `F` is your [Format].
//! Each expression is delimited by string literals (or the other
//! options below).  Note that since an expression is
//!
//! ```
//! use display_as::{HTML, format_as};
//! let s = "This is not a literal: <";
//! assert_eq!(&format_as!(HTML, s ),
//!            "This is not a literal: &lt;");
//! ```
//!
//! ### Blocks and conditionals
//!
//! You can use braces to enclose any template expression.  Any rust
//! code before the braces is treated as literal rust.  This enables
//! you to write conditionals, match expressions, and loops.
//!
//! ```
//! use display_as::{HTML, format_as};
//! assert_eq!(&format_as!(HTML,
//!                        for i in 1..4 {
//!                            "Counting " i "...\n"
//!                        }
//!                        "Blast off!"),
//!            "Counting 1...\nCounting 2...\nCounting 3...\nBlast off!");
//! ```
//!
//! ### Semicolons
//!
//! You may also play any rust statements you wish, if you end them
//! with a semicolon.  This enables you to define local variables.
//!
//! ```
//! use display_as::{HTML, format_as};
//! assert_eq!(&format_as!(HTML, "I am counting " let count = 5;
//!                              count " and again " count ),
//!            "I am counting 5 and again 5");
//! ```
//!
//! ### Embedding a different format
//!
//! You can also embed in one format a representation from another
//! type.  This can be helpful, for instance, if you want to use
//! MathJax to handle LaTeX math embedded in an HTML file.
//!
//! ```
//! use display_as::{HTML, Math, format_as};
//! assert_eq!(&format_as!(HTML, "The number $" 1.2e12 as Math "$"),
//!            r"The number $1.2\times10^{12}$");
//! ```
//!
//! ### Saving a portion of a template for reuse
//!
//! You can also save a template expression using a let statement,
//! provided the template expression is enclosed in braces.  This
//! allows you to achieve goals similar to the base templates in
//! Jinja2.  (Once we have an include feature... Example to come in
//! the future.)
//!
//! ```
//! use display_as::{HTML, format_as};
//! assert_eq!(&format_as!(HTML,
//!                        let x = 1;
//!                        let announce = { "number " x };
//!                        "The " announce " is silly " announce),
//!            "The number 1 is silly number 1");
//! ```
//!
//! ## Differences when putting a template in a file
//!
//! You will most likely always put largish templates in a separate
//! file.  This makes editing your template simpler and keeps things
//! in general easier.  The template language for templates held in a
//! distinct file has one difference from those shown above: the file
//! always begins and ends with string literals, but their initial and
//! final quotes respectively are omitted.  Furthermore, the first and
//! last string literals must be "raw" literals with a number of #
//! signs equal to the maximum used in the template.  I suggest using
//! an equal number of # signs for all string literals in a given
//! template.  Thus a template might look like:
//!
//! ```ignore
//! <html>
//!   <body>
//!     "## self.title r##"
//!   </body>
//! </html>
//! ```

//! You can see that the quotes appear "inside out."  This is
//! intentional, so that for most formats the quotes will appear to
//! enclose the rust code rather than everything else, and as a result
//! editors will hopefully be able to do the "right thing" for the
//! template format (e.g. HTML in this case).

#![cfg_attr(feature = "docinclude", feature(external_doc))]
//! ## Using `include!("...")` within a template
//!
//! Now I will demonstrate how you can include template files within
//! other template files by using the `include!` macro within a
//! template.  To demonstrate this, we will need a few template files.
//!
//! We will begin with a "base" template that describes how a page is
//! laid out.
//! #### `base.html`:
//! ```ignore
#![cfg_attr(feature = "docinclude", doc(include = "base.html"))]
//! ```
//! We can have a template for how we will display students...
//! #### `student.html`:
//! ```ignore
#![cfg_attr(feature = "docinclude", doc(include = "student.html"))]
//!```
//! Finally, an actual web page describing a class!
//! #### `class.html`:
//! ```ignore
#![cfg_attr(feature = "docinclude", doc(include = "class.html"))]
//! ```
//! Now to put all this together, we'll need some rust code.
//!
//! ```
//! use display_as::{DisplayAs, HTML, format_as, with_template};
//! struct Student { name: &'static str };
//! #[with_template("student.html")]
//! impl DisplayAs<HTML> for Student {}
//!
//! struct Class { coursename: &'static str, coursenumber: usize, students: Vec<Student> };
//! #[with_template("class.html")]
//! impl DisplayAs<HTML> for Class {}
//!
//! let myclass = Class {
//!       coursename: "Templates",
//!       coursenumber: 365,
//!       students: vec![Student {name: "David"}, Student {name: "Joel"}],
//! };
//! assert_eq!(&format_as!(HTML, myclass), r#"<title>PH365: Templates</title>
//! <html>
//!   <ul>
//!
//!   // This is buggy:  I want to iterate, but it fails!
//!   for s in self.students.iter() {
//!     "<li>" s "</li>"
//!   }
//!
//!   </ul>
//! </html>
//!
//!
//!"#);
//! ```

extern crate display_as_proc_macro;
extern crate mime;
extern crate proc_macro_hack;

#[proc_macro_hack]
pub use display_as_proc_macro::format_as;
#[proc_macro_hack]
pub use display_as_proc_macro::write_as;
use proc_macro_hack::proc_macro_hack;

/// Can I write doc here?
pub use display_as_proc_macro::with_template;

use std::fmt::{Display, Error, Formatter};

#[macro_use]
mod html;
mod latex;
mod mathlatex;
mod rust;
mod url;
mod utf8;

pub mod float;

pub use crate::html::HTML;
pub use crate::url::URL;
pub use crate::latex::LaTeX;
pub use crate::mathlatex::Math;
pub use crate::rust::Rust;
pub use crate::utf8::UTF8;

/// Format is a format that we can use for displaying data.
pub trait Format {
    /// "Escape" the given string so it can be safely displayed in
    /// this format.  The precise meaning of this may vary from format
    /// to format, but the general sense is that this string does not
    /// have any internal formatting, and must be displayed
    /// appropriately.
    fn escape(f: &mut Formatter, s: &str) -> Result<(), Error>;
    /// The mime type of this format.
    fn mime() -> mime::Mime;
    /// Return an actual [Format] for use in [As] below.
    fn this_format() -> Self;
}

/// This trait is analogous to [Display](std::fmt::Display), but will display the data in
/// `F` [Format].
pub trait DisplayAs<F: Format> {
    /// Formats the value using the given formatter.
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error>;

    /// Creates a display object
    fn display<'a>(&'a self) -> As<'a, F, Self> {
        As::from(self)
    }
}

/// Create a Display object, which can be used with various web frameworks.
pub fn display<'a, F: Format, T: DisplayAs<F>>(_f: F, x: &'a T) -> As<'a, F, T> {
    x.display()
}

struct Closure<F: Format, C: Fn(&mut Formatter) -> Result<(), Error>> {
    f: C,
    _format: F,
}
/// Display the given closure as this format.
///
/// This is used internally in template handling.
pub fn display_closure_as<F: Format>(f: F, c: impl Fn(&mut Formatter) -> Result<(), Error>) -> impl DisplayAs<F> {
    Closure {
        f: c,
        _format: f,
    }
}
impl<F: Format, C: Fn(&mut Formatter) -> Result<(), Error>> DisplayAs<F> for Closure<F,C> {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        (self.f)(f)
    }
}

#[test]
fn test_closure() {
    let x = |__f: &mut Formatter| -> Result<(), Error> {
        __f.write_str("hello world")?;
        Ok(())
    };
    assert_eq!("hello world", &format_as!(HTML, display_closure_as(HTML, x)));
}

/// Choose to [Display](std::fmt::Display) this type using a particular [Format] `F`.
pub struct As<'a, F: Format, T: DisplayAs<F> + ?Sized> {
    inner: &'a T,
    _format: F,
}
impl<'a, F: Format, T: DisplayAs<F> + ?Sized> From<&'a T> for As<'a, F, T> {
    fn from(value: &'a T) -> Self {
        As {
            _format: F::this_format(),
            inner: value,
        }
    }
}
impl<'a, F: Format, T: DisplayAs<F> + ?Sized> Display for As<'a, F, T> {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        self.inner.fmt(f)
    }
}

/// The `rouille` feature flag enables conversion of any `As<F,T>`
/// type into a [rouille::Response].  Note that it is necessary to be
/// explicit about the format because a given type `T` may be
/// displayed in multiple different formats.
#[cfg(feature = "rouille")]
pub mod rouille {
    extern crate rouille;
    use super::{As, DisplayAs, Format};
    impl<'a, F: Format, T: DisplayAs<F>> Into<rouille::Response> for As<'a, F, T> {
        fn into(self) -> rouille::Response {
            let s = format!("{}", &self);
            rouille::Response::from_data(F::mime().as_ref().to_string(), s)
        }
    }
}

/// The `actix-web` feature flag makes any [As] type a
/// [actix_web::Responder].
#[cfg(feature = "actix-web")]
pub mod actix {
    extern crate actix_web;
    use self::actix_web::{HttpRequest, HttpResponse, Responder};
    use super::{As, DisplayAs, Format};
    impl<'a, F: Format, T: 'a + DisplayAs<F>> Responder for As<'a, F, T> {
        type Item = HttpResponse;
        type Error = ::std::io::Error;
        fn respond_to<S: 'static>(
            self,
            _req: &HttpRequest<S>,
        ) -> Result<HttpResponse, Self::Error> {
            Ok(HttpResponse::Ok()
                .content_type(F::mime().as_ref().to_string())
                .body(format!("{}", &self)))
        }
    }
}

/// The `gotham-web` feature flag makes any [As] type a
/// [gotham::IntoResponse].
#[cfg(feature = "gotham-web")]
pub mod gotham {
    use crate::{As, DisplayAs, Format};
    impl<'a, F: Format, T: 'a + DisplayAs<F>> gotham::handler::IntoResponse for As<'a, F, T> {
        fn into_response(self, state: &gotham::state::State) -> http::Response<hyper::Body> {
            let s = format!("{}", &self);
            (http::StatusCode::OK, F::mime(), s).into_response(state)
        }
    }
}

/// The `warp` feature flag makes any [DisplayAs] type Into<[http::Response]>.
#[cfg(feature = "warp")]
pub mod warp {
    use crate::{DisplayAs, Format, As};
    impl<'a, F: Format, T: DisplayAs<F>> As<'a, F, T> {
        /// Convert into a [warp::Reply].
        pub fn http_response(&self) -> http::Response<String> {
            let s = format!("{}", self);
            let m = F::mime().as_ref().to_string();
            let mut response = http::Response::builder();
            response
                .header("Content-type", m.as_bytes())
                .status(http::StatusCode::OK);
            response.body(s).unwrap()
        }
    }

    #[test]
    fn test_warp() {
        use crate::{HTML, display};
        // This sloppy test just verify that the code runs.
        display(HTML, &"hello world".to_string()).http_response();
    }
}

impl<F: Format> DisplayAs<F> for String {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        F::escape(f, self)
    }
}
impl<'a, F: Format> DisplayAs<F> for &'a String {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        F::escape(f, self)
    }
}
impl<F: Format> DisplayAs<F> for str {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        F::escape(f, self)
    }
}
impl<'a, F: Format> DisplayAs<F> for &'a str {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        F::escape(f, self)
    }
}

#[cfg(test)]
mod tests {
    use super::{HTML};
    #[test]
    fn html_escaping() {
        assert_eq!(&format_as!(HTML, ("&")), "&amp;");
        assert_eq!(
            &format_as!(HTML, ("hello &>this is cool")),
            "hello &amp;&gt;this is cool"
        );
        assert_eq!(
            &format_as!(HTML, ("hello &>this is 'cool")),
            "hello &amp;&gt;this is &#x27;cool"
        );
    }
}