Image for post
Image for post

Automatic semicolon insertion in Go

Michał Łowicki
Dec 22, 2016 · 3 min read
Block = "{" StatementList "}" .
StatementList = { Statement ";" } .
{
fmt.Println(1);
fmt.Println(2);
}
{
fmt.Println(1)
fmt.Println(2)
}

The roots

Image for post
Image for post
func g() int {
return 1
}
func f() func(int) {
return func(n int) {
fmt.Println("Inner func called")
}
}
f()
(g())
f();
(g());

Under the hood

Image for post
Image for post
package mainimport (
"fmt"
"go/scanner"
"go/token"
)
func main() {
scanner := scanner.Scanner{}
source := []byte("n := 1\nfmt.Println(n)")
errorHandler := func(_ token.Position, msg string) {
fmt.Printf("error handler called: %s\n", msg)
}
fset := token.NewFileSet()
file := fset.AddFile("", fset.Base(), len(source))
scanner.Init(file, source, errorHandler, 0)
for {
position, tok, literal := scanner.Scan()
fmt.Printf("%d: %s", position, tok)
if literal != ""{
fmt.Printf(" %q", literal)
}
fmt.Println()
if tok == token.EOF {
break
}
}
}
1: IDENT "n"
3: :=
6: INT "1"
7: ; "\n"
8: IDENT "fmt"
11: .
12: IDENT "Println"
19: (
20: IDENT "n"
21: )
22: ; "\n"
22: EOF
n := 1
fmt.Println(n)

golangspec

A series dedicated to deeply understand Go’s specification…

Michał Łowicki

Written by

Software engineering manager at Facebook, previously Opera, never satisfied.

golangspec

A series dedicated to deeply understand Go’s specification and language’s nuances

Michał Łowicki

Written by

Software engineering manager at Facebook, previously Opera, never satisfied.

golangspec

A series dedicated to deeply understand Go’s specification and language’s nuances

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store