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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
extern crate quasi;
mod codegen {
extern crate aster;
extern crate glob;
extern crate mime_guess;
use self::mime_guess::guess_mime_type;
use std::path::{self, Path, PathBuf};
use std::ops::Deref;
use syntax::ast::{MetaItem, Item};
use syntax::ast;
use syntax::attr;
use syntax::codemap::Span;
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ptr::P;
use syntax::print::pprust::{lit_to_string};
use syntax::parse::token::{InternedString};
pub fn expand_webapp_implementation(cx: &mut ExtCtxt, span: Span,
meta_item: &MetaItem,
annotatable: &Annotatable,
push: &mut FnMut(Annotatable)) {
let item =
match *annotatable {
Annotatable::Item(ref item) => item,
_ => {
cx.span_err(meta_item.span,
"`#[derive(WebAppFiles)]` may only be applied to struct implementations");
return;
}
};
let builder = aster::AstBuilder::new().span(span);
implement_webapp(cx, &builder, &item, push);
}
fn implement_webapp(cx: &ExtCtxt, builder: &aster::AstBuilder,
item: &Item, push: &mut FnMut(Annotatable)) {
let static_files_dir = extract_path(cx, item);
let src = Path::new("src");
let static_files =
{
let mut buf = src.to_path_buf();
buf.push(static_files_dir.deref());
buf
};
let search_location =
{
let mut buf = static_files.to_path_buf();
buf.push("**");
buf.push("*");
buf
};
let files =
glob::glob(search_location.to_str().expect("Valid UTF8 path")).expect("The sources directory is missing.").collect::<Result<Vec<PathBuf>,
glob::GlobError>>().expect("There should be no error when reading a list of files.");
let statements =
files.iter().filter(|path_buf|
path_buf.is_file()).map(|path_buf| {
let path =
path_buf.as_path();
let filename =
path.file_name().and_then(|s|
s.to_str()).expect("Only UTF8 paths.");
let mime_type =
guess_mime_type(filename).to_string();
let file_path =
as_uri(path.strip_prefix(&static_files).ok().expect("Prefix is always there, cause it\'s absolute path;qed"));
let file_path_in_source =
path.to_str().expect("Only UTF8 paths.");
let path_lit =
builder.expr().str(file_path.as_str());
let mime_lit =
builder.expr().str(mime_type.as_str());
let web_path_lit =
builder.expr().str(file_path_in_source);
let separator_lit =
builder.expr().str(path::MAIN_SEPARATOR.to_string().as_str());
let concat_id =
builder.id("concat!");
let env_id =
builder.id("env!");
let macro_id =
builder.id("include_bytes!");
let content =
{
let ext_cx =
&*cx;
::quasi::parse_expr_panic(&mut ::syntax::parse::new_parser_from_tts(ext_cx.parse_sess(),
ext_cx.cfg(),
{
#[allow(unused_imports)]
use quasi::IntoWrappedIterator;
#[allow(unused_imports)]
use quasi::IntoWrappedRepeat;
let _sp =
ext_cx.call_site();
let mut tt =
::std::vec::Vec::new();
tt.extend(::quasi::ToTokens::to_tokens(¯o_id,
ext_cx).into_iter());
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren)));
tt.extend(::quasi::ToTokens::to_tokens(&concat_id,
ext_cx).into_iter());
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren)));
tt.extend(::quasi::ToTokens::to_tokens(&env_id,
ext_cx).into_iter());
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Literal(::syntax::parse::token::Str_(ext_cx.name_of("CARGO_MANIFEST_DIR")),
::std::option::Option::None)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Comma));
tt.extend(::quasi::ToTokens::to_tokens(&separator_lit,
ext_cx).into_iter());
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Comma));
tt.extend(::quasi::ToTokens::to_tokens(&web_path_lit,
ext_cx).into_iter());
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren)));
tt
}))
};
{
let ext_cx =
&*cx;
::quasi::parse_stmt_panic(&mut ::syntax::parse::new_parser_from_tts(ext_cx.parse_sess(),
ext_cx.cfg(),
{
#[allow(unused_imports)]
use quasi::IntoWrappedIterator;
#[allow(unused_imports)]
use quasi::IntoWrappedRepeat;
let _sp =
ext_cx.call_site();
let mut tt =
::std::vec::Vec::new();
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("files"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Dot));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("insert"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren)));
tt.extend(::quasi::ToTokens::to_tokens(&path_lit,
ext_cx).into_iter());
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Comma));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("File"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::OpenDelim(::syntax::parse::token::Brace)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("path"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Colon));
tt.extend(::quasi::ToTokens::to_tokens(&path_lit,
ext_cx).into_iter());
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Comma));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("content_type"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Colon));
tt.extend(::quasi::ToTokens::to_tokens(&mime_lit,
ext_cx).into_iter());
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Comma));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("content"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Colon));
tt.extend(::quasi::ToTokens::to_tokens(&content,
ext_cx).into_iter());
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::CloseDelim(::syntax::parse::token::Brace)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Semi));
tt
}))
}.expect("The statement is always ok, because it just uses literals.")
}).collect::<Vec<ast::Stmt>>();
let type_name = item.ident;
let files_impl =
{
let ext_cx = &*cx;
::quasi::parse_item_panic(&mut ::syntax::parse::new_parser_from_tts(ext_cx.parse_sess(),
ext_cx.cfg(),
{
#[allow(unused_imports)]
use quasi::IntoWrappedIterator;
#[allow(unused_imports)]
use quasi::IntoWrappedRepeat;
let _sp =
ext_cx.call_site();
let mut tt =
::std::vec::Vec::new();
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("impl"))));
tt.extend(::quasi::ToTokens::to_tokens(&type_name,
ext_cx).into_iter());
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::OpenDelim(::syntax::parse::token::Brace)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("fn"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("files"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::RArrow));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::ModSep));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("std"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::ModSep));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("collections"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::ModSep));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("HashMap"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Lt));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::BinOp(::syntax::parse::token::And)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Lifetime(ext_cx.ident_of("\'static"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("str"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Comma));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("File"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Gt));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::OpenDelim(::syntax::parse::token::Brace)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("let"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("mut"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("files"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Eq));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::ModSep));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("std"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::ModSep));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("collections"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::ModSep));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("HashMap"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::ModSep));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("new"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::OpenDelim(::syntax::parse::token::Paren)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::CloseDelim(::syntax::parse::token::Paren)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Semi));
tt.extend(::quasi::ToTokens::to_tokens(&statements,
ext_cx).into_iter());
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::Ident(ext_cx.ident_of("files"))));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::CloseDelim(::syntax::parse::token::Brace)));
tt.push(::syntax::ast::TokenTree::Token(_sp,
::syntax::parse::token::CloseDelim(::syntax::parse::token::Brace)));
tt
}))
}.unwrap();
push(Annotatable::Item(files_impl));
}
fn extract_path(cx: &ExtCtxt, item: &Item) -> String {
for meta_items in item.attrs().iter().filter_map(webapp_meta_items) {
for meta_item in meta_items {
match meta_item.node {
ast::MetaItemKind::NameValue(ref name, ref lit) if
name == &"path" => {
if let Some(s) = get_str_from_lit(cx, name, lit) {
return s.deref().to_owned();
}
}
_ => { }
}
}
}
"web".to_owned()
}
fn get_str_from_lit(cx: &ExtCtxt, name: &str, lit: &ast::Lit)
-> Option<InternedString> {
match lit.node {
ast::LitKind::Str(ref s, _) => Some(s.clone()),
_ => {
cx.span_err(lit.span,
&format!("webapp annotation `{}` must be a string, not `{}`"
, name , lit_to_string ( lit )));
return None;
}
}
}
fn webapp_meta_items(attr: &ast::Attribute)
-> Option<&[P<ast::MetaItem>]> {
match attr.node.value.node {
ast::MetaItemKind::List(ref name, ref items) if name == &"webapp"
=> {
attr::mark_used(&attr);
Some(items)
}
_ => None,
}
}
fn as_uri(path: &Path) -> String {
let mut s = String::new();
for component in path.iter() {
s.push_str(component.to_str().expect("Only UTF-8 filenames are supported."));
s.push('/');
}
s[0..s.len() - 1].into()
}
#[test]
fn should_convert_path_separators_on_all_platforms() {
let p =
{
let mut p = PathBuf::new();
p.push("web");
p.push("src");
p.push("index.html");
p
};
let path = as_uri(&p);
assert_eq!(path , "web/src/index.html" . to_owned ( ));
}
}
mod build {
#[cfg(feature = "with-syntex")]
pub mod inner {
use syntex;
use codegen;
use syntax::{ast, fold};
use std::env;
use std::path::Path;
fn strip_attributes(krate: ast::Crate) -> ast::Crate {
struct StripAttributeFolder;
impl fold::Folder for StripAttributeFolder {
fn fold_attribute(&mut self, attr: ast::Attribute)
-> Option<ast::Attribute> {
match attr.node.value.node {
ast::MetaItemKind::List(ref n, _) if n == &"webapp" =>
{
return None;
}
_ => { }
}
Some(attr)
}
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
fold::noop_fold_mac(mac, self)
}
}
fold::Folder::fold_crate(&mut StripAttributeFolder, krate)
}
pub fn register(reg: &mut syntex::Registry) {
reg.add_attr("feature(custom_derive)");
reg.add_attr("feature(custom_attribute)");
reg.add_decorator("derive_WebAppFiles",
codegen::expand_webapp_implementation);
reg.add_post_expansion_pass(strip_attributes);
}
pub fn generate() {
let out_dir = env::var_os("OUT_DIR").unwrap();
let mut registry = syntex::Registry::new();
register(&mut registry);
let src = Path::new("src/lib.rs.in");
let dst = Path::new(&out_dir).join("lib.rs");
registry.expand("", &src, &dst).unwrap();
}
}
#[cfg(not(feature = "with-syntex"))]
pub mod inner {
use codegen;
pub fn register(reg: &mut rustc_plugin::Registry) {
reg.register_syntax_extension(syntax::parse::token::intern("derive_WebAppFiles"),
syntax::ext::base::MultiDecorator(Box::new(codegen::expand_webapp_implementation)));
reg.register_attribute("webapp".to_owned(),
AttributeType::Normal);
}
pub fn generate() { }
}
}
pub mod js {
#![cfg_attr(feature = "use-precompiled-js", allow(dead_code))]
#![cfg_attr(feature = "use-precompiled-js", allow(unused_imports))]
use std::fmt;
use std::process::Command;
#[cfg(not(windows))]
mod platform {
use std::process::Command;
pub static NPM_CMD: &'static str = "npm";
pub fn handle_fd(cmd: &mut Command) -> &mut Command { cmd }
}
#[cfg(windows)]
mod platform {
use std::process::{Command, Stdio};
pub static NPM_CMD: &'static str = "npm.cmd";
pub fn handle_fd(cmd: &mut Command) -> &mut Command {
cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null())
}
}
fn die<T: fmt::Debug>(s: &'static str, e: T) -> ! {
panic!("Error: {}: {:?}" , s , e);
}
#[cfg(feature = "use-precompiled-js")]
pub fn test(_path: &str) { }
#[cfg(feature = "use-precompiled-js")]
pub fn build(_path: &str, _dest: &str) { }
#[cfg(not(feature = "use-precompiled-js"))]
pub fn build(path: &str, dest: &str) {
let child =
platform::handle_fd(&mut Command::new(platform::NPM_CMD)).arg("install").arg("--no-progress").current_dir(path).status().unwrap_or_else(|e|
die("Installing node.js dependencies with npm",
e));
assert!(child . success ( ) ,
"There was an error installing dependencies.");
let child =
platform::handle_fd(&mut Command::new(platform::NPM_CMD)).arg("run").arg("build").env("NODE_ENV",
"production").env("BUILD_DEST",
dest).current_dir(path).status().unwrap_or_else(|e|
die("Building JS code",
e));
assert!(child . success ( ) , "There was an error build JS code.");
}
#[cfg(not(feature = "use-precompiled-js"))]
pub fn test(path: &str) {
let child =
Command::new(platform::NPM_CMD).arg("run").arg("test").current_dir(path).status().unwrap_or_else(|e|
die("Running test command",
e));
assert!(child . success ( ) ,
"There was an error while running JS tests.");
}
}
pub use build::inner::generate;
use std::default::Default;
#[derive(Clone)]
pub struct File {
pub path: &'static str,
pub content: &'static [u8],
pub content_type: &'static str,
}
#[derive(Debug, Clone)]
pub struct Info {
pub name: &'static str,
pub version: &'static str,
pub author: &'static str,
pub description: &'static str,
pub icon_url: &'static str,
}
pub trait WebApp: Default + Send + Sync {
fn file(&self, path: &str)
-> Option<&File>;
fn info(&self)
-> Info;
}