]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/source_util.rs
Auto merge of #56487 - nikic:discard-modules-earlier, r=alexcrichton
[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 syntax_pos::{self, Pos, Span, FileName};
13 use ext::base::*;
14 use ext::base;
15 use ext::build::AstBuilder;
16 use parse::{token, DirectoryOwnership};
17 use parse;
18 use print::pprust;
19 use ptr::P;
20 use smallvec::SmallVec;
21 use symbol::Symbol;
22 use tokenstream;
23
24 use std::fs::File;
25 use std::io::prelude::*;
26 use std::path::PathBuf;
27 use rustc_data_structures::sync::Lrc;
28
29 // These macros all relate to the file system; they either return
30 // the column/row/filename of the expression, or they include
31 // a given file into the current one.
32
33 /// line!(): expands to the current line number
34 pub fn expand_line(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
35                    -> Box<dyn base::MacResult+'static> {
36     base::check_zero_tts(cx, sp, tts, "line!");
37
38     let topmost = cx.expansion_cause().unwrap_or(sp);
39     let loc = cx.source_map().lookup_char_pos(topmost.lo());
40
41     base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32))
42 }
43
44 /* column!(): expands to the current column number */
45 pub fn expand_column(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
46                   -> Box<dyn base::MacResult+'static> {
47     base::check_zero_tts(cx, sp, tts, "column!");
48
49     let topmost = cx.expansion_cause().unwrap_or(sp);
50     let loc = cx.source_map().lookup_char_pos(topmost.lo());
51
52     base::MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32 + 1))
53 }
54
55 /* __rust_unstable_column!(): expands to the current column number */
56 pub fn expand_column_gated(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
57                   -> Box<dyn base::MacResult+'static> {
58     if sp.allows_unstable() {
59         expand_column(cx, sp, tts)
60     } else {
61         cx.span_fatal(sp, "the __rust_unstable_column macro is unstable");
62     }
63 }
64
65 /// file!(): expands to the current filename */
66 /// The source_file (`loc.file`) contains a bunch more information we could spit
67 /// out if we wanted.
68 pub fn expand_file(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
69                    -> Box<dyn base::MacResult+'static> {
70     base::check_zero_tts(cx, sp, tts, "file!");
71
72     let topmost = cx.expansion_cause().unwrap_or(sp);
73     let loc = cx.source_map().lookup_char_pos(topmost.lo());
74     base::MacEager::expr(cx.expr_str(topmost, Symbol::intern(&loc.file.name.to_string())))
75 }
76
77 pub fn expand_stringify(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
78                         -> Box<dyn base::MacResult+'static> {
79     let s = pprust::tts_to_string(tts);
80     base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&s)))
81 }
82
83 pub fn expand_mod(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
84                   -> Box<dyn base::MacResult+'static> {
85     base::check_zero_tts(cx, sp, tts, "module_path!");
86     let mod_path = &cx.current_expansion.module.mod_path;
87     let string = mod_path.iter().map(|x| x.to_string()).collect::<Vec<String>>().join("::");
88
89     base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&string)))
90 }
91
92 /// include! : parse the given file as an expr
93 /// This is generally a bad idea because it's going to behave
94 /// unhygienically.
95 pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
96                            -> Box<dyn base::MacResult+'cx> {
97     let file = match get_single_str_from_tts(cx, sp, tts, "include!") {
98         Some(f) => f,
99         None => return DummyResult::expr(sp),
100     };
101     // The file will be added to the code map by the parser
102     let path = res_rel_file(cx, sp, file);
103     let directory_ownership = DirectoryOwnership::Owned { relative: None };
104     let p = parse::new_sub_parser_from_file(cx.parse_sess(), &path, directory_ownership, None, sp);
105
106     struct ExpandResult<'a> {
107         p: parse::parser::Parser<'a>,
108     }
109     impl<'a> base::MacResult for ExpandResult<'a> {
110         fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
111             Some(panictry!(self.p.parse_expr()))
112         }
113
114         fn make_items(mut self: Box<ExpandResult<'a>>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
115             let mut ret = SmallVec::new();
116             while self.p.token != token::Eof {
117                 match panictry!(self.p.parse_item()) {
118                     Some(item) => ret.push(item),
119                     None => self.p.diagnostic().span_fatal(self.p.span,
120                                                            &format!("expected item, found `{}`",
121                                                                     self.p.this_token_to_string()))
122                                                .raise()
123                 }
124             }
125             Some(ret)
126         }
127     }
128
129     Box::new(ExpandResult { 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: &[tokenstream::TokenTree])
134                           -> Box<dyn 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, 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             let interned_src = Symbol::intern(&src);
154
155             // Add this input file to the code map to make it available as
156             // dependency information
157             cx.source_map().new_source_file(file.into(), src);
158
159             base::MacEager::expr(cx.expr_str(sp, interned_src))
160         }
161         Err(_) => {
162             cx.span_err(sp,
163                         &format!("{} wasn't a utf-8 file",
164                                 file.display()));
165             DummyResult::expr(sp)
166         }
167     }
168 }
169
170 pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
171                             -> Box<dyn 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, 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             DummyResult::expr(sp)
183         }
184         Ok(..) => {
185             let src = match String::from_utf8(bytes.clone()) {
186                 Ok(contents) => contents,
187                 Err(..) => "".to_string()
188             };
189
190             cx.source_map().new_source_file(file.into(), src);
191
192             base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes))))
193         }
194     }
195 }
196
197 // resolve a file-system path to an absolute file-system path (if it
198 // isn't already)
199 fn res_rel_file(cx: &mut ExtCtxt, sp: syntax_pos::Span, arg: String) -> PathBuf {
200     let arg = PathBuf::from(arg);
201     // Relative paths are resolved relative to the file in which they are found
202     // after macro expansion (that is, they are unhygienic).
203     if !arg.is_absolute() {
204         let callsite = sp.source_callsite();
205         let mut path = match cx.source_map().span_to_unmapped_path(callsite) {
206             FileName::Real(path) => path,
207             FileName::DocTest(path, _) => path,
208             other => panic!("cannot resolve relative path in non-file source `{}`", other),
209         };
210         path.pop();
211         path.push(arg);
212         path
213     } else {
214         arg
215     }
216 }