4 use rustc_ast::tokenstream::TokenStream;
5 use rustc_ast_pretty::pprust;
6 use rustc_expand::base::{self, *};
7 use rustc_expand::module::DirectoryOwnership;
8 use rustc_parse::{self, new_parser_from_file, parser::Parser};
9 use rustc_session::lint::builtin::INCOMPLETE_INCLUDE;
10 use rustc_span::symbol::Symbol;
11 use rustc_span::{self, Pos, Span};
13 use smallvec::SmallVec;
16 use rustc_data_structures::sync::Lrc;
18 // These macros all relate to the file system; they either return
19 // the column/row/filename of the expression, or they include
20 // a given file into the current one.
22 /// line!(): expands to the current line number
27 ) -> Box<dyn base::MacResult + 'static> {
28 let sp = cx.with_def_site_ctxt(sp);
29 base::check_zero_tts(cx, sp, tts, "line!");
31 let topmost = cx.expansion_cause().unwrap_or(sp);
32 let loc = cx.source_map().lookup_char_pos(topmost.lo());
34 base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32))
37 /* column!(): expands to the current column number */
42 ) -> Box<dyn base::MacResult + 'static> {
43 let sp = cx.with_def_site_ctxt(sp);
44 base::check_zero_tts(cx, sp, tts, "column!");
46 let topmost = cx.expansion_cause().unwrap_or(sp);
47 let loc = cx.source_map().lookup_char_pos(topmost.lo());
49 base::MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32 + 1))
52 /// file!(): expands to the current filename */
53 /// The source_file (`loc.file`) contains a bunch more information we could spit
59 ) -> Box<dyn base::MacResult + 'static> {
60 let sp = cx.with_def_site_ctxt(sp);
61 base::check_zero_tts(cx, sp, tts, "file!");
63 let topmost = cx.expansion_cause().unwrap_or(sp);
64 let loc = cx.source_map().lookup_char_pos(topmost.lo());
65 base::MacEager::expr(cx.expr_str(topmost, Symbol::intern(&loc.file.name.to_string())))
68 pub fn expand_stringify(
72 ) -> Box<dyn base::MacResult + 'static> {
73 let sp = cx.with_def_site_ctxt(sp);
74 let s = pprust::tts_to_string(&tts);
75 base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&s)))
82 ) -> Box<dyn base::MacResult + 'static> {
83 let sp = cx.with_def_site_ctxt(sp);
84 base::check_zero_tts(cx, sp, tts, "module_path!");
85 let mod_path = &cx.current_expansion.module.mod_path;
86 let string = mod_path.iter().map(|x| x.to_string()).collect::<Vec<String>>().join("::");
88 base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&string)))
91 /// include! : parse the given file as an expr
92 /// This is generally a bad idea because it's going to behave
94 pub fn expand_include<'cx>(
95 cx: &'cx mut ExtCtxt<'_>,
98 ) -> Box<dyn base::MacResult + 'cx> {
99 let sp = cx.with_def_site_ctxt(sp);
100 let file = match get_single_str_from_tts(cx, sp, tts, "include!") {
102 None => return DummyResult::any(sp),
104 // The file will be added to the code map by the parser
105 let mut file = match cx.resolve_path(file, sp) {
109 return DummyResult::any(sp);
112 let p = new_parser_from_file(cx.parse_sess(), &file, Some(sp));
114 // If in the included file we have e.g., `mod bar;`,
115 // then the path of `bar.rs` should be relative to the directory of `file`.
116 // See https://github.com/rust-lang/rust/pull/69838/files#r395217057 for a discussion.
117 // `MacroExpander::fully_expand_fragment` later restores, so "stack discipline" is maintained.
119 cx.current_expansion.directory_ownership = DirectoryOwnership::Owned { relative: None };
120 let mod_path = cx.current_expansion.module.mod_path.clone();
121 cx.current_expansion.module = Rc::new(ModuleData { mod_path, directory: file });
123 struct ExpandResult<'a> {
125 node_id: ast::NodeId,
127 impl<'a> base::MacResult for ExpandResult<'a> {
128 fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
129 let r = base::parse_expr(&mut self.p)?;
130 if self.p.token != token::Eof {
131 self.p.sess.buffer_lint(
135 "include macro expected single expression in source",
141 fn make_items(mut self: Box<ExpandResult<'a>>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
142 let mut ret = SmallVec::new();
143 while self.p.token != token::Eof {
144 match self.p.parse_item() {
149 Ok(Some(item)) => ret.push(item),
151 let token = pprust::token_to_string(&self.p.token);
152 let msg = format!("expected item, found `{}`", token);
153 self.p.struct_span_err(self.p.token.span, &msg).emit();
162 Box::new(ExpandResult { p, node_id: cx.resolver.lint_node_id(cx.current_expansion.id) })
165 // include_str! : read the given file, insert it as a literal string expr
166 pub fn expand_include_str(
167 cx: &mut ExtCtxt<'_>,
170 ) -> Box<dyn base::MacResult + 'static> {
171 let sp = cx.with_def_site_ctxt(sp);
172 let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") {
174 None => return DummyResult::any(sp),
176 let file = match cx.resolve_path(file, sp) {
180 return DummyResult::any(sp);
183 match cx.source_map().load_binary_file(&file) {
184 Ok(bytes) => match std::str::from_utf8(&bytes) {
186 let interned_src = Symbol::intern(&src);
187 base::MacEager::expr(cx.expr_str(sp, interned_src))
190 cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
195 cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
201 pub fn expand_include_bytes(
202 cx: &mut ExtCtxt<'_>,
205 ) -> Box<dyn base::MacResult + 'static> {
206 let sp = cx.with_def_site_ctxt(sp);
207 let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") {
209 None => return DummyResult::any(sp),
211 let file = match cx.resolve_path(file, sp) {
215 return DummyResult::any(sp);
218 match cx.source_map().load_binary_file(&file) {
219 Ok(bytes) => base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes)))),
221 cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));