]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/source_util.rs
Auto merge of #57145 - RalfJung:panic-if-uninhabited, r=alexcrichton
[rust.git] / src / libsyntax / ext / source_util.rs
1 use ast;
2 use syntax_pos::{self, Pos, Span, FileName};
3 use ext::base::*;
4 use ext::base;
5 use ext::build::AstBuilder;
6 use parse::{token, DirectoryOwnership};
7 use parse;
8 use print::pprust;
9 use ptr::P;
10 use smallvec::SmallVec;
11 use symbol::Symbol;
12 use tokenstream;
13
14 use std::fs;
15 use std::io::ErrorKind;
16 use std::path::PathBuf;
17 use rustc_data_structures::sync::Lrc;
18
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.
22
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!");
27
28     let topmost = cx.expansion_cause().unwrap_or(sp);
29     let loc = cx.source_map().lookup_char_pos(topmost.lo());
30
31     base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32))
32 }
33
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!");
38
39     let topmost = cx.expansion_cause().unwrap_or(sp);
40     let loc = cx.source_map().lookup_char_pos(topmost.lo());
41
42     base::MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32 + 1))
43 }
44
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)
50     } else {
51         cx.span_fatal(sp, "the __rust_unstable_column macro is unstable");
52     }
53 }
54
55 /// file!(): expands to the current filename */
56 /// The source_file (`loc.file`) contains a bunch more information we could spit
57 /// out if we wanted.
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!");
61
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())))
65 }
66
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)))
71 }
72
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("::");
78
79     base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&string)))
80 }
81
82 /// include! : parse the given file as an expr
83 /// This is generally a bad idea because it's going to behave
84 /// unhygienically.
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!") {
88         Some(f) => f,
89         None => return DummyResult::any(sp),
90     };
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);
95
96     struct ExpandResult<'a> {
97         p: parse::parser::Parser<'a>,
98     }
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()))
102         }
103
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()))
112                                                .raise()
113                 }
114             }
115             Some(ret)
116         }
117     }
118
119     Box::new(ExpandResult { p })
120 }
121
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!") {
126         Some(f) => f,
127         None => return DummyResult::expr(sp)
128     };
129     let file = res_rel_file(cx, sp, file);
130     match fs::read_to_string(&file) {
131         Ok(src) => {
132             let interned_src = Symbol::intern(&src);
133
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);
137
138             base::MacEager::expr(cx.expr_str(sp, interned_src))
139         },
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)
143         }
144         Err(e) => {
145             cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
146             DummyResult::expr(sp)
147         }
148     }
149 }
150
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!") {
154         Some(f) => f,
155         None => return DummyResult::expr(sp)
156     };
157     let file = res_rel_file(cx, sp, file);
158     match fs::read(&file) {
159         Ok(bytes) => {
160             // Add the contents to the source map if it contains UTF-8.
161             let (contents, bytes) = match String::from_utf8(bytes) {
162                 Ok(s) => {
163                     let bytes = s.as_bytes().to_owned();
164                     (s, bytes)
165                 },
166                 Err(e) => (String::new(), e.into_bytes()),
167             };
168             cx.source_map().new_source_file(file.into(), contents);
169
170             base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes))))
171         },
172         Err(e) => {
173             cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
174             DummyResult::expr(sp)
175         }
176     }
177 }
178
179 // resolve a file-system path to an absolute file-system path (if it
180 // isn't already)
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),
191         };
192         path.pop();
193         path.push(arg);
194         path
195     } else {
196         arg
197     }
198 }