1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: print error and pos for lacking main or pub main

This commit is contained in:
Enzo Baldisserri 2020-04-18 00:20:38 +02:00 committed by GitHub
parent f2be3d7ffb
commit 0f9322bf36
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 37 additions and 13 deletions

View File

@ -62,10 +62,17 @@ pub fn (c mut Checker) check2(ast_file ast.File) []scanner.Error {
}
pub fn (c mut Checker) check_files(ast_files []ast.File) {
mut all_mods := map[string]int
mut has_main_fn := false
for file in ast_files {
c.check(file)
all_mods[ file.mod.name ] = all_mods[ file.mod.name ] + 1
if file.mod.name == 'main' {
if fn_decl := get_main_fn_decl(file) {
has_main_fn = true
if fn_decl.is_pub {
c.error('function `main` cannot be declared public', fn_decl.pos)
}
}
}
}
// Make sure fn main is defined in non lib builds
if c.pref.build_mode == .build_module || c.pref.is_test {
@ -75,20 +82,21 @@ pub fn (c mut Checker) check_files(ast_files []ast.File) {
// shared libs do not need to have a main
return
}
// check that a main program has a `fn main(){}` function:
if all_mods['main'] > 0 {
for i, f in c.table.fns {
if f.name == 'main' {
if f.is_pub {
c.error('function `main` cannot be declared public', token.Position{})
exit(1)
}
return
if !has_main_fn {
c.error('function `main` must be declared in the main module', token.Position{})
}
}
fn get_main_fn_decl(file ast.File) ?ast.FnDecl {
for stmt in file.stmts {
if stmt is ast.FnDecl {
fn_decl := stmt as ast.FnDecl
if fn_decl.name == 'main' {
return fn_decl
}
}
c.error('function `main` is undeclared in the main module', token.Position{})
exit(1)
}
return none
}
pub fn (c mut Checker) struct_decl(decl ast.StructDecl) {

View File

@ -0,0 +1,5 @@
vlib/v/checker/tests/inout/no_fn_main.v:1:1: error: function `main` must be declared in the main module
1| fn no_main() {
^
2| println('Hello world !')
3| }

View File

@ -0,0 +1,3 @@
fn no_main() {
println('Hello world !')
}

View File

@ -0,0 +1,5 @@
vlib/v/checker/tests/inout/pub_fn_main.v:1:1: error: function `main` cannot be declared public
1| pub fn main() {
~~~
2| println('Hello world !')
3| }

View File

@ -0,0 +1,3 @@
pub fn main() {
println('Hello world !')
}