]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/source_util.rs
librustc: Fix merge fallout.
[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;
13 use codemap::{Pos, Span};
14 use codemap::{ExpnInfo, NameAndSpan};
15 use ext::base::*;
16 use ext::base;
17 use ext::build::AstBuilder;
18 use parse;
19 use parse::token::get_ident_interner;
20 use parse::token;
21 use print::pprust;
22
23 use std::io;
24 use std::io::File;
25 use std::str;
26
27 // These macros all relate to the file system; they either return
28 // the column/row/filename of the expression, or they include
29 // a given file into the current one.
30
31 /* line!(): expands to the current line number */
32 pub fn expand_line(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
33     -> base::MacResult {
34     base::check_zero_tts(cx, sp, tts, "line!");
35
36     let topmost = topmost_expn_info(cx.backtrace().unwrap());
37     let loc = cx.codemap().lookup_char_pos(topmost.call_site.lo);
38
39     base::MRExpr(cx.expr_uint(topmost.call_site, loc.line))
40 }
41
42 /* col!(): expands to the current column number */
43 pub fn expand_col(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
44     -> base::MacResult {
45     base::check_zero_tts(cx, sp, tts, "col!");
46
47     let topmost = topmost_expn_info(cx.backtrace().unwrap());
48     let loc = cx.codemap().lookup_char_pos(topmost.call_site.lo);
49     base::MRExpr(cx.expr_uint(topmost.call_site, loc.col.to_uint()))
50 }
51
52 /* file!(): expands to the current filename */
53 /* The filemap (`loc.file`) contains a bunch more information we could spit
54  * out if we wanted. */
55 pub fn expand_file(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
56     -> base::MacResult {
57     base::check_zero_tts(cx, sp, tts, "file!");
58
59     let topmost = topmost_expn_info(cx.backtrace().unwrap());
60     let loc = cx.codemap().lookup_char_pos(topmost.call_site.lo);
61     let filename = token::intern_and_get_ident(loc.file.name);
62     base::MRExpr(cx.expr_str(topmost.call_site, filename))
63 }
64
65 pub fn expand_stringify(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
66     -> base::MacResult {
67     let s = pprust::tts_to_str(tts, get_ident_interner());
68     base::MRExpr(cx.expr_str(sp, token::intern_and_get_ident(s)))
69 }
70
71 pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
72     -> base::MacResult {
73     base::check_zero_tts(cx, sp, tts, "module_path!");
74     let string = cx.mod_path()
75                    .map(|x| {
76                         let interned_str = token::get_ident(x.name);
77                         interned_str.get().to_str()
78                     })
79                    .connect("::");
80     base::MRExpr(cx.expr_str(sp, token::intern_and_get_ident(string)))
81 }
82
83 // include! : parse the given file as an expr
84 // This is generally a bad idea because it's going to behave
85 // unhygienically.
86 pub fn expand_include(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
87     -> base::MacResult {
88     let file = match get_single_str_from_tts(cx, sp, tts, "include!") {
89         Some(f) => f,
90         None => return MacResult::dummy_expr(),
91     };
92     // The file will be added to the code map by the parser
93     let mut p =
94         parse::new_sub_parser_from_file(cx.parse_sess(),
95                                         cx.cfg(),
96                                         &res_rel_file(cx,
97                                                       sp,
98                                                       &Path::new(file)),
99                                         sp);
100     base::MRExpr(p.parse_expr())
101 }
102
103 // include_str! : read the given file, insert it as a literal string expr
104 pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
105     -> base::MacResult {
106     let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") {
107         Some(f) => f,
108         None => return MacResult::dummy_expr()
109     };
110     let file = res_rel_file(cx, sp, &Path::new(file));
111     let bytes = match io::result(|| File::open(&file).read_to_end()) {
112         Err(e) => {
113             cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e.desc));
114             return MacResult::dummy_expr();
115         }
116         Ok(bytes) => bytes,
117     };
118     match str::from_utf8_owned(bytes) {
119         Some(src) => {
120             // Add this input file to the code map to make it available as
121             // dependency information
122             let filename = file.display().to_str();
123             let interned = token::intern_and_get_ident(src);
124             cx.parse_sess.cm.new_filemap(filename, src);
125
126             base::MRExpr(cx.expr_str(sp, interned))
127         }
128         None => {
129             cx.span_err(sp, format!("{} wasn't a utf-8 file", file.display()));
130             return MacResult::dummy_expr();
131         }
132     }
133 }
134
135 pub fn expand_include_bin(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
136         -> base::MacResult
137 {
138     use std::at_vec;
139
140     let file = match get_single_str_from_tts(cx, sp, tts, "include_bin!") {
141         Some(f) => f,
142         None => return MacResult::dummy_expr()
143     };
144     let file = res_rel_file(cx, sp, &Path::new(file));
145     match io::result(|| File::open(&file).read_to_end()) {
146         Err(e) => {
147             cx.span_err(sp, format!("couldn't read {}: {}", file.display(), e.desc));
148             return MacResult::dummy_expr();
149         }
150         Ok(bytes) => {
151             let bytes = at_vec::to_managed_move(bytes);
152             base::MRExpr(cx.expr_lit(sp, ast::LitBinary(bytes)))
153         }
154     }
155 }
156
157 // recur along an ExpnInfo chain to find the original expression
158 fn topmost_expn_info(expn_info: @codemap::ExpnInfo) -> @codemap::ExpnInfo {
159     match *expn_info {
160         ExpnInfo { call_site: ref call_site, .. } => {
161             match call_site.expn_info {
162                 Some(next_expn_info) => {
163                     match *next_expn_info {
164                         ExpnInfo {
165                             callee: NameAndSpan { name: ref name, .. },
166                             ..
167                         } => {
168                             // Don't recurse into file using "include!"
169                             if "include" == *name  {
170                                 expn_info
171                             } else {
172                                 topmost_expn_info(next_expn_info)
173                             }
174                         }
175                     }
176                 },
177                 None => expn_info
178             }
179         }
180     }
181 }
182
183 // resolve a file-system path to an absolute file-system path (if it
184 // isn't already)
185 fn res_rel_file(cx: &mut ExtCtxt, sp: codemap::Span, arg: &Path) -> Path {
186     // NB: relative paths are resolved relative to the compilation unit
187     if !arg.is_absolute() {
188         let mut cu = Path::new(cx.codemap().span_to_filename(sp));
189         cu.pop();
190         cu.push(arg);
191         cu
192     } else {
193         arg.clone()
194     }
195 }