]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/entry.rs
rustc: replace `TyCtxt<'tcx, 'gcx, 'tcx>` with `TyCtxt<'gcx, 'tcx>`.
[rust.git] / src / librustc / middle / entry.rs
1 use crate::hir::map as hir_map;
2 use crate::hir::def_id::{CrateNum, CRATE_DEF_INDEX, DefId, LOCAL_CRATE};
3 use crate::session::{config, Session};
4 use crate::session::config::EntryFnType;
5 use syntax::attr;
6 use syntax::entry::EntryPointType;
7 use syntax::symbol::sym;
8 use syntax_pos::Span;
9 use crate::hir::{HirId, Item, ItemKind, ImplItem, TraitItem};
10 use crate::hir::itemlikevisit::ItemLikeVisitor;
11 use crate::ty::TyCtxt;
12 use crate::ty::query::Providers;
13
14 struct EntryContext<'a, 'tcx: 'a> {
15     session: &'a Session,
16
17     map: &'a hir_map::Map<'tcx>,
18
19     // The top-level function called 'main'
20     main_fn: Option<(HirId, Span)>,
21
22     // The function that has attribute named 'main'
23     attr_main_fn: Option<(HirId, Span)>,
24
25     // The function that has the attribute 'start' on it
26     start_fn: Option<(HirId, Span)>,
27
28     // The functions that one might think are 'main' but aren't, e.g.
29     // main functions not defined at the top level. For diagnostics.
30     non_main_fns: Vec<(HirId, Span)> ,
31 }
32
33 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for EntryContext<'a, 'tcx> {
34     fn visit_item(&mut self, item: &'tcx Item) {
35         let def_id = self.map.local_def_id_from_hir_id(item.hir_id);
36         let def_key = self.map.def_key(def_id);
37         let at_root = def_key.parent == Some(CRATE_DEF_INDEX);
38         find_item(item, self, at_root);
39     }
40
41     fn visit_trait_item(&mut self, _trait_item: &'tcx TraitItem) {
42         // entry fn is never a trait item
43     }
44
45     fn visit_impl_item(&mut self, _impl_item: &'tcx ImplItem) {
46         // entry fn is never an impl item
47     }
48 }
49
50 fn entry_fn(tcx: TyCtxt<'_, '_>, cnum: CrateNum) -> Option<(DefId, EntryFnType)> {
51     assert_eq!(cnum, LOCAL_CRATE);
52
53     let any_exe = tcx.sess.crate_types.borrow().iter().any(|ty| {
54         *ty == config::CrateType::Executable
55     });
56     if !any_exe {
57         // No need to find a main function
58         return None;
59     }
60
61     // If the user wants no main function at all, then stop here.
62     if attr::contains_name(&tcx.hir().krate().attrs, sym::no_main) {
63         return None;
64     }
65
66     let mut ctxt = EntryContext {
67         session: tcx.sess,
68         map: tcx.hir(),
69         main_fn: None,
70         attr_main_fn: None,
71         start_fn: None,
72         non_main_fns: Vec::new(),
73     };
74
75     tcx.hir().krate().visit_all_item_likes(&mut ctxt);
76
77     configure_main(tcx, &ctxt)
78 }
79
80 // Beware, this is duplicated in `libsyntax/entry.rs`, so make sure to keep
81 // them in sync.
82 fn entry_point_type(item: &Item, at_root: bool) -> EntryPointType {
83     match item.node {
84         ItemKind::Fn(..) => {
85             if attr::contains_name(&item.attrs, sym::start) {
86                 EntryPointType::Start
87             } else if attr::contains_name(&item.attrs, sym::main) {
88                 EntryPointType::MainAttr
89             } else if item.ident.name == sym::main {
90                 if at_root {
91                     // This is a top-level function so can be 'main'.
92                     EntryPointType::MainNamed
93                 } else {
94                     EntryPointType::OtherMain
95                 }
96             } else {
97                 EntryPointType::None
98             }
99         }
100         _ => EntryPointType::None,
101     }
102 }
103
104
105 fn find_item(item: &Item, ctxt: &mut EntryContext<'_, '_>, at_root: bool) {
106     match entry_point_type(item, at_root) {
107         EntryPointType::MainNamed => {
108             if ctxt.main_fn.is_none() {
109                 ctxt.main_fn = Some((item.hir_id, item.span));
110             } else {
111                 span_err!(ctxt.session, item.span, E0136,
112                           "multiple 'main' functions");
113             }
114         },
115         EntryPointType::OtherMain => {
116             ctxt.non_main_fns.push((item.hir_id, item.span));
117         },
118         EntryPointType::MainAttr => {
119             if ctxt.attr_main_fn.is_none() {
120                 ctxt.attr_main_fn = Some((item.hir_id, item.span));
121             } else {
122                 struct_span_err!(ctxt.session, item.span, E0137,
123                                  "multiple functions with a #[main] attribute")
124                 .span_label(item.span, "additional #[main] function")
125                 .span_label(ctxt.attr_main_fn.unwrap().1, "first #[main] function")
126                 .emit();
127             }
128         },
129         EntryPointType::Start => {
130             if ctxt.start_fn.is_none() {
131                 ctxt.start_fn = Some((item.hir_id, item.span));
132             } else {
133                 struct_span_err!(ctxt.session, item.span, E0138, "multiple 'start' functions")
134                     .span_label(ctxt.start_fn.unwrap().1, "previous `start` function here")
135                     .span_label(item.span, "multiple `start` functions")
136                     .emit();
137             }
138         }
139         EntryPointType::None => (),
140     }
141 }
142
143 fn configure_main(
144     tcx: TyCtxt<'_, '_>,
145     visitor: &EntryContext<'_, '_>,
146 ) -> Option<(DefId, EntryFnType)> {
147     if let Some((hir_id, _)) = visitor.start_fn {
148         Some((tcx.hir().local_def_id_from_hir_id(hir_id), EntryFnType::Start))
149     } else if let Some((hir_id, _)) = visitor.attr_main_fn {
150         Some((tcx.hir().local_def_id_from_hir_id(hir_id), EntryFnType::Main))
151     } else if let Some((hir_id, _)) = visitor.main_fn {
152         Some((tcx.hir().local_def_id_from_hir_id(hir_id), EntryFnType::Main))
153     } else {
154         // No main function
155         let mut err = struct_err!(tcx.sess, E0601,
156             "`main` function not found in crate `{}`", tcx.crate_name(LOCAL_CRATE));
157         if !visitor.non_main_fns.is_empty() {
158             // There were some functions named 'main' though. Try to give the user a hint.
159             err.note("the main function must be defined at the crate level \
160                       but you have one or more functions named 'main' that are not \
161                       defined at the crate level. Either move the definition or \
162                       attach the `#[main]` attribute to override this behavior.");
163             for &(_, span) in &visitor.non_main_fns {
164                 err.span_note(span, "here is a function named 'main'");
165             }
166             err.emit();
167         } else {
168             if let Some(ref filename) = tcx.sess.local_crate_source_file {
169                 err.note(&format!("consider adding a `main` function to `{}`", filename.display()));
170             }
171             if tcx.sess.teach(&err.get_code().unwrap()) {
172                 err.note("If you don't know the basics of Rust, you can go look to the Rust Book \
173                           to get started: https://doc.rust-lang.org/book/");
174             }
175             err.emit();
176         }
177
178         None
179     }
180 }
181
182 pub fn find_entry_point(tcx: TyCtxt<'_, '_>) -> Option<(DefId, EntryFnType)> {
183     tcx.entry_fn(LOCAL_CRATE)
184 }
185
186 pub fn provide(providers: &mut Providers<'_>) {
187     *providers = Providers {
188         entry_fn,
189         ..*providers
190     };
191 }