2 use syntax_pos::{self, Pos, Span, FileName};
5 use ext::build::AstBuilder;
6 use parse::{token, DirectoryOwnership};
10 use smallvec::SmallVec;
15 use std::io::ErrorKind;
16 use std::path::PathBuf;
17 use rustc_data_structures::sync::Lrc;
19 // These macros all relate to the file system; they either return
20 // the column/row/filename of the expression, or they include
21 // a given file into the current one.
23 /// line!(): expands to the current line number
24 pub fn expand_line(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
25 -> Box<dyn base::MacResult+'static> {
26 base::check_zero_tts(cx, sp, tts, "line!");
28 let topmost = cx.expansion_cause().unwrap_or(sp);
29 let loc = cx.source_map().lookup_char_pos(topmost.lo());
31 base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32))
34 /* column!(): expands to the current column number */
35 pub fn expand_column(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
36 -> Box<dyn base::MacResult+'static> {
37 base::check_zero_tts(cx, sp, tts, "column!");
39 let topmost = cx.expansion_cause().unwrap_or(sp);
40 let loc = cx.source_map().lookup_char_pos(topmost.lo());
42 base::MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32 + 1))
45 /* __rust_unstable_column!(): expands to the current column number */
46 pub fn expand_column_gated(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
47 -> Box<dyn base::MacResult+'static> {
48 if sp.allows_unstable() {
49 expand_column(cx, sp, tts)
51 cx.span_fatal(sp, "the __rust_unstable_column macro is unstable");
55 /// file!(): expands to the current filename */
56 /// The source_file (`loc.file`) contains a bunch more information we could spit
58 pub fn expand_file(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
59 -> Box<dyn base::MacResult+'static> {
60 base::check_zero_tts(cx, sp, tts, "file!");
62 let topmost = cx.expansion_cause().unwrap_or(sp);
63 let loc = cx.source_map().lookup_char_pos(topmost.lo());
64 base::MacEager::expr(cx.expr_str(topmost, Symbol::intern(&loc.file.name.to_string())))
67 pub fn expand_stringify(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
68 -> Box<dyn base::MacResult+'static> {
69 let s = pprust::tts_to_string(tts);
70 base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&s)))
73 pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
74 -> Box<dyn base::MacResult+'static> {
75 base::check_zero_tts(cx, sp, tts, "module_path!");
76 let mod_path = &cx.current_expansion.module.mod_path;
77 let string = mod_path.iter().map(|x| x.to_string()).collect::<Vec<String>>().join("::");
79 base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&string)))
82 /// include! : parse the given file as an expr
83 /// This is generally a bad idea because it's going to behave
85 pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
86 -> Box<dyn base::MacResult+'cx> {
87 let file = match get_single_str_from_tts(cx, sp, tts, "include!") {
89 None => return DummyResult::expr(sp),
91 // The file will be added to the code map by the parser
92 let path = res_rel_file(cx, sp, file);
93 let directory_ownership = DirectoryOwnership::Owned { relative: None };
94 let p = parse::new_sub_parser_from_file(cx.parse_sess(), &path, directory_ownership, None, sp);
96 struct ExpandResult<'a> {
97 p: parse::parser::Parser<'a>,
99 impl<'a> base::MacResult for ExpandResult<'a> {
100 fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
101 Some(panictry!(self.p.parse_expr()))
104 fn make_items(mut self: Box<ExpandResult<'a>>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
105 let mut ret = SmallVec::new();
106 while self.p.token != token::Eof {
107 match panictry!(self.p.parse_item()) {
108 Some(item) => ret.push(item),
109 None => self.p.diagnostic().span_fatal(self.p.span,
110 &format!("expected item, found `{}`",
111 self.p.this_token_to_string()))
119 Box::new(ExpandResult { p })
122 // include_str! : read the given file, insert it as a literal string expr
123 pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
124 -> Box<dyn base::MacResult+'static> {
125 let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") {
127 None => return DummyResult::expr(sp)
129 let file = res_rel_file(cx, sp, file);
130 match fs::read_to_string(&file) {
132 let interned_src = Symbol::intern(&src);
134 // Add this input file to the code map to make it available as
135 // dependency information
136 cx.source_map().new_source_file(file.into(), src);
138 base::MacEager::expr(cx.expr_str(sp, interned_src))
140 Err(ref e) if e.kind() == ErrorKind::InvalidData => {
141 cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
142 DummyResult::expr(sp)
145 cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
146 DummyResult::expr(sp)
151 pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
152 -> Box<dyn base::MacResult+'static> {
153 let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") {
155 None => return DummyResult::expr(sp)
157 let file = res_rel_file(cx, sp, file);
158 match fs::read(&file) {
160 // Add the contents to the source map if it contains UTF-8.
161 let (contents, bytes) = match String::from_utf8(bytes) {
163 let bytes = s.as_bytes().to_owned();
166 Err(e) => (String::new(), e.into_bytes()),
168 cx.source_map().new_source_file(file.into(), contents);
170 base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes))))
173 cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
174 DummyResult::expr(sp)
179 // resolve a file-system path to an absolute file-system path (if it
181 fn res_rel_file(cx: &mut ExtCtxt, sp: syntax_pos::Span, arg: String) -> PathBuf {
182 let arg = PathBuf::from(arg);
183 // Relative paths are resolved relative to the file in which they are found
184 // after macro expansion (that is, they are unhygienic).
185 if !arg.is_absolute() {
186 let callsite = sp.source_callsite();
187 let mut path = match cx.source_map().span_to_unmapped_path(callsite) {
188 FileName::Real(path) => path,
189 FileName::DocTest(path, _) => path,
190 other => panic!("cannot resolve relative path in non-file source `{}`", other),