[Question] non-declaration statement outside function body
tejas-kale opened this issue · 2 comments
Hi,
I have just started learning Go and the following code (saved as cards.go
), when executed using an IDE fails with the error ./cards.go:5:1: syntax error: non-declaration statement outside function body
.
package main
import "fmt"
deckSize := 20
func main() {
fmt.Println(deckSize)
}
But the same piece of code when run in a Jupyter cell works fine.
So, I am curious to know what happens under the hood in gophernotes
which allows the Jupyter cell shown above to run fine. Thanks.
This is an intentional extension: since gophernotes
is interactive, the compile and runtime phases are interleaved
and allowing statements and expressions at top-level is both useful and necessary:
it's useful because gophernotes
can also be used as a calculator - for example you can execute 7 + 12
or "foo" + "bar"
it's also necessary because as minimum you need a way to execute the functions you created - there is no separate runtime that will execute your main()
[UPDATE] about "how" it works under the hood: for every declaration, statement or expression the steps are
- convert the source code from
string
to a sequence ofgo/token.Token
using a slightly modifiedgo/scanner.Scanner
that also accepts top-level statements and expressions - convert the tokens to an abstract syntax tree of
go/ast.Node
using a slightly modifiedgo/parser
that also accepts top-level statements and expressions - perform a reduced type checking and convert the abstract syntax tree to a tree of closures
github.com/cosmos72/gomacro/fast/Expr
- execute the closure
@cosmos72 Thanks for the explanation. It helps me understand the difference between gophernotes
and the regular compile and run execution of Go. Closing the issue.