]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/source_util.rs
Simplify SaveHandler trait
[rust.git] / src / libsyntax / ext / source_util.rs
1 use crate::ast;
2 use crate::ext::base::{self, *};
3 use crate::ext::build::AstBuilder;
4 use crate::parse::{self, token, DirectoryOwnership};
5 use crate::print::pprust;
6 use crate::ptr::P;
7 use crate::symbol::Symbol;
8 use crate::tokenstream;
9
10 use smallvec::SmallVec;
11 use syntax_pos::{self, Pos, Span};
12
13 use std::fs;
14 use std::io::ErrorKind;
15 use rustc_data_structures::sync::Lrc;
16
17 // These macros all relate to the file system; they either return
18 // the column/row/filename of the expression, or they include
19 // a given file into the current one.
20
21 /// line!(): expands to the current line number
22 pub fn expand_line(cx: &mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
23                    -> Box<dyn base::MacResult+'static> {
24     base::check_zero_tts(cx, sp, tts, "line!");
25
26     let topmost = cx.expansion_cause().unwrap_or(sp);
27     let loc = cx.source_map().lookup_char_pos(topmost.lo());
28
29     base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32))
30 }
31
32 /* column!(): expands to the current column number */
33 pub fn expand_column(cx: &mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
34                   -> Box<dyn base::MacResult+'static> {
35     base::check_zero_tts(cx, sp, tts, "column!");
36
37     let topmost = cx.expansion_cause().unwrap_or(sp);
38     let loc = cx.source_map().lookup_char_pos(topmost.lo());
39
40     base::MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32 + 1))
41 }
42
43 /// file!(): expands to the current filename */
44 /// The source_file (`loc.file`) contains a bunch more information we could spit
45 /// out if we wanted.
46 pub fn expand_file(cx: &mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
47                    -> Box<dyn base::MacResult+'static> {
48     base::check_zero_tts(cx, sp, tts, "file!");
49
50     let topmost = cx.expansion_cause().unwrap_or(sp);
51     let loc = cx.source_map().lookup_char_pos(topmost.lo());
52     base::MacEager::expr(cx.expr_str(topmost, Symbol::intern(&loc.file.name.to_string())))
53 }
54
55 pub fn expand_stringify(cx: &mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
56                         -> Box<dyn base::MacResult+'static> {
57     let s = pprust::tts_to_string(tts);
58     base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&s)))
59 }
60
61 pub fn expand_mod(cx: &mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
62                   -> Box<dyn base::MacResult+'static> {
63     base::check_zero_tts(cx, sp, tts, "module_path!");
64     let mod_path = &cx.current_expansion.module.mod_path;
65     let string = mod_path.iter().map(|x| x.to_string()).collect::<Vec<String>>().join("::");
66
67     base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&string)))
68 }
69
70 /// include! : parse the given file as an expr
71 /// This is generally a bad idea because it's going to behave
72 /// unhygienically.
73 pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
74                            -> Box<dyn base::MacResult+'cx> {
75     let file = match get_single_str_from_tts(cx, sp, tts, "include!") {
76         Some(f) => f,
77         None => return DummyResult::any(sp),
78     };
79     // The file will be added to the code map by the parser
80     let file = cx.resolve_path(file, sp);
81     let directory_ownership = DirectoryOwnership::Owned { relative: None };
82     let p = parse::new_sub_parser_from_file(cx.parse_sess(), &file, directory_ownership, None, sp);
83
84     struct ExpandResult<'a> {
85         p: parse::parser::Parser<'a>,
86     }
87     impl<'a> base::MacResult for ExpandResult<'a> {
88         fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
89             Some(panictry!(self.p.parse_expr()))
90         }
91
92         fn make_items(mut self: Box<ExpandResult<'a>>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
93             let mut ret = SmallVec::new();
94             while self.p.token != token::Eof {
95                 match panictry!(self.p.parse_item()) {
96                     Some(item) => ret.push(item),
97                     None => self.p.diagnostic().span_fatal(self.p.token.span,
98                                                            &format!("expected item, found `{}`",
99                                                                     self.p.this_token_to_string()))
100                                                .raise()
101                 }
102             }
103             Some(ret)
104         }
105     }
106
107     Box::new(ExpandResult { p })
108 }
109
110 // include_str! : read the given file, insert it as a literal string expr
111 pub fn expand_include_str(cx: &mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
112                           -> Box<dyn base::MacResult+'static> {
113     let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") {
114         Some(f) => f,
115         None => return DummyResult::expr(sp)
116     };
117     let file = cx.resolve_path(file, sp);
118     match fs::read_to_string(&file) {
119         Ok(src) => {
120             let interned_src = Symbol::intern(&src);
121
122             // Add this input file to the code map to make it available as
123             // dependency information
124             cx.source_map().new_source_file(file.into(), src);
125
126             base::MacEager::expr(cx.expr_str(sp, interned_src))
127         },
128         Err(ref e) if e.kind() == ErrorKind::InvalidData => {
129             cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
130             DummyResult::expr(sp)
131         }
132         Err(e) => {
133             cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
134             DummyResult::expr(sp)
135         }
136     }
137 }
138
139 pub fn expand_include_bytes(cx: &mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
140                             -> Box<dyn base::MacResult+'static> {
141     let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") {
142         Some(f) => f,
143         None => return DummyResult::expr(sp)
144     };
145     let file = cx.resolve_path(file, sp);
146     match fs::read(&file) {
147         Ok(bytes) => {
148             // Add the contents to the source map if it contains UTF-8.
149             let (contents, bytes) = match String::from_utf8(bytes) {
150                 Ok(s) => {
151                     let bytes = s.as_bytes().to_owned();
152                     (s, bytes)
153                 },
154                 Err(e) => (String::new(), e.into_bytes()),
155             };
156             cx.source_map().new_source_file(file.into(), contents);
157
158             base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes))))
159         },
160         Err(e) => {
161             cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
162             DummyResult::expr(sp)
163         }
164     }
165 }