1 use rustc_ast
::entry
::EntryPointType
;
2 use rustc_errors
::struct_span_err
;
3 use rustc_hir
::def_id
::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE}
;
4 use rustc_hir
::itemlikevisit
::ItemLikeVisitor
;
5 use rustc_hir
::{ForeignItem, HirId, 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}
;
15 struct EntryContext
<'a
, 'tcx
> {
20 /// The function that has attribute named `main`.
21 attr_main_fn
: Option
<(HirId
, Span
)>,
23 /// The function that has the attribute 'start' on it.
24 start_fn
: Option
<(HirId
, Span
)>,
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
<(HirId
, Span
)>,
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
);
38 fn visit_trait_item(&mut self, _trait_item
: &'tcx TraitItem
<'tcx
>) {
39 // Entry fn is never a trait item.
42 fn visit_impl_item(&mut self, _impl_item
: &'tcx ImplItem
<'tcx
>) {
43 // Entry fn is never a trait item.
46 fn visit_foreign_item(&mut self, _
: &'tcx ForeignItem
<'tcx
>) {
47 // Entry fn is never a foreign item.
51 fn entry_fn(tcx
: TyCtxt
<'_
>, (): ()) -> Option
<(DefId
, EntryFnType
)> {
52 let any_exe
= tcx
.sess
.crate_types().iter().any(|ty
| *ty
== CrateType
::Executable
);
54 // No need to find a main function.
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
) {
63 let mut ctxt
= EntryContext
{
68 non_main_fns
: Vec
::new(),
71 tcx
.hir().krate().visit_all_item_likes(&mut ctxt
);
73 configure_main(tcx
, &ctxt
)
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
) {
82 } else if ctxt
.session
.contains_name(attrs
, sym
::rustc_main
) {
83 EntryPointType
::MainAttr
84 } else if item
.ident
.name
== sym
::main
{
86 // This is a top-level function so can be `main`.
87 EntryPointType
::MainNamed
89 EntryPointType
::OtherMain
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
))
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");
109 if let Some(attr
) = ctxt
.session
.find_by_name(attrs
, sym
::rustc_main
) {
110 throw_attr_err(&ctxt
.session
, attr
.span
, "rustc_main");
113 EntryPointType
::MainNamed
=> (),
114 EntryPointType
::OtherMain
=> {
115 ctxt
.non_main_fns
.push((item
.hir_id(), item
.span
));
117 EntryPointType
::MainAttr
=> {
118 if ctxt
.attr_main_fn
.is_none() {
119 ctxt
.attr_main_fn
= Some((item
.hir_id(), item
.span
));
125 "multiple functions with a `#[main]` attribute"
127 .span_label(item
.span
, "additional `#[main]` function")
128 .span_label(ctxt
.attr_main_fn
.unwrap().1, "first `#[main]` function")
132 EntryPointType
::Start
=> {
133 if ctxt
.start_fn
.is_none() {
134 ctxt
.start_fn
= Some((item
.hir_id(), item
.span
));
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")
145 fn configure_main(tcx
: TyCtxt
<'_
>, visitor
: &EntryContext
<'_
, '_
>) -> Option
<(DefId
, EntryFnType
)> {
146 if let Some((hir_id
, _
)) = visitor
.start_fn
{
147 Some((tcx
.hir().local_def_id(hir_id
).to_def_id(), EntryFnType
::Start
))
148 } else if let Some((hir_id
, _
)) = visitor
.attr_main_fn
{
149 Some((tcx
.hir().local_def_id(hir_id
).to_def_id(), EntryFnType
::Main
))
151 if let Some(main_def
) = tcx
.resolutions(()).main_def
{
152 if let Some(def_id
) = main_def
.opt_fn_def_id() {
153 // non-local main imports are handled below
154 if def_id
.is_local() {
155 let hir_id
= tcx
.hir().local_def_id_to_hir_id(def_id
.expect_local());
156 if matches
!(tcx
.hir().find(hir_id
), Some(Node
::ForeignItem(_
))) {
159 tcx
.hir().span(hir_id
),
160 "the `main` function cannot be declared in an `extern` block",
167 if main_def
.is_import
&& !tcx
.features().imported_main
{
168 let span
= main_def
.span
;
170 &tcx
.sess
.parse_sess
,
173 "using an imported function as entry point `main` is experimental",
177 return Some((def_id
, EntryFnType
::Main
));
180 no_main_err(tcx
, visitor
);
185 fn no_main_err(tcx
: TyCtxt
<'_
>, visitor
: &EntryContext
<'_
, '_
>) {
186 let sp
= tcx
.hir().krate().item
.inner
;
187 if *tcx
.sess
.parse_sess
.reached_eof
.borrow() {
188 // There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about
189 // the missing `fn main()` then as it might have been hidden inside an unclosed block.
190 tcx
.sess
.delay_span_bug(sp
, "`main` not found, but expected unclosed brace error");
194 // There is no main function.
195 let mut err
= struct_span_err
!(
199 "`main` function not found in crate `{}`",
200 tcx
.crate_name(LOCAL_CRATE
)
202 let filename
= &tcx
.sess
.local_crate_source_file
;
203 let note
= if !visitor
.non_main_fns
.is_empty() {
204 for &(_
, span
) in &visitor
.non_main_fns
{
205 err
.span_note(span
, "here is a function named `main`");
207 err
.note("you have one or more functions named `main` not defined at the crate level");
208 err
.help("consider moving the `main` function definitions");
209 // There were some functions named `main` though. Try to give the user a hint.
211 "the main function must be defined at the crate level{}",
212 filename
.as_ref().map(|f
| format
!(" (in `{}`)", f
.display())).unwrap_or_default()
214 } else if let Some(filename
) = filename
{
215 format
!("consider adding a `main` function to `{}`", filename
.display())
217 String
::from("consider adding a `main` function at the crate level")
219 // The file may be empty, which leads to the diagnostic machinery not emitting this
220 // note. This is a relatively simple way to detect that case and emit a span-less
222 if tcx
.sess
.source_map().lookup_line(sp
.lo()).is_ok() {
224 err
.span_label(sp
, ¬e
);
229 if let Some(main_def
) = tcx
.resolutions(()).main_def
{
230 if main_def
.opt_fn_def_id().is_none() {
231 // There is something at `crate::main`, but it is not a function definition.
232 err
.span_label(main_def
.span
, &format
!("non-function item at `crate::main` is found"));
236 if tcx
.sess
.teach(&err
.get_code().unwrap()) {
238 "If you don't know the basics of Rust, you can go look to the Rust Book \
239 to get started: https://doc.rust-lang.org/book/",
245 pub fn provide(providers
: &mut Providers
) {
246 *providers
= Providers { entry_fn, ..*providers }
;