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.
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.
12 use codemap::{Pos, Span};
16 use ext::build::AstBuilder;
21 use util::small_vector::SmallVector;
24 use std::io::prelude::*;
25 use std::path::{Path, PathBuf};
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.
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!");
37 let topmost = cx.expansion_cause();
38 let loc = cx.codemap().lookup_char_pos(topmost.lo);
40 base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32))
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!");
48 let topmost = cx.expansion_cause();
49 let loc = cx.codemap().lookup_char_pos(topmost.lo);
51 base::MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32))
54 /// file!(): expands to the current filename */
55 /// The filemap (`loc.file`) contains a bunch more information we could spit
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!");
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))
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[..])))
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()
79 .map(|x| x.to_string())
80 .collect::<Vec<String>>()
82 base::MacEager::expr(cx.expr_str(
84 token::intern_and_get_ident(&string[..])))
87 /// include! : parse the given file as an expr
88 /// This is generally a bad idea because it's going to behave
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!") {
94 None => return DummyResult::expr(sp),
96 // The file will be added to the code map by the parser
98 parse::new_sub_parser_from_file(cx.parse_sess(),
107 struct ExpandResult<'a> {
108 p: parse::parser::Parser<'a>,
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()))
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())))
129 Box::new(ExpandResult { p: p })
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!") {
137 None => return DummyResult::expr(sp)
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)) {
145 &format!("couldn't read {}: {}",
148 return DummyResult::expr(sp);
151 match String::from_utf8(bytes) {
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);
159 base::MacEager::expr(cx.expr_str(sp, interned))
163 &format!("{} wasn't a utf-8 file",
165 return DummyResult::expr(sp);
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!") {
174 None => return DummyResult::expr(sp)
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)) {
181 &format!("couldn't read {}: {}", file.display(), e));
182 return DummyResult::expr(sp);
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, "");
190 base::MacEager::expr(cx.expr_lit(sp, ast::LitByteStr(Rc::new(bytes))))
195 // resolve a file-system path to an absolute file-system path (if it
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));