]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/source_util.rs
Auto merge of #66646 - RalfJung:unwind_to_block, r=oli-obk
[rust.git] / src / libsyntax_ext / source_util.rs
1 use rustc_parse::{self, DirectoryOwnership, new_sub_parser_from_file, parser::Parser};
2 use syntax::ast;
3 use syntax::print::pprust;
4 use syntax::ptr::P;
5 use syntax::symbol::Symbol;
6 use syntax::token;
7 use syntax::tokenstream::TokenStream;
8 use syntax::early_buffered_lints::BufferedEarlyLintId;
9 use syntax_expand::panictry;
10 use syntax_expand::base::{self, *};
11
12 use smallvec::SmallVec;
13 use syntax_pos::{self, Pos, Span};
14
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)
23                    -> Box<dyn base::MacResult+'static> {
24     let sp = cx.with_def_site_ctxt(sp);
25     base::check_zero_tts(cx, sp, tts, "line!");
26
27     let topmost = cx.expansion_cause().unwrap_or(sp);
28     let loc = cx.source_map().lookup_char_pos(topmost.lo());
29
30     base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32))
31 }
32
33 /* column!(): expands to the current column number */
34 pub fn expand_column(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
35                   -> Box<dyn base::MacResult+'static> {
36     let sp = cx.with_def_site_ctxt(sp);
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 /// file!(): expands to the current filename */
46 /// The source_file (`loc.file`) contains a bunch more information we could spit
47 /// out if we wanted.
48 pub fn expand_file(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
49                    -> Box<dyn base::MacResult+'static> {
50     let sp = cx.with_def_site_ctxt(sp);
51     base::check_zero_tts(cx, sp, tts, "file!");
52
53     let topmost = cx.expansion_cause().unwrap_or(sp);
54     let loc = cx.source_map().lookup_char_pos(topmost.lo());
55     base::MacEager::expr(cx.expr_str(topmost, Symbol::intern(&loc.file.name.to_string())))
56 }
57
58 pub fn expand_stringify(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
59                         -> Box<dyn base::MacResult+'static> {
60     let sp = cx.with_def_site_ctxt(sp);
61     let s = pprust::tts_to_string(tts);
62     base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&s)))
63 }
64
65 pub fn expand_mod(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
66                   -> Box<dyn base::MacResult+'static> {
67     let sp = cx.with_def_site_ctxt(sp);
68     base::check_zero_tts(cx, sp, tts, "module_path!");
69     let mod_path = &cx.current_expansion.module.mod_path;
70     let string = mod_path.iter().map(|x| x.to_string()).collect::<Vec<String>>().join("::");
71
72     base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&string)))
73 }
74
75 /// include! : parse the given file as an expr
76 /// This is generally a bad idea because it's going to behave
77 /// unhygienically.
78 pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
79                            -> Box<dyn base::MacResult+'cx> {
80     let sp = cx.with_def_site_ctxt(sp);
81     let file = match get_single_str_from_tts(cx, sp, tts, "include!") {
82         Some(f) => f,
83         None => return DummyResult::any(sp),
84     };
85     // The file will be added to the code map by the parser
86     let file = match cx.resolve_path(file, sp) {
87         Ok(f) => f,
88         Err(mut err) => {
89             err.emit();
90             return DummyResult::any(sp);
91         },
92     };
93     let directory_ownership = DirectoryOwnership::Owned { relative: None };
94     let p = new_sub_parser_from_file(cx.parse_sess(), &file, directory_ownership, None, sp);
95
96     struct ExpandResult<'a> {
97         p: 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             let r = panictry!(self.p.parse_expr());
102             if self.p.token != token::Eof {
103                 self.p.sess.buffer_lint(
104                     BufferedEarlyLintId::IncompleteInclude,
105                     self.p.token.span,
106                     ast::CRATE_NODE_ID,
107                     "include macro expected single expression in source",
108                 );
109             }
110             Some(r)
111         }
112
113         fn make_items(mut self: Box<ExpandResult<'a>>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
114             let mut ret = SmallVec::new();
115             while self.p.token != token::Eof {
116                 match panictry!(self.p.parse_item()) {
117                     Some(item) => ret.push(item),
118                     None => self.p.sess.span_diagnostic.span_fatal(self.p.token.span,
119                                                            &format!("expected item, found `{}`",
120                                                                     self.p.this_token_to_string()))
121                                                .raise()
122                 }
123             }
124             Some(ret)
125         }
126     }
127
128     Box::new(ExpandResult { p })
129 }
130
131 // include_str! : read the given file, insert it as a literal string expr
132 pub fn expand_include_str(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
133                           -> Box<dyn base::MacResult+'static> {
134     let sp = cx.with_def_site_ctxt(sp);
135     let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") {
136         Some(f) => f,
137         None => return DummyResult::any(sp)
138     };
139     let file = match cx.resolve_path(file, sp) {
140         Ok(f) => f,
141         Err(mut err) => {
142             err.emit();
143             return DummyResult::any(sp);
144         },
145     };
146     match cx.source_map().load_binary_file(&file) {
147         Ok(bytes) => match std::str::from_utf8(&bytes) {
148             Ok(src) => {
149                 let interned_src = Symbol::intern(&src);
150                 base::MacEager::expr(cx.expr_str(sp, interned_src))
151             }
152             Err(_) => {
153                 cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
154                 DummyResult::any(sp)
155             }
156         },
157         Err(e) => {
158             cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
159             DummyResult::any(sp)
160         }
161     }
162 }
163
164 pub fn expand_include_bytes(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
165                             -> Box<dyn base::MacResult+'static> {
166     let sp = cx.with_def_site_ctxt(sp);
167     let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") {
168         Some(f) => f,
169         None => return DummyResult::any(sp)
170     };
171     let file = match cx.resolve_path(file, sp) {
172         Ok(f) => f,
173         Err(mut err) => {
174             err.emit();
175             return DummyResult::any(sp);
176         },
177     };
178     match cx.source_map().load_binary_file(&file) {
179         Ok(bytes) => {
180             base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes))))
181         },
182         Err(e) => {
183             cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
184             DummyResult::any(sp)
185         }
186     }
187 }