swift: [SR-12683] `@main` is no longer usable due to misdetection of top level code

Previous ID SR-12683
Radar rdar://problem/62475602
Original Reporter @compnerd
Type Bug

Attachment: Download

Additional Detail from JIRA
Votes 16
Component/s
Labels Bug
Assignee None
Priority Medium

md5: d99a1a03d2003d32b1bfd6a2ae65a2fa

is duplicated by:

  • SR-14488 Can’t use @main in executable target with single file

Issue Description:

There seems to be a recent regression with comment blocks and functions being treated as top level code which prevents the use of `@main`.

About this issue

  • Original URL
  • State: open
  • Created 7 years ago
  • Reactions: 7
  • Comments: 15 (5 by maintainers)

Commits related to this issue

Most upvoted comments

Comment by Eneko Alonso (JIRA)

This seems to still be an issue for new Swift 5.5 packages containing a main.swift file.

Steps to reproduce:

  1. mkdir myapp && cd myapp
  2. swift package init --type executable
  3. Replace `main.swift` content with the following

{{
@main
struct Program {
static func main() {
print(“Hello, world!”)
}
}
}}

4. swift run
5. Observe error: main.swift:2:1: error: ‘main’ attribute cannot be used in a module that contains top-level code

Multiple files

Adding a second file does not seem to fix the issue:

  1. create a second file Hello.swift with this content

{{
func hello() {
print(“Hello, world!”)
}
}}

2. Update `main.swift` as follows:

{{
@main
struct Program {
static func main() {
hello()
}
}
}}

3. swift run
4. Observe error: main.swift:2:1: error: ‘main’ attribute cannot be used in a module that contains top-level code

Solution

Renaming `main.swift` to something else (eg. `Program.swift`) solves the issue, whether there are only one file or more.

  1. Delete Hello.swift
  2. Update main.swift as follows:

{{
func hello() {
print(“Hello, world!”)
}

@main
struct Program {
static func main() {
hello()
}
}
}}

3. swift run
4. Observer the output “Hello, world!”

This issue seems very old but I’d like to chime in that it doesn’t seem fixed at all in Swift 5.9. See https://github.com/apple/swift-getting-started-cli/issues/3 - I hit the bug midway through the “getting started” tutorial for a command line program.

I initially had the same problem when following the CLI tutorial, but the issue went away when I added path: "Sources" to the MyCLI target in Package.swift. I didn’t use -parse-as-library.

This is with Swift 6.1.2 on Windows 11 24H2

OK so it looks like I need to use -XSwiftc -parse-as-library in order to be able to do swift run.

Ran into the same issue in the same tutorial as @ayaen , Swift 5.10.1 on WIndows. This worked but it was -Xswiftc with a lowercase s.

Trying to use this example for using raw nio:https://theswiftdev.com/swiftnio-tutorial-the-echo-server/ its only from 3 months ago, but I the newest info I’ve found. seems the renaming worked for me was well.