]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/source_util.rs
[breaking-change] don't glob export ast::Expr_ variants
[rust.git] / src / libsyntax / ext / source_util.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use ast;
12 use codemap::{Pos, Span};
13 use codemap;
14 use ext::base::*;
15 use ext::base;
16 use ext::build::AstBuilder;
17 use parse::token;
18 use parse;
19 use print::pprust;
20 use ptr::P;
21 use util::small_vector::SmallVector;
22
23 use std::fs::File;
24 use std::io::prelude::*;
25 use std::path::{Path, PathBuf};
26 use std::rc::Rc;
27
28 // These macros all relate to the file system; they either return
29 // the column/row/filename of the expression, or they include
30 // a given file into the current one.
31
32 /// line!(): expands to the current line number
33 pub fn expand_line(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
34                    -> Box<base::MacResult+'static> {
35     base::check_zero_tts(cx, sp, tts, "line!");
36
37     let topmost = cx.expansion_cause();
38     let loc = cx.codemap().lookup_char_pos(topmost.lo);
39
40     base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32))
41 }
42
43 /* column!(): expands to the current column number */
44 pub fn expand_column(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
45                   -> Box<base::MacResult+'static> {
46     base::check_zero_tts(cx, sp, tts, "column!");
47
48     let topmost = cx.expansion_cause();
49     let loc = cx.codemap().lookup_char_pos(topmost.lo);
50
51     base::MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32))
52 }
53
54 /// file!(): expands to the current filename */
55 /// The filemap (`loc.file`) contains a bunch more information we could spit
56 /// out if we wanted.
57 pub fn expand_file(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
58                    -> Box<base::MacResult+'static> {
59     base::check_zero_tts(cx, sp, tts, "file!");
60
61     let topmost = cx.expansion_cause();
62     let loc = cx.codemap().lookup_char_pos(topmost.lo);
63     let filename = token::intern_and_get_ident(&loc.file.name);
64     base::MacEager::expr(cx.expr_str(topmost, filename))
65 }
66
67 pub fn expand_stringify(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
68                         -> Box<base::MacResult+'static> {
69     let s = pprust::tts_to_string(tts);
70     base::MacEager::expr(cx.expr_str(sp,
71                                    token::intern_and_get_ident(&s[..])))
72 }
73
74 pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
75                   -> Box<base::MacResult+'static> {
76     base::check_zero_tts(cx, sp, tts, "module_path!");
77     let string = cx.mod_path()
78                    .iter()
79                    .map(|x| x.to_string())
80                    .collect::<Vec<String>>()
81                    .join("::");
82     base::MacEager::expr(cx.expr_str(
83             sp,
84             token::intern_and_get_ident(&string[..])))
85 }
86
87 /// include! : parse the given file as an expr
88 /// This is generally a bad idea because it's going to behave
89 /// unhygienically.
90 pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
91                            -> Box<base::MacResult+'cx> {
92     let file = match get_single_str_from_tts(cx, sp, tts, "include!") {
93         Some(f) => f,
94         None => return DummyResult::expr(sp),
95     };
96     // The file will be added to the code map by the parser
97     let p =
98         parse::new_sub_parser_from_file(cx.parse_sess(),
99                                         cx.cfg(),
100                                         &res_rel_file(cx,
101                                                       sp,
102                                                       Path::new(&file)),
103                                         true,
104                                         None,
105                                         sp);
106
107     struct ExpandResult<'a> {
108         p: parse::parser::Parser<'a>,
109     }
110     impl<'a> base::MacResult for ExpandResult<'a> {
111         fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
112             Some(panictry!(self.p.parse_expr()))
113         }
114         fn make_items(mut self: Box<ExpandResult<'a>>)
115                       -> Option<SmallVector<P<ast::Item>>> {
116             let mut ret = SmallVector::zero();
117             while self.p.token != token::Eof {
118                 match panictry!(self.p.parse_item()) {
119                     Some(item) => ret.push(item),
120                     None => panic!(self.p.diagnostic().span_fatal(self.p.span,
121                                                            &format!("expected item, found `{}`",
122                                                                     self.p.this_token_to_string())))
123                 }
124             }
125             Some(ret)
126         }
127     }
128
129     Box::new(ExpandResult { p: p })
130 }
131
132 // include_str! : read the given file, insert it as a literal string expr
133 pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
134                           -> Box<base::MacResult+'static> {
135     let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") {
136         Some(f) => f,
137         None => return DummyResult::expr(sp)
138     };
139     let file = res_rel_file(cx, sp, Path::new(&file));
140     let mut bytes = Vec::new();
141     match File::open(&file).and_then(|mut f| f.read_to_end(&mut bytes)) {
142         Ok(..) => {}
143         Err(e) => {
144             cx.span_err(sp,
145                         &format!("couldn't read {}: {}",
146                                 file.display(),
147                                 e));
148             return DummyResult::expr(sp);
149         }
150     };
151     match String::from_utf8(bytes) {
152         Ok(src) => {
153             // Add this input file to the code map to make it available as
154             // dependency information
155             let filename = format!("{}", file.display());
156             let interned = token::intern_and_get_ident(&src[..]);
157             cx.codemap().new_filemap_and_lines(&filename, &src);
158
159             base::MacEager::expr(cx.expr_str(sp, interned))
160         }
161         Err(_) => {
162             cx.span_err(sp,
163                         &format!("{} wasn't a utf-8 file",
164                                 file.display()));
165             return DummyResult::expr(sp);
166         }
167     }
168 }
169
170 pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
171                             -> Box<base::MacResult+'static> {
172     let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") {
173         Some(f) => f,
174         None => return DummyResult::expr(sp)
175     };
176     let file = res_rel_file(cx, sp, Path::new(&file));
177     let mut bytes = Vec::new();
178     match File::open(&file).and_then(|mut f| f.read_to_end(&mut bytes)) {
179         Err(e) => {
180             cx.span_err(sp,
181                         &format!("couldn't read {}: {}", file.display(), e));
182             return DummyResult::expr(sp);
183         }
184         Ok(..) => {
185             // Add this input file to the code map to make it available as
186             // dependency information, but don't enter it's contents
187             let filename = format!("{}", file.display());
188             cx.codemap().new_filemap_and_lines(&filename, "");
189
190             base::MacEager::expr(cx.expr_lit(sp, ast::LitByteStr(Rc::new(bytes))))
191         }
192     }
193 }
194
195 // resolve a file-system path to an absolute file-system path (if it
196 // isn't already)
197 fn res_rel_file(cx: &mut ExtCtxt, sp: codemap::Span, arg: &Path) -> PathBuf {
198     // NB: relative paths are resolved relative to the compilation unit
199     if !arg.is_absolute() {
200         let mut cu = PathBuf::from(&cx.codemap().span_to_filename(sp));
201         cu.pop();
202         cu.push(arg);
203         cu
204     } else {
205         arg.to_path_buf()
206     }
207 }