]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_passes/src/entry.rs
Auto merge of #92361 - vacuus:doctest-run-test-out-lines, r=CraftSpider
[rust.git] / compiler / rustc_passes / src / entry.rs
1 use rustc_ast::entry::EntryPointType;
2 use rustc_errors::struct_span_err;
3 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE};
4 use rustc_hir::itemlikevisit::ItemLikeVisitor;
5 use rustc_hir::{ForeignItem, ImplItem, Item, ItemKind, Node, TraitItem, CRATE_HIR_ID};
6 use rustc_middle::hir::map::Map;
7 use rustc_middle::ty::query::Providers;
8 use rustc_middle::ty::TyCtxt;
9 use rustc_session::config::{CrateType, EntryFnType};
10 use rustc_session::parse::feature_err;
11 use rustc_session::Session;
12 use rustc_span::symbol::sym;
13 use rustc_span::{Span, DUMMY_SP};
14
15 struct EntryContext<'a, 'tcx> {
16     session: &'a Session,
17
18     map: Map<'tcx>,
19
20     /// The function that has attribute named `main`.
21     attr_main_fn: Option<(LocalDefId, Span)>,
22
23     /// The function that has the attribute 'start' on it.
24     start_fn: Option<(LocalDefId, Span)>,
25
26     /// The functions that one might think are `main` but aren't, e.g.
27     /// main functions not defined at the top level. For diagnostics.
28     non_main_fns: Vec<Span>,
29 }
30
31 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for EntryContext<'a, 'tcx> {
32     fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
33         let def_key = self.map.def_key(item.def_id);
34         let at_root = def_key.parent == Some(CRATE_DEF_INDEX);
35         find_item(item, self, at_root);
36     }
37
38     fn visit_trait_item(&mut self, _trait_item: &'tcx TraitItem<'tcx>) {
39         // Entry fn is never a trait item.
40     }
41
42     fn visit_impl_item(&mut self, _impl_item: &'tcx ImplItem<'tcx>) {
43         // Entry fn is never a trait item.
44     }
45
46     fn visit_foreign_item(&mut self, _: &'tcx ForeignItem<'tcx>) {
47         // Entry fn is never a foreign item.
48     }
49 }
50
51 fn entry_fn(tcx: TyCtxt<'_>, (): ()) -> Option<(DefId, EntryFnType)> {
52     let any_exe = tcx.sess.crate_types().iter().any(|ty| *ty == CrateType::Executable);
53     if !any_exe {
54         // No need to find a main function.
55         return None;
56     }
57
58     // If the user wants no main function at all, then stop here.
59     if tcx.sess.contains_name(&tcx.hir().attrs(CRATE_HIR_ID), sym::no_main) {
60         return None;
61     }
62
63     let mut ctxt = EntryContext {
64         session: tcx.sess,
65         map: tcx.hir(),
66         attr_main_fn: None,
67         start_fn: None,
68         non_main_fns: Vec::new(),
69     };
70
71     tcx.hir().visit_all_item_likes(&mut ctxt);
72
73     configure_main(tcx, &ctxt)
74 }
75
76 // Beware, this is duplicated in `librustc_builtin_macros/test_harness.rs`
77 // (with `ast::Item`), so make sure to keep them in sync.
78 fn entry_point_type(ctxt: &EntryContext<'_, '_>, item: &Item<'_>, at_root: bool) -> EntryPointType {
79     let attrs = ctxt.map.attrs(item.hir_id());
80     if ctxt.session.contains_name(attrs, sym::start) {
81         EntryPointType::Start
82     } else if ctxt.session.contains_name(attrs, sym::rustc_main) {
83         EntryPointType::MainAttr
84     } else if item.ident.name == sym::main {
85         if at_root {
86             // This is a top-level function so can be `main`.
87             EntryPointType::MainNamed
88         } else {
89             EntryPointType::OtherMain
90         }
91     } else {
92         EntryPointType::None
93     }
94 }
95
96 fn throw_attr_err(sess: &Session, span: Span, attr: &str) {
97     sess.struct_span_err(span, &format!("`{}` attribute can only be used on functions", attr))
98         .emit();
99 }
100
101 fn find_item(item: &Item<'_>, ctxt: &mut EntryContext<'_, '_>, at_root: bool) {
102     match entry_point_type(ctxt, item, at_root) {
103         EntryPointType::None => (),
104         _ if !matches!(item.kind, ItemKind::Fn(..)) => {
105             let attrs = ctxt.map.attrs(item.hir_id());
106             if let Some(attr) = ctxt.session.find_by_name(attrs, sym::start) {
107                 throw_attr_err(&ctxt.session, attr.span, "start");
108             }
109             if let Some(attr) = ctxt.session.find_by_name(attrs, sym::rustc_main) {
110                 throw_attr_err(&ctxt.session, attr.span, "rustc_main");
111             }
112         }
113         EntryPointType::MainNamed => (),
114         EntryPointType::OtherMain => {
115             ctxt.non_main_fns.push(item.span);
116         }
117         EntryPointType::MainAttr => {
118             if ctxt.attr_main_fn.is_none() {
119                 ctxt.attr_main_fn = Some((item.def_id, item.span));
120             } else {
121                 struct_span_err!(
122                     ctxt.session,
123                     item.span,
124                     E0137,
125                     "multiple functions with a `#[main]` attribute"
126                 )
127                 .span_label(item.span, "additional `#[main]` function")
128                 .span_label(ctxt.attr_main_fn.unwrap().1, "first `#[main]` function")
129                 .emit();
130             }
131         }
132         EntryPointType::Start => {
133             if ctxt.start_fn.is_none() {
134                 ctxt.start_fn = Some((item.def_id, item.span));
135             } else {
136                 struct_span_err!(ctxt.session, item.span, E0138, "multiple `start` functions")
137                     .span_label(ctxt.start_fn.unwrap().1, "previous `#[start]` function here")
138                     .span_label(item.span, "multiple `start` functions")
139                     .emit();
140             }
141         }
142     }
143 }
144
145 fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) -> Option<(DefId, EntryFnType)> {
146     if let Some((def_id, _)) = visitor.start_fn {
147         Some((def_id.to_def_id(), EntryFnType::Start))
148     } else if let Some((def_id, _)) = visitor.attr_main_fn {
149         Some((def_id.to_def_id(), EntryFnType::Main))
150     } else {
151         if let Some(main_def) = tcx.resolutions(()).main_def && let Some(def_id) = main_def.opt_fn_def_id() {
152             // non-local main imports are handled below
153             if let Some(def_id) = def_id.as_local() && matches!(tcx.hir().find_by_def_id(def_id), Some(Node::ForeignItem(_))) {
154                 tcx.sess
155                     .struct_span_err(
156                         tcx.def_span(def_id),
157                         "the `main` function cannot be declared in an `extern` block",
158                     )
159                     .emit();
160                 return None;
161             }
162
163             if main_def.is_import && !tcx.features().imported_main {
164                 let span = main_def.span;
165                 feature_err(
166                     &tcx.sess.parse_sess,
167                     sym::imported_main,
168                     span,
169                     "using an imported function as entry point `main` is experimental",
170                 )
171                 .emit();
172             }
173             return Some((def_id, EntryFnType::Main));
174         }
175         no_main_err(tcx, visitor);
176         None
177     }
178 }
179
180 fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) {
181     let sp = tcx.def_span(CRATE_DEF_ID);
182     if *tcx.sess.parse_sess.reached_eof.borrow() {
183         // There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about
184         // the missing `fn main()` then as it might have been hidden inside an unclosed block.
185         tcx.sess.delay_span_bug(sp, "`main` not found, but expected unclosed brace error");
186         return;
187     }
188
189     // There is no main function.
190     let mut err = struct_span_err!(
191         tcx.sess,
192         DUMMY_SP,
193         E0601,
194         "`main` function not found in crate `{}`",
195         tcx.crate_name(LOCAL_CRATE)
196     );
197     let filename = &tcx.sess.local_crate_source_file;
198     let note = if !visitor.non_main_fns.is_empty() {
199         for &span in &visitor.non_main_fns {
200             err.span_note(span, "here is a function named `main`");
201         }
202         err.note("you have one or more functions named `main` not defined at the crate level");
203         err.help("consider moving the `main` function definitions");
204         // There were some functions named `main` though. Try to give the user a hint.
205         format!(
206             "the main function must be defined at the crate level{}",
207             filename.as_ref().map(|f| format!(" (in `{}`)", f.display())).unwrap_or_default()
208         )
209     } else if let Some(filename) = filename {
210         format!("consider adding a `main` function to `{}`", filename.display())
211     } else {
212         String::from("consider adding a `main` function at the crate level")
213     };
214     // The file may be empty, which leads to the diagnostic machinery not emitting this
215     // note. This is a relatively simple way to detect that case and emit a span-less
216     // note instead.
217     if tcx.sess.source_map().lookup_line(sp.hi()).is_ok() {
218         err.set_span(sp.shrink_to_hi());
219         err.span_label(sp.shrink_to_hi(), &note);
220     } else {
221         err.note(&note);
222     }
223
224     if let Some(main_def) = tcx.resolutions(()).main_def && main_def.opt_fn_def_id().is_none(){
225         // There is something at `crate::main`, but it is not a function definition.
226         err.span_label(main_def.span, "non-function item at `crate::main` is found");
227     }
228
229     if tcx.sess.teach(&err.get_code().unwrap()) {
230         err.note(
231             "If you don't know the basics of Rust, you can go look to the Rust Book \
232                   to get started: https://doc.rust-lang.org/book/",
233         );
234     }
235     err.emit();
236 }
237
238 pub fn provide(providers: &mut Providers) {
239     *providers = Providers { entry_fn, ..*providers };
240 }