]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/source_util.rs
auto merge of #19227 : johshoff/rust/master, r=brson
[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::io::File;
24 use std::rc::Rc;
25
26 // These macros all relate to the file system; they either return
27 // the column/row/filename of the expression, or they include
28 // a given file into the current one.
29
30 /// line!(): expands to the current line number
31 pub fn expand_line(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
32                    -> Box<base::MacResult+'static> {
33     base::check_zero_tts(cx, sp, tts, "line!");
34
35     let topmost = cx.original_span_in_file();
36     let loc = cx.codemap().lookup_char_pos(topmost.lo);
37
38     base::MacExpr::new(cx.expr_uint(topmost, loc.line))
39 }
40
41 /* column!(): expands to the current column number */
42 pub fn expand_column(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
43                   -> Box<base::MacResult+'static> {
44     base::check_zero_tts(cx, sp, tts, "column!");
45
46     let topmost = cx.original_span_in_file();
47     let loc = cx.codemap().lookup_char_pos(topmost.lo);
48     base::MacExpr::new(cx.expr_uint(topmost, loc.col.to_uint()))
49 }
50
51 /// file!(): expands to the current filename */
52 /// The filemap (`loc.file`) contains a bunch more information we could spit
53 /// out if we wanted.
54 pub fn expand_file(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
55                    -> Box<base::MacResult+'static> {
56     base::check_zero_tts(cx, sp, tts, "file!");
57
58     let topmost = cx.original_span_in_file();
59     let loc = cx.codemap().lookup_char_pos(topmost.lo);
60     let filename = token::intern_and_get_ident(loc.file.name[]);
61     base::MacExpr::new(cx.expr_str(topmost, filename))
62 }
63
64 pub fn expand_stringify(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
65                         -> Box<base::MacResult+'static> {
66     let s = pprust::tts_to_string(tts);
67     base::MacExpr::new(cx.expr_str(sp,
68                                    token::intern_and_get_ident(s[])))
69 }
70
71 pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
72                   -> Box<base::MacResult+'static> {
73     base::check_zero_tts(cx, sp, tts, "module_path!");
74     let string = cx.mod_path()
75                    .iter()
76                    .map(|x| token::get_ident(*x).get().to_string())
77                    .collect::<Vec<String>>()
78                    .connect("::");
79     base::MacExpr::new(cx.expr_str(
80             sp,
81             token::intern_and_get_ident(string[])))
82 }
83
84 /// include! : parse the given file as an expr
85 /// This is generally a bad idea because it's going to behave
86 /// unhygienically.
87 pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
88                            -> Box<base::MacResult+'cx> {
89     let file = match get_single_str_from_tts(cx, sp, tts, "include!") {
90         Some(f) => f,
91         None => return DummyResult::expr(sp),
92     };
93     // The file will be added to the code map by the parser
94     let p =
95         parse::new_sub_parser_from_file(cx.parse_sess(),
96                                         cx.cfg(),
97                                         &res_rel_file(cx,
98                                                       sp,
99                                                       &Path::new(file)),
100                                         true,
101                                         None,
102                                         sp);
103
104     struct ExpandResult<'a> {
105         p: parse::parser::Parser<'a>,
106     }
107     impl<'a> base::MacResult for ExpandResult<'a> {
108         fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
109             Some(self.p.parse_expr())
110         }
111         fn make_items(mut self: Box<ExpandResult<'a>>)
112                       -> Option<SmallVector<P<ast::Item>>> {
113             let mut ret = SmallVector::zero();
114             loop {
115                 match self.p.parse_item_with_outer_attributes() {
116                     Some(item) => ret.push(item),
117                     None => break
118                 }
119             }
120             Some(ret)
121         }
122     }
123
124     box ExpandResult { p: p }
125 }
126
127 // include_str! : read the given file, insert it as a literal string expr
128 pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
129                           -> Box<base::MacResult+'static> {
130     let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") {
131         Some(f) => f,
132         None => return DummyResult::expr(sp)
133     };
134     let file = res_rel_file(cx, sp, &Path::new(file));
135     let bytes = match File::open(&file).read_to_end() {
136         Err(e) => {
137             cx.span_err(sp,
138                         format!("couldn't read {}: {}",
139                                 file.display(),
140                                 e)[]);
141             return DummyResult::expr(sp);
142         }
143         Ok(bytes) => bytes,
144     };
145     match String::from_utf8(bytes) {
146         Ok(src) => {
147             // Add this input file to the code map to make it available as
148             // dependency information
149             let filename = file.display().to_string();
150             let interned = token::intern_and_get_ident(src[]);
151             cx.codemap().new_filemap(filename, src);
152
153             base::MacExpr::new(cx.expr_str(sp, interned))
154         }
155         Err(_) => {
156             cx.span_err(sp,
157                         format!("{} wasn't a utf-8 file",
158                                 file.display())[]);
159             return DummyResult::expr(sp);
160         }
161     }
162 }
163
164 pub fn expand_include_bin(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
165                           -> Box<base::MacResult+'static> {
166     cx.span_warn(sp, "include_bin! is deprecated; use include_bytes! instead");
167     expand_include_bytes(cx, sp, tts)
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     match File::open(&file).read_to_end() {
178         Err(e) => {
179             cx.span_err(sp,
180                         format!("couldn't read {}: {}", file.display(), e)[]);
181             return DummyResult::expr(sp);
182         }
183         Ok(bytes) => {
184             let bytes = bytes.iter().map(|x| *x).collect();
185             base::MacExpr::new(cx.expr_lit(sp, ast::LitBinary(Rc::new(bytes))))
186         }
187     }
188 }
189
190 // resolve a file-system path to an absolute file-system path (if it
191 // isn't already)
192 fn res_rel_file(cx: &mut ExtCtxt, sp: codemap::Span, arg: &Path) -> Path {
193     // NB: relative paths are resolved relative to the compilation unit
194     if !arg.is_absolute() {
195         let mut cu = Path::new(cx.codemap().span_to_filename(sp));
196         cu.pop();
197         cu.push(arg);
198         cu
199     } else {
200         arg.clone()
201     }
202 }