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