Skip to content

Commit 2f96bff

Browse files
authored
checker: fix comptime main fn (#25747)
1 parent 6b7535e commit 2f96bff

File tree

3 files changed

+36
-4
lines changed

3 files changed

+36
-4
lines changed

vlib/v/checker/checker.v

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -476,11 +476,27 @@ pub fn (mut c Checker) check_files(ast_files []&ast.File) {
476476
}
477477
}
478478

479-
// do checks specific to files in main module
480-
// returns `true` if a main function is in the file
481-
fn (mut c Checker) file_has_main_fn(file &ast.File) bool {
479+
fn (mut c Checker) stmts_has_main_fn(stmts []ast.Stmt) bool {
482480
mut has_main_fn := false
483-
for stmt in file.stmts {
481+
for stmt in stmts {
482+
if stmt is ast.ExprStmt {
483+
// top level comptime main fn
484+
if stmt.expr is ast.IfExpr && stmt.expr.is_comptime {
485+
// $if a ? { fn main(){} } $else { fn main() {} }
486+
for branch in stmt.expr.branches {
487+
if c.stmts_has_main_fn(branch.stmts) {
488+
has_main_fn = true
489+
}
490+
}
491+
} else if stmt.expr is ast.MatchExpr && stmt.expr.is_comptime {
492+
// $match os { 'windows' { fn main() {} } ...
493+
for branch in stmt.expr.branches {
494+
if c.stmts_has_main_fn(branch.stmts) {
495+
has_main_fn = true
496+
}
497+
}
498+
}
499+
}
484500
if stmt is ast.FnDecl {
485501
if stmt.name == 'main.main' {
486502
if has_main_fn {
@@ -504,6 +520,12 @@ fn (mut c Checker) file_has_main_fn(file &ast.File) bool {
504520
return has_main_fn
505521
}
506522

523+
// do checks specific to files in main module
524+
// returns `true` if a main function is in the file
525+
fn (mut c Checker) file_has_main_fn(file &ast.File) bool {
526+
return c.stmts_has_main_fn(file.stmts)
527+
}
528+
507529
@[direct_array_access]
508530
fn (mut c Checker) check_valid_snake_case(name string, identifier string, pos token.Pos) {
509531
if c.pref.translated || c.file.is_translated {
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
main2
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
$if usemain1 ? {
2+
fn main() {
3+
println('main1')
4+
}
5+
} $else {
6+
fn main() {
7+
println('main2')
8+
}
9+
}

0 commit comments

Comments
 (0)