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