gopherdata / gophernotes

The Go kernel for Jupyter notebooks and nteract.
MIT License
3.86k stars 263 forks source link

[Question] non-declaration statement outside function body #226

Closed tejas-kale closed 3 years ago

tejas-kale commented 3 years ago

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.

image

So, I am curious to know what happens under the hood in gophernotes which allows the Jupyter cell shown above to run fine. Thanks.

cosmos72 commented 3 years ago

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

  1. convert the source code from string to a sequence of go/token.Token using a slightly modified go/scanner.Scanner that also accepts top-level statements and expressions
  2. convert the tokens to an abstract syntax tree of go/ast.Node using a slightly modified go/parser that also accepts top-level statements and expressions
  3. perform a reduced type checking and convert the abstract syntax tree to a tree of closures github.com/cosmos72/gomacro/fast/Expr
  4. execute the closure
tejas-kale commented 3 years ago

@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.