SlideShare a Scribd company logo
1 of 51
Download to read offline
A Tale of Go REPL
motemen
Go Conference 2015 Summer @ Tokyo
About Me
- @motemen
- Web engineer
- Chief engineer at Hatena, Kyoto
Mackerel mackerel.io
Agenda
- Introduction of ! motemen/gore
- Gore’s architecture
- Implementation details
Gore /gɔː/
Case: Learning New Languages
- Playing with language features
- Trying libraries
My Case — Perl
- perl ~/sketch.pl
- Edit and Run
My Case — Ruby
- irb
- pry
- A “REPL”

(Read-Eval-Print-Loop)
My Case — Go?
- tmp.go
- “packge main” “func main()”
- Removing unused variables by hand
- Question: Can gophers haz a REPL?
Go "REPL" impls (AFAIK)
- ! sbinet/igo — built upon ! sbinet/go-eval, with liner
- ! emicklei/rango — importing, statements, listing variables
- ! vito/go-repl — importing, statements, useful commands
- ! d4l3k/go-pry — attaches to running program, uses reflection
- (play.golang.org)
Needed a REPL that:
- Evaluates statements
- Imports any module
- Pretty prints values automatically
- Completes code
The Difficulties
- How can we achieve Go semantics?
- No APIs provided
- Re-implement Go compiler? 😩
Solution: “go run”
Solution: “go run”
- An “eval” to Go
- Perfect implementation & Always up-to-date
- Dead simple
- In: a program Out: the result 🎉
Gore: A REPL using “go run”
go get github.com/motemen/gore
Caveats 🙏
- Gore runs all code input for each run
- Code with side effects will be repeated
- eg. Printing output / Sleeping
Stories Inside Gore
Overview: not a “REPL” exactly
- REPL: Read-Eval-Print-Loop
- No “Eval” and “Print” phase
- As we do them by “go run”
- Much like: Read-Generate-Run-Loop
Read-Gen-Run-Loop
1. Read user input to evaluate
2. Generate a .go file that prints result
3. “go run” it
4. Back to 1.
Step: Read
- Codes go under AST (abstract syntax tree) form
- Syntax checking
- Easier to manipulate
- Input String → AST → .go → “go run”
Read: Input
- ! peterh/liner
- Line editing
- History
- Supports Windows
Read: Input to AST
- package go/parser
- Go has rich support for parsing/typing its code
- Easy to generate & manipulate
Read: Input to AST
- Parse input as an expression
- If failed: a statement
- Otherwise: continue input (multi-line)
Read: Expression
- Easy
- Dedicated API
- parser.ParseExpr(in)
Read: Statements
- $
func (s *Session) evalStmt(in string) error {
src := fmt.Sprintf("package P; func F() { %s }", in)
f, err := parser.ParseFile(s.Fset, "stmt.go", src, 0)
if err != nil {
return err
}
enclosingFunc := f.Scope.Lookup("F").Decl.
(*ast.FuncDecl)
stmts := enclosingFunc.Body.List
}
Generate: The Delicious Part
- Append the input AST nodes to our main()
- Add the code to print the value
Printing Values
- The generated program prints values (not gore)
- “New Values” should be printed
- Expression: Its resulting value
- Statement: Values assigned
Printing Values: Expression
- User: foo.Bar(a+1)
- Gore: __gore_p(foo.Bar(a+1))
Printing Values: Statements
- ast.AssignStmt stands for assign/define
- User: a, b := foo()
- Gore: a, b := foo(); __gore_p(a, b)
Printing Values: __gore_p()
- “Pretty prints” values
- Defined along with the main()
- Depends on installed packages
- ! k0kubun/pp, ! davecgh/go-spew or plain old %#v
The Initial .go File (pp)
package main
import "github.com/k0kubun/pp"
func __gore_p(xx ...interface{}) {
for _, x := range xx {
pp.Println(x)
}
}
func main() {
// User input goes here
}
The Initial .go File (go-spew)
package main
import "github.com/davecgh/go-spew/spew"
func __gore_p(xx ...interface{}) {
for _, x := range xx {
spew.Printf("%#vn", x)
}
}
func main() {
// User input goes here
}
The Initial .go File (%#v)
package main
import "fmt"
func __gore_p(xx ...interface{}) {
for _, x := range xx {
fmt.Printf("%#vn", x)
}
}
func main() {
// User input goes here
}
Generate: Append to main()
- Just append those generated statements

s.mainBody.List = append(s.mainBody.List, stmts…)
- Now we’ve got the working code!
- Really? No! %
Go compiler complaints (you know)
- “x declared but not used”
- “p imported but not used”
- “no new variables of left side of :=“
- & Should remove these to a successful go run
Quick Fixing Erroneous Program
- “x declared but not used”
- “p imported but not used”
- “no new variables on left side of :=“
Use it!!
Anonymize it!!
Make it `=‘ !!
“declared but not used”
package P
func main() {
s := "hello"
}
package P
func main() {
s := "hello"
_ = s
}
”imported but not used”
package P
import "fmt"
func main() {
}
package P
import _ "fmt"
func main() {
}
“no new variables on left side of :=“
package P
func main() {
var a int
a := 1
}
package P
func main() {
var a int
a = 1
}
! motemen/go-quickfix to do the work
- Type check source code using go/types.Check()
- Catch errors and modify AST
- Packed with a bin
- goquickfix -w main.go
Gore specific quickfix
- __gore_p() for non-value expressions
Running
- Output the AST to file — go/printer
- Then go run
- If failed to run, revert the last input
Recap: Read-Gen-Quickfix-Run-Loop
1. Read and parse the input to obtain AST
2. Add printing function call __gore_p()
3. Append the code to main()
4. Quickfix it so that it compiles well
5. go run
PRs welcome! 🍻
- ! motemen/gore
- ! motemen/go-quickfix
htn.to/intern2015
A Tale Gore
motemen
Go Conference 2015 Summer @ Tokyo
Appendix:
More Features
Code Completion
- liner has support for completion
- Great tool for editors: ! nsf/gocode
- Server/client model
- And an interface to it: motemen/gore/gocode
- If gocode binary can be located, use it
Commands
- :print
- :write <file>
- :import <pkg>
- :doc <expr>
:import <pkg>
- Imports arbitrary packages
- Just append import statement to the file
- Unused imports are handled by quickfix
:doc <expr>
- Invokes go doc for given expression
- Package: :doc json
- Function: :doc json.Marshal
- Method: :doc json.NewEncoder().Encode

More Related Content

What's hot

[Quase] Tudo que você precisa saber sobre tarefas assíncronas
[Quase] Tudo que você precisa saber sobre  tarefas assíncronas[Quase] Tudo que você precisa saber sobre  tarefas assíncronas
[Quase] Tudo que você precisa saber sobre tarefas assíncronasFilipe Ximenes
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run themFilipe Ximenes
 
My first program in c, hello world !
My first program in c, hello world !My first program in c, hello world !
My first program in c, hello world !Rumman Ansari
 
Laravel でやってみるクリーンアーキテクチャ #phpconfuk
Laravel でやってみるクリーンアーキテクチャ #phpconfukLaravel でやってみるクリーンアーキテクチャ #phpconfuk
Laravel でやってみるクリーンアーキテクチャ #phpconfukShohei Okada
 
Adobe董龙飞:关于PhoneGap的12件事
Adobe董龙飞:关于PhoneGap的12件事Adobe董龙飞:关于PhoneGap的12件事
Adobe董龙飞:关于PhoneGap的12件事yangdj
 
Swift: Apple's New Programming Language for iOS and OS X
Swift: Apple's New Programming Language for iOS and OS XSwift: Apple's New Programming Language for iOS and OS X
Swift: Apple's New Programming Language for iOS and OS XSasha Goldshtein
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone DevelopmentGiordano Scalzo
 
XpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayXpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayGiordano Scalzo
 
How c program execute in c program
How c program execute in c program How c program execute in c program
How c program execute in c program Rumman Ansari
 
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)Miguel Arroyo
 
Design Summit - Rails 4 Migration - Aaron Patterson
Design Summit - Rails 4 Migration - Aaron PattersonDesign Summit - Rails 4 Migration - Aaron Patterson
Design Summit - Rails 4 Migration - Aaron PattersonManageIQ
 
Functional Pearls 4 (YAPC::EU::2009 remix)
Functional Pearls 4 (YAPC::EU::2009 remix)Functional Pearls 4 (YAPC::EU::2009 remix)
Functional Pearls 4 (YAPC::EU::2009 remix)osfameron
 
__proto__-and-prototype
  __proto__-and-prototype  __proto__-and-prototype
__proto__-and-prototypeLee zhiye
 
クリーンアーキテクチャの考え方にもとづく Laravel との付き合い方 #shuuumai
クリーンアーキテクチャの考え方にもとづく Laravel との付き合い方 #shuuumaiクリーンアーキテクチャの考え方にもとづく Laravel との付き合い方 #shuuumai
クリーンアーキテクチャの考え方にもとづく Laravel との付き合い方 #shuuumaiShohei Okada
 

What's hot (20)

[Quase] Tudo que você precisa saber sobre tarefas assíncronas
[Quase] Tudo que você precisa saber sobre  tarefas assíncronas[Quase] Tudo que você precisa saber sobre  tarefas assíncronas
[Quase] Tudo que você precisa saber sobre tarefas assíncronas
 
Tasks: you gotta know how to run them
Tasks: you gotta know how to run themTasks: you gotta know how to run them
Tasks: you gotta know how to run them
 
GNU Parallel
GNU ParallelGNU Parallel
GNU Parallel
 
Qt Translations
Qt TranslationsQt Translations
Qt Translations
 
My first program in c, hello world !
My first program in c, hello world !My first program in c, hello world !
My first program in c, hello world !
 
Laravel でやってみるクリーンアーキテクチャ #phpconfuk
Laravel でやってみるクリーンアーキテクチャ #phpconfukLaravel でやってみるクリーンアーキテクチャ #phpconfuk
Laravel でやってみるクリーンアーキテクチャ #phpconfuk
 
Adobe董龙飞:关于PhoneGap的12件事
Adobe董龙飞:关于PhoneGap的12件事Adobe董龙飞:关于PhoneGap的12件事
Adobe董龙飞:关于PhoneGap的12件事
 
Swift: Apple's New Programming Language for iOS and OS X
Swift: Apple's New Programming Language for iOS and OS XSwift: Apple's New Programming Language for iOS and OS X
Swift: Apple's New Programming Language for iOS and OS X
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone Development
 
XpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayXpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp way
 
How c program execute in c program
How c program execute in c program How c program execute in c program
How c program execute in c program
 
Siddhi CEP 2nd sideshow presentation
Siddhi CEP 2nd sideshow presentationSiddhi CEP 2nd sideshow presentation
Siddhi CEP 2nd sideshow presentation
 
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
 
effective_r27
effective_r27effective_r27
effective_r27
 
Lab07 (1)
Lab07 (1)Lab07 (1)
Lab07 (1)
 
Design Summit - Rails 4 Migration - Aaron Patterson
Design Summit - Rails 4 Migration - Aaron PattersonDesign Summit - Rails 4 Migration - Aaron Patterson
Design Summit - Rails 4 Migration - Aaron Patterson
 
Functional Pearls 4 (YAPC::EU::2009 remix)
Functional Pearls 4 (YAPC::EU::2009 remix)Functional Pearls 4 (YAPC::EU::2009 remix)
Functional Pearls 4 (YAPC::EU::2009 remix)
 
Web Scraping
Web ScrapingWeb Scraping
Web Scraping
 
__proto__-and-prototype
  __proto__-and-prototype  __proto__-and-prototype
__proto__-and-prototype
 
クリーンアーキテクチャの考え方にもとづく Laravel との付き合い方 #shuuumai
クリーンアーキテクチャの考え方にもとづく Laravel との付き合い方 #shuuumaiクリーンアーキテクチャの考え方にもとづく Laravel との付き合い方 #shuuumai
クリーンアーキテクチャの考え方にもとづく Laravel との付き合い方 #shuuumai
 

Viewers also liked

Wight: Phantom’s Perl friend - YAPC::Asia 2012
Wight: Phantom’s Perl friend - YAPC::Asia 2012Wight: Phantom’s Perl friend - YAPC::Asia 2012
Wight: Phantom’s Perl friend - YAPC::Asia 2012Hiroshi Shibamura
 
Go lang(goroutine, channel, 동기화 객체)
Go lang(goroutine, channel, 동기화 객체)Go lang(goroutine, channel, 동기화 객체)
Go lang(goroutine, channel, 동기화 객체)seungkyu park
 
Virtunoid: Breaking out of KVM
Virtunoid: Breaking out of KVMVirtunoid: Breaking out of KVM
Virtunoid: Breaking out of KVMNelson Elhage
 
Introduction to DBIx::Lite - Kyoto.pm tech talk #2
Introduction to DBIx::Lite - Kyoto.pm tech talk #2Introduction to DBIx::Lite - Kyoto.pm tech talk #2
Introduction to DBIx::Lite - Kyoto.pm tech talk #2Hiroshi Shibamura
 
Go로 push agent 개선하기
Go로 push agent 개선하기Go로 push agent 개선하기
Go로 push agent 개선하기동철 박
 
Golang 으로 vision api 적용하기
Golang 으로 vision api 적용하기Golang 으로 vision api 적용하기
Golang 으로 vision api 적용하기동철 박
 
H2O x mrubyで人はどれだけ幸せになれるのか
H2O x mrubyで人はどれだけ幸せになれるのかH2O x mrubyで人はどれだけ幸せになれるのか
H2O x mrubyで人はどれだけ幸せになれるのかIchito Nagata
 

Viewers also liked (8)

Wight: Phantom’s Perl friend - YAPC::Asia 2012
Wight: Phantom’s Perl friend - YAPC::Asia 2012Wight: Phantom’s Perl friend - YAPC::Asia 2012
Wight: Phantom’s Perl friend - YAPC::Asia 2012
 
Go lang(goroutine, channel, 동기화 객체)
Go lang(goroutine, channel, 동기화 객체)Go lang(goroutine, channel, 동기화 객체)
Go lang(goroutine, channel, 동기화 객체)
 
日本の連休 2013
日本の連休 2013日本の連休 2013
日本の連休 2013
 
Virtunoid: Breaking out of KVM
Virtunoid: Breaking out of KVMVirtunoid: Breaking out of KVM
Virtunoid: Breaking out of KVM
 
Introduction to DBIx::Lite - Kyoto.pm tech talk #2
Introduction to DBIx::Lite - Kyoto.pm tech talk #2Introduction to DBIx::Lite - Kyoto.pm tech talk #2
Introduction to DBIx::Lite - Kyoto.pm tech talk #2
 
Go로 push agent 개선하기
Go로 push agent 개선하기Go로 push agent 개선하기
Go로 push agent 개선하기
 
Golang 으로 vision api 적용하기
Golang 으로 vision api 적용하기Golang 으로 vision api 적용하기
Golang 으로 vision api 적용하기
 
H2O x mrubyで人はどれだけ幸せになれるのか
H2O x mrubyで人はどれだけ幸せになれるのかH2O x mrubyで人はどれだけ幸せになれるのか
H2O x mrubyで人はどれだけ幸せになれるのか
 

Similar to Gore: Go REPL

Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes
 
Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Samuel Lampa
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Robert Stern
 
OSCON2014 : Quick Introduction to System Tools Programming with Go
OSCON2014 : Quick Introduction to System Tools Programming with GoOSCON2014 : Quick Introduction to System Tools Programming with Go
OSCON2014 : Quick Introduction to System Tools Programming with GoChris McEniry
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programmingNico Ludwig
 
Building Interpreters with PyPy
Building Interpreters with PyPyBuilding Interpreters with PyPy
Building Interpreters with PyPyDaniel Neuhäuser
 
Unix And C
Unix And CUnix And C
Unix And CDr.Ravi
 
Introduction to Assembly Language
Introduction to Assembly LanguageIntroduction to Assembly Language
Introduction to Assembly LanguageMotaz Saad
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using SwiftDiego Freniche Brito
 
PuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, Puppet
PuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, PuppetPuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, Puppet
PuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, PuppetPuppet
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoMatt Stine
 
I18nize Scala programs à la gettext
I18nize Scala programs à la gettextI18nize Scala programs à la gettext
I18nize Scala programs à la gettextNgoc Dao
 
Python - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave ParkPython - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave Parkpointstechgeeks
 

Similar to Gore: Go REPL (20)

Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1
 
OSCON2014 : Quick Introduction to System Tools Programming with Go
OSCON2014 : Quick Introduction to System Tools Programming with GoOSCON2014 : Quick Introduction to System Tools Programming with Go
OSCON2014 : Quick Introduction to System Tools Programming with Go
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
PHP 5.3/6
PHP 5.3/6PHP 5.3/6
PHP 5.3/6
 
Building Interpreters with PyPy
Building Interpreters with PyPyBuilding Interpreters with PyPy
Building Interpreters with PyPy
 
Easy R
Easy REasy R
Easy R
 
Golang workshop
Golang workshopGolang workshop
Golang workshop
 
Unix And C
Unix And CUnix And C
Unix And C
 
Introduction to Assembly Language
Introduction to Assembly LanguageIntroduction to Assembly Language
Introduction to Assembly Language
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
 
Os Treat
Os TreatOs Treat
Os Treat
 
PuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, Puppet
PuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, PuppetPuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, Puppet
PuppetConf 2017: Puppet Tasks: Taming ssh in a "for" loop- Alex Dreyer, Puppet
 
Automate Yo' Self
Automate Yo' SelfAutomate Yo' Self
Automate Yo' Self
 
Git::Hooks
Git::HooksGit::Hooks
Git::Hooks
 
A Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to GoA Recovering Java Developer Learns to Go
A Recovering Java Developer Learns to Go
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
I18nize Scala programs à la gettext
I18nize Scala programs à la gettextI18nize Scala programs à la gettext
I18nize Scala programs à la gettext
 
Python - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave ParkPython - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave Park
 

Gore: Go REPL

  • 1. A Tale of Go REPL motemen Go Conference 2015 Summer @ Tokyo
  • 2. About Me - @motemen - Web engineer - Chief engineer at Hatena, Kyoto
  • 4. Agenda - Introduction of ! motemen/gore - Gore’s architecture - Implementation details
  • 6. Case: Learning New Languages - Playing with language features - Trying libraries
  • 7. My Case — Perl - perl ~/sketch.pl - Edit and Run
  • 8. My Case — Ruby - irb - pry - A “REPL”
 (Read-Eval-Print-Loop)
  • 9. My Case — Go? - tmp.go - “packge main” “func main()” - Removing unused variables by hand - Question: Can gophers haz a REPL?
  • 10. Go "REPL" impls (AFAIK) - ! sbinet/igo — built upon ! sbinet/go-eval, with liner - ! emicklei/rango — importing, statements, listing variables - ! vito/go-repl — importing, statements, useful commands - ! d4l3k/go-pry — attaches to running program, uses reflection - (play.golang.org)
  • 11. Needed a REPL that: - Evaluates statements - Imports any module - Pretty prints values automatically - Completes code
  • 12. The Difficulties - How can we achieve Go semantics? - No APIs provided - Re-implement Go compiler? 😩
  • 14. Solution: “go run” - An “eval” to Go - Perfect implementation & Always up-to-date - Dead simple - In: a program Out: the result 🎉
  • 15. Gore: A REPL using “go run” go get github.com/motemen/gore
  • 16. Caveats 🙏 - Gore runs all code input for each run - Code with side effects will be repeated - eg. Printing output / Sleeping
  • 18. Overview: not a “REPL” exactly - REPL: Read-Eval-Print-Loop - No “Eval” and “Print” phase - As we do them by “go run” - Much like: Read-Generate-Run-Loop
  • 19. Read-Gen-Run-Loop 1. Read user input to evaluate 2. Generate a .go file that prints result 3. “go run” it 4. Back to 1.
  • 20. Step: Read - Codes go under AST (abstract syntax tree) form - Syntax checking - Easier to manipulate - Input String → AST → .go → “go run”
  • 21. Read: Input - ! peterh/liner - Line editing - History - Supports Windows
  • 22. Read: Input to AST - package go/parser - Go has rich support for parsing/typing its code - Easy to generate & manipulate
  • 23. Read: Input to AST - Parse input as an expression - If failed: a statement - Otherwise: continue input (multi-line)
  • 24. Read: Expression - Easy - Dedicated API - parser.ParseExpr(in)
  • 25. Read: Statements - $ func (s *Session) evalStmt(in string) error { src := fmt.Sprintf("package P; func F() { %s }", in) f, err := parser.ParseFile(s.Fset, "stmt.go", src, 0) if err != nil { return err } enclosingFunc := f.Scope.Lookup("F").Decl. (*ast.FuncDecl) stmts := enclosingFunc.Body.List }
  • 26. Generate: The Delicious Part - Append the input AST nodes to our main() - Add the code to print the value
  • 27. Printing Values - The generated program prints values (not gore) - “New Values” should be printed - Expression: Its resulting value - Statement: Values assigned
  • 28. Printing Values: Expression - User: foo.Bar(a+1) - Gore: __gore_p(foo.Bar(a+1))
  • 29. Printing Values: Statements - ast.AssignStmt stands for assign/define - User: a, b := foo() - Gore: a, b := foo(); __gore_p(a, b)
  • 30. Printing Values: __gore_p() - “Pretty prints” values - Defined along with the main() - Depends on installed packages - ! k0kubun/pp, ! davecgh/go-spew or plain old %#v
  • 31. The Initial .go File (pp) package main import "github.com/k0kubun/pp" func __gore_p(xx ...interface{}) { for _, x := range xx { pp.Println(x) } } func main() { // User input goes here }
  • 32. The Initial .go File (go-spew) package main import "github.com/davecgh/go-spew/spew" func __gore_p(xx ...interface{}) { for _, x := range xx { spew.Printf("%#vn", x) } } func main() { // User input goes here }
  • 33. The Initial .go File (%#v) package main import "fmt" func __gore_p(xx ...interface{}) { for _, x := range xx { fmt.Printf("%#vn", x) } } func main() { // User input goes here }
  • 34. Generate: Append to main() - Just append those generated statements
 s.mainBody.List = append(s.mainBody.List, stmts…) - Now we’ve got the working code! - Really? No! %
  • 35. Go compiler complaints (you know) - “x declared but not used” - “p imported but not used” - “no new variables of left side of :=“ - & Should remove these to a successful go run
  • 36. Quick Fixing Erroneous Program - “x declared but not used” - “p imported but not used” - “no new variables on left side of :=“ Use it!! Anonymize it!! Make it `=‘ !!
  • 37. “declared but not used” package P func main() { s := "hello" } package P func main() { s := "hello" _ = s }
  • 38. ”imported but not used” package P import "fmt" func main() { } package P import _ "fmt" func main() { }
  • 39. “no new variables on left side of :=“ package P func main() { var a int a := 1 } package P func main() { var a int a = 1 }
  • 40. ! motemen/go-quickfix to do the work - Type check source code using go/types.Check() - Catch errors and modify AST - Packed with a bin - goquickfix -w main.go
  • 41. Gore specific quickfix - __gore_p() for non-value expressions
  • 42. Running - Output the AST to file — go/printer - Then go run - If failed to run, revert the last input
  • 43. Recap: Read-Gen-Quickfix-Run-Loop 1. Read and parse the input to obtain AST 2. Add printing function call __gore_p() 3. Append the code to main() 4. Quickfix it so that it compiles well 5. go run
  • 44. PRs welcome! 🍻 - ! motemen/gore - ! motemen/go-quickfix
  • 46. A Tale Gore motemen Go Conference 2015 Summer @ Tokyo
  • 48. Code Completion - liner has support for completion - Great tool for editors: ! nsf/gocode - Server/client model - And an interface to it: motemen/gore/gocode - If gocode binary can be located, use it
  • 49. Commands - :print - :write <file> - :import <pkg> - :doc <expr>
  • 50. :import <pkg> - Imports arbitrary packages - Just append import statement to the file - Unused imports are handled by quickfix
  • 51. :doc <expr> - Invokes go doc for given expression - Package: :doc json - Function: :doc json.Marshal - Method: :doc json.NewEncoder().Encode