SlideShare ist ein Scribd-Unternehmen logo
1 von 45
Downloaden Sie, um offline zu lesen
The Go gopher was designed by Renée French.
The gopher stickers was made by Takuya Ueda.
Licensed under the Creative Commons 3.0 Attributions license.
Static Analysis in Go
@GolangUK Conference
18th Aug. 2017
1
Who am I?
Takuya Ueda
@tenntenn
➔ Work for
➔ Communities
&
Go Beginners
in Tokyo
Go Conference
in Tokyo
2
Mercari Europe
3
https://www.mercari.com/uk/
Who am I?
Takuya Ueda
@tenntenn
➔ Work for
➔ Communities
&
Go Beginners
in Tokyo
Go Conference
in Tokyo
4
Agenda
➔ Where’s Gopher?
➔ Static Analysis
➔ Static Analysis in Go
➔ Static Analysis for Products
5
Where’s Gopher?
Find Me!!
Powered by https://gopherize.me
6
Where’s Gopher?
Find Me!!
Powered by https://gopherize.me
7
Where’s “Gopher”?
type Gopher struct { Gopher string `json:"gopher"` }
func main() {
const gopher = "GOPHER"
gogopher := GOPHER()
gogopher.Gopher = gopher
fmt.Println(gogopher)
}
func GOPHER() (gopher *Gopher) {
gopher = &Gopher{ Gopher: "gopher" }
return
}
8
We love grep
$ grep Gopher main.go
type Gopher struct { Gopher string `json:"gopher"` }
gogopher.Gopher = gopher
func GOPHER() (gopher *Gopher) {
gopher = &Gopher{ Gopher: "gopher" }
We can search “Gopher” with grep.
9
Where’s “Gopher” TYPE?
type Gopher struct { Gopher string `json:"gopher"` }
func main() {
const gopher = "GOPHER"
gogopher := GOPHER()
gogopher.Gopher = gopher
fmt.Println(gogopher)
}
func GOPHER() (gopher *Gopher) {
gopher = &Gopher{ Gopher: "gopher" }
return
}
10
How to search “Gopher” type
➔ grep can search only by text
➔ The text must be understood as Go source
code
➔ We need “Static Analysis”
11
Static Analysis
12
Static Analysis & Dynamic Analysis
➔ Static Analysis
◆ Analyzing a program WITHOUT execution
◆ Analyzing structure of a program from source codes
◆ e.g. linter, code complement, code formatter
➔ Dynamic Analysis
◆ Analyzing a program WITH execution
◆ Investigating variables and result of functions
◆ e.g. race detector
13
Reflection
➔ Reflection
◆ Analyzing values and types at runtime.
➔ Reflection in Go
◆ reflect package
◆ It is only way to get struct tags at runtime
◆ encoding package uses reflection to
encode/decode JSONs, XMLs and so on.
14
Static Analysis Tools for Go
➔ There are many static analysis tools for Go
gofmt/goimports code formatter
go vet/golint code checker, linter
guru code comprehension tool
gocode code complement tool
errcheck error handlings checker
gorename/gomvpkg refactoring tools
15
Go for Static Analysis
➔ Go is easy to static analyze
◆ Static typing
◆ Simple syntax
◆ Type inference
◆ No Implicit type conversion
◆ go package is provided as a standard package
Static Analysis gives
a lot of information
16
Sub packages of go package
ast Package ast declares the types used to represent syntax trees for Go packages.
build Package build gathers information about Go packages.
constant Package constant implements Values representing untyped Go constants and their corresponding operations.
doc Package doc extracts source code documentation from a Go AST.
format Package format implements standard formatting of Go source.
importer Package importer provides access to export data importers.
parser Package parser implements a parser for Go source files.
printer Package printer implements printing of AST nodes.
scanner Package scanner implements a scanner for Go source text.
token
Package token defines constants representing the lexical tokens of the Go programming language and basic
operations on tokens (printing, predicates).
types Package types declares the data types and implements the algorithms for type-checking of Go packages.
17
Static Analysis in Go
18
Flow of Static Analysis
Source Code
Token
Abstract Syntax Tree
(AST)
Type Info
Parse
Tokenize
Type Check
go/scanner
go/token
go/parser
go/ast
go/types
go/constant
19
Tokenization - go/scanner,go/token
IDENT ADD INT
Tokens
Source Code: v + 1
➔ Dividing input string into tokens
20
Parsing - go/parser,go/ast
➔ Converting tokens to abstract syntax tree
v + 1
IDENT ADD INT
Source Code:
+
v 1
BinaryExpr
Ident BasicLit
Tokens:
Abstract Syntax Tree:
(AST)
21
AST of “Hello, World”
package main
import "fmt"
func main() {
fmt.Println("Hello, 侖界")
}
Run on Playground
*ast.File
[]ast.Decl
*ast.GenDecl *ast.FuncDecl
22
Type Check - go/types,go/constant
➔ Extract type infomation from AST
◆ Identifier Resolution
◆ Type Detection
◆ Constant Evalution
n := 100 + 200
m := n + 300
Constant Evalution
= 300
Type Detection
-> int
Identifier Resolution
23
Getting AST from source code
➔ Use parser.Parse* function
◆ ParseExpr,ParseExprFrom
● Parsing expression
● ParseExpr is simple version of ParseExprFrom
◆ ParseFile
● Parsing a file
◆ ParseDir
● Parsing files in a directory
● Calling ParseFile in the function
24
Getting AST from an expression
expr, err := parser.ParseExpr(`v + 1`)
if err != nil {
/* handling the error */
}
/* use expr */
➔ Parsing an expression
25
Getting AST from a file
const src = `
package main
var v = 100
func main() {
fmt.Println(v+1)
}`
fs := token.NewFileSet()
f, err := parser.ParseFile(fs, "my.go", src, 0)
if err != nil {
/* handling the error */
}
/* use f */
file name which is opened when
src is nil
Source Code
Parsing Mode
26
token.FileSet
➔ Recording positions on files
◆ The position (token.Pos) is represented by integer
◆ The value is unique among multiple files
◆ token.FileSet holds offset of each files
◆ The offsets are recorded at parsing
◆ token.FileSet is passed to parsing function as
an output parameter
type Pos int
27
Demo 1: Parse and Dump an AST
28
https://youtu.be/lM1Pj6xYxZs
Traversing AST - ast.Inspect
➔ Using ast.Inspect
expr, _ := parser.ParseExpr(`v + 1`)
ast.Inspect(expr, func(n ast.Node) bool {
if n != nil { fmt.Printf("%Tn", n) }
return true
})
Traverse the AST
*ast.BinaryExpr
*ast.Ident
*ast.BasicLit
Run on Playground
ast.Walk is more powerful and complex
+
v 1
BinaryExpr
Ident BasicLit
29
Traversing AST - Recursively
func traverse(n ast.Node) {
switch n := n.(type) {
case *ast.Ident:
fmt.Println(n.Name)
case *ast.BinaryExpr:
traverse(n.X)
traverse(n.Y)
case *ast.UnaryExpr:
traverse(n.X)
default:
fmt.Println(n)
}
}
print idetifyer’s name
traverse each terms recursively
switching by types
Run on Playground
traverse a term recursively
30
Demo 2: Inspect identifiers
31
https://youtu.be/mpUgaaASvHo
Type Checking
/* initialize configs for type checking */
cfg := &types.Config{Importer: importer.Default()}
info := &types.Info{
/* TODO: initialize maps which will hold results */
}
pkg,err := cfg.Check("main", fs, []*ast.File{f}, info)
if err != nil {
/* handling the error */
}
/* TODO: use pkg or info */
➔ (*types.Config).Check do a type checking
32
types.Info holds results of type checking
type Info struct {
// Types maps expressions to their types, and for constant
// expressions, also their values.
Types map[ast.Expr]TypeAndValue
// Defs maps identifiers to the objects they define.
Defs map[*ast.Ident]Object
// Uses maps identifiers to the objects they denote.
Uses map[*ast.Ident]Object
// Implicits maps nodes to their implicitly declared objects, if any.
Implicits map[ast.Node]Object
// Selections maps selector expressions (excluding qualified identifiers)
// to their corresponding selections.
Selections map[*ast.SelectorExpr]*Selection
// Scopes maps ast.Nodes to the scopes they define.
Scopes map[ast.Node]*Scope
// InitOrder is the list of package-level initializers in the order in which
// they must be executed.
InitOrder []*Initializer
}
33
Demo 3: Inspect Gopher type
34
https://youtu.be/AuSDtmiMaXI
Static Analysis for Products
Case 1: gpath,go-httpdoc
35
go.mercari.io/go-httpdoc
➔ Generate API Docs from tests of handlers
◆ Just write tests of HTTP handlers
◆ gRPC and JSON RPC are supported
36
Tests for requests and responses
➔ Requests (Responses) can be test by
specifying fields and expected values,
document for each fields
validator.RequestBody(t, []httpdoc.TestCase{
{"Name", "tenntenn", "User Name"},
{"Attribute.Email", "tenntenn@example.com", "e-mail address"},
}, &createUserRequest{})
37
github.com/tenntenn/gpath
➔ Simplefy reflection of struct fields
◆ Reflecting by expression of selectors
◆ Easy to reflect complex struct value
◆ Supports maps and slices (but restricted)
type Bar struct { N []int }
type Foo struct { Bar *Bar }
f := &Foo{ Bar: &Bar{ N: []int{100} }}
v, _ := At(f, `Bar.N[0]`)
fmt.Println(v)
$ go run main.go
100
38
Create own static analysis tools
➔ Reduce costs of code reviews by own tools
◆ Custimized linter for your project
◆ Detecting typical bugs with own tools
◆ You should pay your time for more important things
● algorithm, design, performance and so on
39
Static Analysis in Production
Case 2: Banner Tool
40
Banner Tool
➔ A management tool of in-app banners
In-App Banner
A screenshot of our app (Mercari Atte)
41
Banner Tool
➔ A management tool of in-app banners
Banner Tool
● Delivery Conditions
● Response
Getting Banners
w/ OS, API Version
List of Delivered Banners
w/ Image URL, Destination URL, etc...
Apps
42
Evaluation of Delivery Conditions
Getting Banners
GET /banner/?os=1
String(os) == "1"
Banner Image, etc...
Delivery Condition:
Banner Tool
"1" == "1"
true
BIND
EVAL
➔ Describing delivery conditions by a Go like expression
◆ Eval expressions with go package
◆ Using a function calling for describing a variable with a type
43
Conclutions
➔ Static Analysis is EASY in Go
◆ static typing, simple syntax, go package, etc...
➔ go package can
◆ tokenize, parse and type check
➔ Static analysis in production
◆ own static analysis tools (e.g. gpath, go-httpdoc)
◆ web apps (e.g. Banner Tool)
44
Thank you!
twitter: @tenntenn
Qiita: tenntenn
connpass: tenntenn
45

Weitere Àhnliche Inhalte

Was ist angesagt?

Gns3 0.5 Tutorial
Gns3 0.5 TutorialGns3 0.5 Tutorial
Gns3 0.5 Tutorial
rusevi
 

Was ist angesagt? (20)

Classless inter domain routing
Classless inter domain routingClassless inter domain routing
Classless inter domain routing
 
Self-issued OpenID Provider_OpenID Foundation Virtual Workshop
Self-issued OpenID Provider_OpenID Foundation Virtual Workshop Self-issued OpenID Provider_OpenID Foundation Virtual Workshop
Self-issued OpenID Provider_OpenID Foundation Virtual Workshop
 
Gns3 0.5 Tutorial
Gns3 0.5 TutorialGns3 0.5 Tutorial
Gns3 0.5 Tutorial
 
PyConMY 2016 Django Channels
PyConMY 2016 Django ChannelsPyConMY 2016 Django Channels
PyConMY 2016 Django Channels
 
From NAT to NAT Traversal
From NAT to NAT TraversalFrom NAT to NAT Traversal
From NAT to NAT Traversal
 
Enterprise messaging with jms
Enterprise messaging with jmsEnterprise messaging with jms
Enterprise messaging with jms
 
FIWARE Wednesday Webinars - FIWARE Overview
FIWARE Wednesday Webinars - FIWARE OverviewFIWARE Wednesday Webinars - FIWARE Overview
FIWARE Wednesday Webinars - FIWARE Overview
 
OpenID Connect: An Overview
OpenID Connect: An OverviewOpenID Connect: An Overview
OpenID Connect: An Overview
 
OpenID for Verifiable Credentials
OpenID for Verifiable CredentialsOpenID for Verifiable Credentials
OpenID for Verifiable Credentials
 
IPv6 Transition Strategies
IPv6 Transition StrategiesIPv6 Transition Strategies
IPv6 Transition Strategies
 
Session 3 - i4Trust components for Identity Management and Access Control i4T...
Session 3 - i4Trust components for Identity Management and Access Control i4T...Session 3 - i4Trust components for Identity Management and Access Control i4T...
Session 3 - i4Trust components for Identity Management and Access Control i4T...
 
Sharing 3D Cultural Heritage
Sharing 3D Cultural HeritageSharing 3D Cultural Heritage
Sharing 3D Cultural Heritage
 
OPA: The Cloud Native Policy Engine
OPA: The Cloud Native Policy EngineOPA: The Cloud Native Policy Engine
OPA: The Cloud Native Policy Engine
 
Solid pods and the future of the spatial web
Solid pods and the future of the spatial webSolid pods and the future of the spatial web
Solid pods and the future of the spatial web
 
The feature of huawei ma5600
The feature of huawei ma5600The feature of huawei ma5600
The feature of huawei ma5600
 
[Apache KafkaÂź Meetup by Confluent] Graph-based stream processing
[Apache KafkaÂź Meetup by Confluent] Graph-based stream processing[Apache KafkaÂź Meetup by Confluent] Graph-based stream processing
[Apache KafkaÂź Meetup by Confluent] Graph-based stream processing
 
ăƒ€ăƒ•ăƒŒă‚’æ”Żăˆă‚‹ăƒ‡ăƒŒă‚żă‚»ăƒłă‚żăƒăƒƒăƒˆăƒŻăƒŒă‚Ż
ăƒ€ăƒ•ăƒŒă‚’æ”Żăˆă‚‹ăƒ‡ăƒŒă‚żă‚»ăƒłă‚żăƒăƒƒăƒˆăƒŻăƒŒă‚Żăƒ€ăƒ•ăƒŒă‚’æ”Żăˆă‚‹ăƒ‡ăƒŒă‚żă‚»ăƒłă‚żăƒăƒƒăƒˆăƒŻăƒŒă‚Ż
ăƒ€ăƒ•ăƒŒă‚’æ”Żăˆă‚‹ăƒ‡ăƒŒă‚żă‚»ăƒłă‚żăƒăƒƒăƒˆăƒŻăƒŒă‚Ż
 
APIă‚šă‚łăƒŽăƒŸăƒŒæ™‚ä»ŁăźèȘèšŒăƒ»èȘćŻ
APIă‚šă‚łăƒŽăƒŸăƒŒæ™‚ä»ŁăźèȘèšŒăƒ»èȘćŻAPIă‚šă‚łăƒŽăƒŸăƒŒæ™‚ä»ŁăźèȘèšŒăƒ»èȘćŻ
APIă‚šă‚łăƒŽăƒŸăƒŒæ™‚ä»ŁăźèȘèšŒăƒ»èȘćŻ
 
Implementing Microservices with NATS
Implementing Microservices with NATSImplementing Microservices with NATS
Implementing Microservices with NATS
 
Implementing security requirements for banking API system using Open Source ...
 Implementing security requirements for banking API system using Open Source ... Implementing security requirements for banking API system using Open Source ...
Implementing security requirements for banking API system using Open Source ...
 

Andere mochten auch

Andere mochten auch (20)

Goă«ă‚ˆă‚‹iOSケプăƒȘぼ開ç™ș
Goă«ă‚ˆă‚‹iOSケプăƒȘぼ開ç™șGoă«ă‚ˆă‚‹iOSケプăƒȘぼ開ç™ș
Goă«ă‚ˆă‚‹iOSケプăƒȘぼ開ç™ș
 
Mobile Apps by Pure Go with Reverse Binding
Mobile Apps by Pure Go with Reverse BindingMobile Apps by Pure Go with Reverse Binding
Mobile Apps by Pure Go with Reverse Binding
 
Go1.8 for Google App Engine
Go1.8 for Google App EngineGo1.8 for Google App Engine
Go1.8 for Google App Engine
 
HTTP2 RFC ç™șèĄŒèš˜ćż”ç„èł€äŒš
HTTP2 RFC ç™șèĄŒèš˜ćż”ç„èł€äŒšHTTP2 RFC ç™șèĄŒèš˜ćż”ç„èł€äŒš
HTTP2 RFC ç™șèĄŒèš˜ćż”ç„èł€äŒš
 
çČ—æŽąă—ă‚’ă—ăŠGoぼコントăƒȘăƒ’ă‚™ăƒ„ăƒŒă‚żăƒŒă«ăȘるæ–čæł•
çČ—æŽąă—ă‚’ă—ăŠGoぼコントăƒȘăƒ’ă‚™ăƒ„ăƒŒă‚żăƒŒă«ăȘるæ–čæł•çČ—æŽąă—ă‚’ă—ăŠGoぼコントăƒȘăƒ’ă‚™ăƒ„ăƒŒă‚żăƒŒă«ăȘるæ–čæł•
çČ—æŽąă—ă‚’ă—ăŠGoぼコントăƒȘăƒ’ă‚™ăƒ„ăƒŒă‚żăƒŒă«ăȘるæ–čæł•
 
æĄä»¶ćŒè©•äŸĄć™šăźćźŸèŁ…ă«ă‚ˆă‚‹çźĄç†ăƒ„ăƒŒăƒ«ăźæŠœè±ĄćŒ–
æĄä»¶ćŒè©•äŸĄć™šăźćźŸèŁ…ă«ă‚ˆă‚‹çźĄç†ăƒ„ăƒŒăƒ«ăźæŠœè±ĄćŒ–æĄä»¶ćŒè©•äŸĄć™šăźćźŸèŁ…ă«ă‚ˆă‚‹çźĄç†ăƒ„ăƒŒăƒ«ăźæŠœè±ĄćŒ–
æĄä»¶ćŒè©•äŸĄć™šăźćźŸèŁ…ă«ă‚ˆă‚‹çźĄç†ăƒ„ăƒŒăƒ«ăźæŠœè±ĄćŒ–
 
Cloud FunctionsたçŽč介
Cloud FunctionsたçŽč介Cloud FunctionsたçŽč介
Cloud FunctionsたçŽč介
 
Namespace API ă‚’ç”šă„ăŸăƒžăƒ«ăƒăƒ†ăƒŠăƒłăƒˆćž‹ Web ケプăƒȘăźćźŸè·”
Namespace API ă‚’ç”šă„ăŸăƒžăƒ«ăƒăƒ†ăƒŠăƒłăƒˆćž‹ Web ケプăƒȘăźćźŸè·”Namespace API ă‚’ç”šă„ăŸăƒžăƒ«ăƒăƒ†ăƒŠăƒłăƒˆćž‹ Web ケプăƒȘăźćźŸè·”
Namespace API ă‚’ç”šă„ăŸăƒžăƒ«ăƒăƒ†ăƒŠăƒłăƒˆćž‹ Web ケプăƒȘăźćźŸè·”
 
Goă«ăŠă‘ă‚‹é™çš„è§ŁæžăšèŁœć“é–‹ç™șまぼ濜甹
Goă«ăŠă‘ă‚‹é™çš„è§ŁæžăšèŁœć“é–‹ç™șまぼ濜甹Goă«ăŠă‘ă‚‹é™çš„è§ŁæžăšèŁœć“é–‹ç™șまぼ濜甹
Goă«ăŠă‘ă‚‹é™çš„è§ŁæžăšèŁœć“é–‹ç™șまぼ濜甹
 
Goé™çš„è§Łæžăƒăƒłă‚č゙ă‚Șン
Goé™çš„è§Łæžăƒăƒłă‚č゙ă‚ȘンGoé™çš„è§Łæžăƒăƒłă‚č゙ă‚Șン
Goé™çš„è§Łæžăƒăƒłă‚č゙ă‚Șン
 
うしちゃん WebRTC Chat on SkyWayぼ開ç™șă‚łăƒŒăƒ‰ïœ—
うしちゃん WebRTC Chat on SkyWayぼ開ç™șă‚łăƒŒăƒ‰ïœ—ă†ă—ăĄă‚ƒă‚“ WebRTC Chat on SkyWayぼ開ç™șă‚łăƒŒăƒ‰ïœ—
うしちゃん WebRTC Chat on SkyWayぼ開ç™șă‚łăƒŒăƒ‰ïœ—
 
Javaăƒˆăƒ©ăƒ–ăƒ«ă«ć‚™ăˆă‚ˆă† #jjug_ccc #ccc_h2
Javaăƒˆăƒ©ăƒ–ăƒ«ă«ć‚™ăˆă‚ˆă† #jjug_ccc #ccc_h2Javaăƒˆăƒ©ăƒ–ăƒ«ă«ć‚™ăˆă‚ˆă† #jjug_ccc #ccc_h2
Javaăƒˆăƒ©ăƒ–ăƒ«ă«ć‚™ăˆă‚ˆă† #jjug_ccc #ccc_h2
 
goăƒă‚šăƒƒă‚±ăƒŒă‚·ă‚™ăŠă‚™ćž‹æƒ…ć ±ă‚’ç”šă„ăŸă‚œăƒŒă‚čă‚łăƒŒăƒˆă‚™æ€œçŽąă‚’ćźŸçŸă™ă‚‹
goăƒă‚šăƒƒă‚±ăƒŒă‚·ă‚™ăŠă‚™ćž‹æƒ…ć ±ă‚’ç”šă„ăŸă‚œăƒŒă‚čă‚łăƒŒăƒˆă‚™æ€œçŽąă‚’ćźŸçŸă™ă‚‹goăƒă‚šăƒƒă‚±ăƒŒă‚·ă‚™ăŠă‚™ćž‹æƒ…ć ±ă‚’ç”šă„ăŸă‚œăƒŒă‚čă‚łăƒŒăƒˆă‚™æ€œçŽąă‚’ćźŸçŸă™ă‚‹
goăƒă‚šăƒƒă‚±ăƒŒă‚·ă‚™ăŠă‚™ćž‹æƒ…ć ±ă‚’ç”šă„ăŸă‚œăƒŒă‚čă‚łăƒŒăƒˆă‚™æ€œçŽąă‚’ćźŸçŸă™ă‚‹
 
é™çš„è§ŁæžăšUIたè‡Șć‹•ç”Ÿæˆă‚’é§†äœżă—ăŠăƒąăƒă‚™ă‚€ăƒ«ă‚ąăƒ•ă‚šăƒȘぼ運甹コă‚čăƒˆă‚’ć€§ćč…ă«äž‹ă‘ă‚™ăŸè©±
é™çš„è§ŁæžăšUIたè‡Șć‹•ç”Ÿæˆă‚’é§†äœżă—ăŠăƒąăƒă‚™ă‚€ăƒ«ă‚ąăƒ•ă‚šăƒȘぼ運甹コă‚čăƒˆă‚’ć€§ćč…ă«äž‹ă‘ă‚™ăŸè©±é™çš„è§ŁæžăšUIたè‡Șć‹•ç”Ÿæˆă‚’é§†äœżă—ăŠăƒąăƒă‚™ă‚€ăƒ«ă‚ąăƒ•ă‚šăƒȘぼ運甹コă‚čăƒˆă‚’ć€§ćč…ă«äž‹ă‘ă‚™ăŸè©±
é™çš„è§ŁæžăšUIたè‡Șć‹•ç”Ÿæˆă‚’é§†äœżă—ăŠăƒąăƒă‚™ă‚€ăƒ«ă‚ąăƒ•ă‚šăƒȘぼ運甹コă‚čăƒˆă‚’ć€§ćč…ă«äž‹ă‘ă‚™ăŸè©±
 
Cloud functionsたçŽč介
Cloud functionsたçŽč介Cloud functionsたçŽč介
Cloud functionsたçŽč介
 
ăƒĄăƒ«ă‚«ăƒȘăƒ»ă‚œă‚Šă‚Ÿă‚Šă§ăŻ どうGoă‚’æŽ»ç”šă—ăŠă„ă‚‹ăźă‹ïŒŸ
ăƒĄăƒ«ă‚«ăƒȘăƒ»ă‚œă‚Šă‚Ÿă‚Šă§ăŻ どうGoă‚’æŽ»ç”šă—ăŠă„ă‚‹ăźă‹ïŒŸăƒĄăƒ«ă‚«ăƒȘăƒ»ă‚œă‚Šă‚Ÿă‚Šă§ăŻ どうGoă‚’æŽ»ç”šă—ăŠă„ă‚‹ăźă‹ïŒŸ
ăƒĄăƒ«ă‚«ăƒȘăƒ»ă‚œă‚Šă‚Ÿă‚Šă§ăŻ どうGoă‚’æŽ»ç”šă—ăŠă„ă‚‹ăźă‹ïŒŸ
 
HTTP2 æ™‚ä»Łăź Web - web over http2
HTTP2 æ™‚ä»Łăź Web - web over http2HTTP2 æ™‚ä»Łăź Web - web over http2
HTTP2 æ™‚ä»Łăź Web - web over http2
 
ă‚Șă‚čă‚čăƒĄăźæš™æș–ăƒ»æș–æš™æș–ăƒă‚šăƒƒă‚±ăƒŒă‚·ă‚™20遞
ă‚Șă‚čă‚čăƒĄăźæš™æș–ăƒ»æș–æš™æș–ăƒă‚šăƒƒă‚±ăƒŒă‚·ă‚™20遞ă‚Șă‚čă‚čăƒĄăźæš™æș–ăƒ»æș–æš™æș–ăƒă‚šăƒƒă‚±ăƒŒă‚·ă‚™20遞
ă‚Șă‚čă‚čăƒĄăźæš™æș–ăƒ»æș–æš™æș–ăƒă‚šăƒƒă‚±ăƒŒă‚·ă‚™20遞
 
Google Assistanté–ąäż‚ăźă‚»ăƒƒă‚·ăƒ§ăƒłăŸăšă‚
Google Assistanté–ąäż‚ăźă‚»ăƒƒă‚·ăƒ§ăƒłăŸăšă‚Google Assistanté–ąäż‚ăźă‚»ăƒƒă‚·ăƒ§ăƒłăŸăšă‚
Google Assistanté–ąäż‚ăźă‚»ăƒƒă‚·ăƒ§ăƒłăŸăšă‚
 
WebRTC Browsers n Stacks Implementation differences
WebRTC Browsers n Stacks Implementation differencesWebRTC Browsers n Stacks Implementation differences
WebRTC Browsers n Stacks Implementation differences
 

Ähnlich wie Static Analysis in Go

Python-GTK
Python-GTKPython-GTK
Python-GTK
Yuren Ju
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manual
Sami Said
 
Python GTK (Hacking Camp)
Python GTK (Hacking Camp)Python GTK (Hacking Camp)
Python GTK (Hacking Camp)
Yuren Ju
 
An Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax TreesAn Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax Trees
Ray Toal
 

Ähnlich wie Static Analysis in Go (20)

Golang
GolangGolang
Golang
 
Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
Python-GTK
Python-GTKPython-GTK
Python-GTK
 
Lex tool manual
Lex tool manualLex tool manual
Lex tool manual
 
Python GTK (Hacking Camp)
Python GTK (Hacking Camp)Python GTK (Hacking Camp)
Python GTK (Hacking Camp)
 
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
 
JavaZone 2014 - goto java;
JavaZone 2014 - goto java;JavaZone 2014 - goto java;
JavaZone 2014 - goto java;
 
Compact ordered dict__k_lab_meeting_
Compact ordered dict__k_lab_meeting_Compact ordered dict__k_lab_meeting_
Compact ordered dict__k_lab_meeting_
 
Golang 101
Golang 101Golang 101
Golang 101
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to Gophers
 
Vocabulary Types in C++17
Vocabulary Types in C++17Vocabulary Types in C++17
Vocabulary Types in C++17
 
Let's Go-lang
Let's Go-langLet's Go-lang
Let's Go-lang
 
An Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax TreesAn Annotation Framework for Statically-Typed Syntax Trees
An Annotation Framework for Statically-Typed Syntax Trees
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Pseudo dynamic immutable records in C++
Pseudo dynamic immutable records in C++Pseudo dynamic immutable records in C++
Pseudo dynamic immutable records in C++
 
Gunosy.go #4 go
Gunosy.go #4 goGunosy.go #4 go
Gunosy.go #4 go
 
Groovy AST Transformations
Groovy AST TransformationsGroovy AST Transformations
Groovy AST Transformations
 
Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Python basic
Python basicPython basic
Python basic
 

Mehr von Takuya Ueda

Mehr von Takuya Ueda (15)

Goă«ăŠă‘ă‚‹ăƒăƒŒă‚žăƒ§ăƒłçźĄç†ăźćż…èŠæ€§ − vgoに぀いお −
Goă«ăŠă‘ă‚‹ăƒăƒŒă‚žăƒ§ăƒłçźĄç†ăźćż…èŠæ€§ − vgoに぀いお −Goă«ăŠă‘ă‚‹ăƒăƒŒă‚žăƒ§ăƒłçźĄç†ăźćż…èŠæ€§ − vgoに぀いお −
Goă«ăŠă‘ă‚‹ăƒăƒŒă‚žăƒ§ăƒłçźĄç†ăźćż…èŠæ€§ − vgoに぀いお −
 
WebAssembly with Go
WebAssembly with GoWebAssembly with Go
WebAssembly with Go
 
GAE/Goずsyncăƒ‘ăƒƒă‚±ăƒŒă‚ž
GAE/Goずsyncăƒ‘ăƒƒă‚±ăƒŒă‚žGAE/Goずsyncăƒ‘ăƒƒă‚±ăƒŒă‚ž
GAE/Goずsyncăƒ‘ăƒƒă‚±ăƒŒă‚ž
 
é™çš„è§Łæžă‚’äœżăŁăŸé–‹ç™șăƒ„ăƒŒăƒ«ăźé–‹ç™ș
é™çš„è§Łæžă‚’äœżăŁăŸé–‹ç™șăƒ„ăƒŒăƒ«ăźé–‹ç™șé™çš„è§Łæžă‚’äœżăŁăŸé–‹ç™șăƒ„ăƒŒăƒ«ăźé–‹ç™ș
é™çš„è§Łæžă‚’äœżăŁăŸé–‹ç™șăƒ„ăƒŒăƒ«ăźé–‹ç™ș
 
そうだ、Goを構めよう
そうだ、Goを構めようそうだ、Goを構めよう
そうだ、Goを構めよう
 
マă‚čă‚żăƒŒăƒ»ă‚Șăƒ•ă‚™ăƒ»goăƒă‚šăƒƒă‚±ăƒŒă‚·ă‚™
マă‚čă‚żăƒŒăƒ»ă‚Șăƒ•ă‚™ăƒ»goăƒă‚šăƒƒă‚±ăƒŒă‚·ă‚™ăƒžă‚čă‚żăƒŒăƒ»ă‚Șăƒ•ă‚™ăƒ»goăƒă‚šăƒƒă‚±ăƒŒă‚·ă‚™
マă‚čă‚żăƒŒăƒ»ă‚Șăƒ•ă‚™ăƒ»goăƒă‚šăƒƒă‚±ăƒŒă‚·ă‚™
 
ăƒĄăƒ«ă‚«ăƒȘ ă‚«ă‚Šăƒ«ăźăƒžă‚čă‚żăƒ†ă‚™ăƒŒă‚żăźæ›Žæ–°
ăƒĄăƒ«ă‚«ăƒȘ ă‚«ă‚Šăƒ«ăźăƒžă‚čă‚żăƒ†ă‚™ăƒŒă‚żăźæ›Žæ–°ăƒĄăƒ«ă‚«ăƒȘ ă‚«ă‚Šăƒ«ăźăƒžă‚čă‚żăƒ†ă‚™ăƒŒă‚żăźæ›Žæ–°
ăƒĄăƒ«ă‚«ăƒȘ ă‚«ă‚Šăƒ«ăźăƒžă‚čă‚żăƒ†ă‚™ăƒŒă‚żăźæ›Žæ–°
 
Go Friday ć‚‘äœœéž
Go Friday ć‚‘äœœéžGo Friday ć‚‘äœœéž
Go Friday ć‚‘äœœéž
 
スキă‚čăƒă‚šăƒŒăƒˆGo
スキă‚čăƒă‚šăƒŒăƒˆGoスキă‚čăƒă‚šăƒŒăƒˆGo
スキă‚čăƒă‚šăƒŒăƒˆGo
 
Gopher Fest 2017ć‚ćŠ ăƒŹăƒ›ă‚šăƒŒăƒˆ
Gopher Fest 2017ć‚ćŠ ăƒŹăƒ›ă‚šăƒŒăƒˆGopher Fest 2017ć‚ćŠ ăƒŹăƒ›ă‚šăƒŒăƒˆ
Gopher Fest 2017ć‚ćŠ ăƒŹăƒ›ă‚šăƒŒăƒˆ
 
GoăŠă‚™ă‹ă‚“ăŸă‚“ă‚œăƒŒă‚čă‚łăƒŒăƒˆă‚™ăźé™çš„è§Łæž
GoăŠă‚™ă‹ă‚“ăŸă‚“ă‚œăƒŒă‚čă‚łăƒŒăƒˆă‚™ăźé™çš„è§ŁæžGoăŠă‚™ă‹ă‚“ăŸă‚“ă‚œăƒŒă‚čă‚łăƒŒăƒˆă‚™ăźé™çš„è§Łæž
GoăŠă‚™ă‹ă‚“ăŸă‚“ă‚œăƒŒă‚čă‚łăƒŒăƒˆă‚™ăźé™çš„è§Łæž
 
Goど゙webケプăƒȘを開ç™șしどみよう
Goど゙webケプăƒȘを開ç™șしどみようGoど゙webケプăƒȘを開ç™șしどみよう
Goど゙webケプăƒȘを開ç™șしどみよう
 
GAE/Goど゙WebケプăƒȘ開ç™șć…„é–€
GAE/Goど゙WebケプăƒȘ開ç™șć…„é–€GAE/Goど゙WebケプăƒȘ開ç™șć…„é–€
GAE/Goど゙WebケプăƒȘ開ç™șć…„é–€
 
GAEGoど゙LINE Messaging API ă‚’äœżă†
GAEGoど゙LINE Messaging API ă‚’äœżă†GAEGoど゙LINE Messaging API ă‚’äœżă†
GAEGoど゙LINE Messaging API ă‚’äœżă†
 
ăƒĄăƒ«ă‚«ăƒȘă‚ąăƒƒăƒ†ăźćźŸć‹™ăŠă‚™äœżăˆăŸă€GAE/Goぼ開ç™șをćŠč率的にするæ–čæł•
ăƒĄăƒ«ă‚«ăƒȘă‚ąăƒƒăƒ†ăźćźŸć‹™ăŠă‚™äœżăˆăŸă€GAE/Goぼ開ç™șをćŠč率的にするæ–čæł•ăƒĄăƒ«ă‚«ăƒȘă‚ąăƒƒăƒ†ăźćźŸć‹™ăŠă‚™äœżăˆăŸă€GAE/Goぼ開ç™șをćŠč率的にするæ–čæł•
ăƒĄăƒ«ă‚«ăƒȘă‚ąăƒƒăƒ†ăźćźŸć‹™ăŠă‚™äœżăˆăŸă€GAE/Goぼ開ç™șをćŠč率的にするæ–čæł•
 

KĂŒrzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

KĂŒrzlich hochgeladen (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 

Static Analysis in Go

  • 1. The Go gopher was designed by RenĂ©e French. The gopher stickers was made by Takuya Ueda. Licensed under the Creative Commons 3.0 Attributions license. Static Analysis in Go @GolangUK Conference 18th Aug. 2017 1
  • 2. Who am I? Takuya Ueda @tenntenn ➔ Work for ➔ Communities & Go Beginners in Tokyo Go Conference in Tokyo 2
  • 4. Who am I? Takuya Ueda @tenntenn ➔ Work for ➔ Communities & Go Beginners in Tokyo Go Conference in Tokyo 4
  • 5. Agenda ➔ Where’s Gopher? ➔ Static Analysis ➔ Static Analysis in Go ➔ Static Analysis for Products 5
  • 6. Where’s Gopher? Find Me!! Powered by https://gopherize.me 6
  • 7. Where’s Gopher? Find Me!! Powered by https://gopherize.me 7
  • 8. Where’s “Gopher”? type Gopher struct { Gopher string `json:"gopher"` } func main() { const gopher = "GOPHER" gogopher := GOPHER() gogopher.Gopher = gopher fmt.Println(gogopher) } func GOPHER() (gopher *Gopher) { gopher = &Gopher{ Gopher: "gopher" } return } 8
  • 9. We love grep $ grep Gopher main.go type Gopher struct { Gopher string `json:"gopher"` } gogopher.Gopher = gopher func GOPHER() (gopher *Gopher) { gopher = &Gopher{ Gopher: "gopher" } We can search “Gopher” with grep. 9
  • 10. Where’s “Gopher” TYPE? type Gopher struct { Gopher string `json:"gopher"` } func main() { const gopher = "GOPHER" gogopher := GOPHER() gogopher.Gopher = gopher fmt.Println(gogopher) } func GOPHER() (gopher *Gopher) { gopher = &Gopher{ Gopher: "gopher" } return } 10
  • 11. How to search “Gopher” type ➔ grep can search only by text ➔ The text must be understood as Go source code ➔ We need “Static Analysis” 11
  • 13. Static Analysis & Dynamic Analysis ➔ Static Analysis ◆ Analyzing a program WITHOUT execution ◆ Analyzing structure of a program from source codes ◆ e.g. linter, code complement, code formatter ➔ Dynamic Analysis ◆ Analyzing a program WITH execution ◆ Investigating variables and result of functions ◆ e.g. race detector 13
  • 14. Reflection ➔ Reflection ◆ Analyzing values and types at runtime. ➔ Reflection in Go ◆ reflect package ◆ It is only way to get struct tags at runtime ◆ encoding package uses reflection to encode/decode JSONs, XMLs and so on. 14
  • 15. Static Analysis Tools for Go ➔ There are many static analysis tools for Go gofmt/goimports code formatter go vet/golint code checker, linter guru code comprehension tool gocode code complement tool errcheck error handlings checker gorename/gomvpkg refactoring tools 15
  • 16. Go for Static Analysis ➔ Go is easy to static analyze ◆ Static typing ◆ Simple syntax ◆ Type inference ◆ No Implicit type conversion ◆ go package is provided as a standard package Static Analysis gives a lot of information 16
  • 17. Sub packages of go package ast Package ast declares the types used to represent syntax trees for Go packages. build Package build gathers information about Go packages. constant Package constant implements Values representing untyped Go constants and their corresponding operations. doc Package doc extracts source code documentation from a Go AST. format Package format implements standard formatting of Go source. importer Package importer provides access to export data importers. parser Package parser implements a parser for Go source files. printer Package printer implements printing of AST nodes. scanner Package scanner implements a scanner for Go source text. token Package token defines constants representing the lexical tokens of the Go programming language and basic operations on tokens (printing, predicates). types Package types declares the data types and implements the algorithms for type-checking of Go packages. 17
  • 19. Flow of Static Analysis Source Code Token Abstract Syntax Tree (AST) Type Info Parse Tokenize Type Check go/scanner go/token go/parser go/ast go/types go/constant 19
  • 20. Tokenization - go/scanner,go/token IDENT ADD INT Tokens Source Code: v + 1 ➔ Dividing input string into tokens 20
  • 21. Parsing - go/parser,go/ast ➔ Converting tokens to abstract syntax tree v + 1 IDENT ADD INT Source Code: + v 1 BinaryExpr Ident BasicLit Tokens: Abstract Syntax Tree: (AST) 21
  • 22. AST of “Hello, World” package main import "fmt" func main() { fmt.Println("Hello, 侖界") } Run on Playground *ast.File []ast.Decl *ast.GenDecl *ast.FuncDecl 22
  • 23. Type Check - go/types,go/constant ➔ Extract type infomation from AST ◆ Identifier Resolution ◆ Type Detection ◆ Constant Evalution n := 100 + 200 m := n + 300 Constant Evalution = 300 Type Detection -> int Identifier Resolution 23
  • 24. Getting AST from source code ➔ Use parser.Parse* function ◆ ParseExpr,ParseExprFrom ● Parsing expression ● ParseExpr is simple version of ParseExprFrom ◆ ParseFile ● Parsing a file ◆ ParseDir ● Parsing files in a directory ● Calling ParseFile in the function 24
  • 25. Getting AST from an expression expr, err := parser.ParseExpr(`v + 1`) if err != nil { /* handling the error */ } /* use expr */ ➔ Parsing an expression 25
  • 26. Getting AST from a file const src = ` package main var v = 100 func main() { fmt.Println(v+1) }` fs := token.NewFileSet() f, err := parser.ParseFile(fs, "my.go", src, 0) if err != nil { /* handling the error */ } /* use f */ file name which is opened when src is nil Source Code Parsing Mode 26
  • 27. token.FileSet ➔ Recording positions on files ◆ The position (token.Pos) is represented by integer ◆ The value is unique among multiple files ◆ token.FileSet holds offset of each files ◆ The offsets are recorded at parsing ◆ token.FileSet is passed to parsing function as an output parameter type Pos int 27
  • 28. Demo 1: Parse and Dump an AST 28 https://youtu.be/lM1Pj6xYxZs
  • 29. Traversing AST - ast.Inspect ➔ Using ast.Inspect expr, _ := parser.ParseExpr(`v + 1`) ast.Inspect(expr, func(n ast.Node) bool { if n != nil { fmt.Printf("%Tn", n) } return true }) Traverse the AST *ast.BinaryExpr *ast.Ident *ast.BasicLit Run on Playground ast.Walk is more powerful and complex + v 1 BinaryExpr Ident BasicLit 29
  • 30. Traversing AST - Recursively func traverse(n ast.Node) { switch n := n.(type) { case *ast.Ident: fmt.Println(n.Name) case *ast.BinaryExpr: traverse(n.X) traverse(n.Y) case *ast.UnaryExpr: traverse(n.X) default: fmt.Println(n) } } print idetifyer’s name traverse each terms recursively switching by types Run on Playground traverse a term recursively 30
  • 31. Demo 2: Inspect identifiers 31 https://youtu.be/mpUgaaASvHo
  • 32. Type Checking /* initialize configs for type checking */ cfg := &types.Config{Importer: importer.Default()} info := &types.Info{ /* TODO: initialize maps which will hold results */ } pkg,err := cfg.Check("main", fs, []*ast.File{f}, info) if err != nil { /* handling the error */ } /* TODO: use pkg or info */ ➔ (*types.Config).Check do a type checking 32
  • 33. types.Info holds results of type checking type Info struct { // Types maps expressions to their types, and for constant // expressions, also their values. Types map[ast.Expr]TypeAndValue // Defs maps identifiers to the objects they define. Defs map[*ast.Ident]Object // Uses maps identifiers to the objects they denote. Uses map[*ast.Ident]Object // Implicits maps nodes to their implicitly declared objects, if any. Implicits map[ast.Node]Object // Selections maps selector expressions (excluding qualified identifiers) // to their corresponding selections. Selections map[*ast.SelectorExpr]*Selection // Scopes maps ast.Nodes to the scopes they define. Scopes map[ast.Node]*Scope // InitOrder is the list of package-level initializers in the order in which // they must be executed. InitOrder []*Initializer } 33
  • 34. Demo 3: Inspect Gopher type 34 https://youtu.be/AuSDtmiMaXI
  • 35. Static Analysis for Products Case 1: gpath,go-httpdoc 35
  • 36. go.mercari.io/go-httpdoc ➔ Generate API Docs from tests of handlers ◆ Just write tests of HTTP handlers ◆ gRPC and JSON RPC are supported 36
  • 37. Tests for requests and responses ➔ Requests (Responses) can be test by specifying fields and expected values, document for each fields validator.RequestBody(t, []httpdoc.TestCase{ {"Name", "tenntenn", "User Name"}, {"Attribute.Email", "tenntenn@example.com", "e-mail address"}, }, &createUserRequest{}) 37
  • 38. github.com/tenntenn/gpath ➔ Simplefy reflection of struct fields ◆ Reflecting by expression of selectors ◆ Easy to reflect complex struct value ◆ Supports maps and slices (but restricted) type Bar struct { N []int } type Foo struct { Bar *Bar } f := &Foo{ Bar: &Bar{ N: []int{100} }} v, _ := At(f, `Bar.N[0]`) fmt.Println(v) $ go run main.go 100 38
  • 39. Create own static analysis tools ➔ Reduce costs of code reviews by own tools ◆ Custimized linter for your project ◆ Detecting typical bugs with own tools ◆ You should pay your time for more important things ● algorithm, design, performance and so on 39
  • 40. Static Analysis in Production Case 2: Banner Tool 40
  • 41. Banner Tool ➔ A management tool of in-app banners In-App Banner A screenshot of our app (Mercari Atte) 41
  • 42. Banner Tool ➔ A management tool of in-app banners Banner Tool ● Delivery Conditions ● Response Getting Banners w/ OS, API Version List of Delivered Banners w/ Image URL, Destination URL, etc... Apps 42
  • 43. Evaluation of Delivery Conditions Getting Banners GET /banner/?os=1 String(os) == "1" Banner Image, etc... Delivery Condition: Banner Tool "1" == "1" true BIND EVAL ➔ Describing delivery conditions by a Go like expression ◆ Eval expressions with go package ◆ Using a function calling for describing a variable with a type 43
  • 44. Conclutions ➔ Static Analysis is EASY in Go ◆ static typing, simple syntax, go package, etc... ➔ go package can ◆ tokenize, parse and type check ➔ Static analysis in production ◆ own static analysis tools (e.g. gpath, go-httpdoc) ◆ web apps (e.g. Banner Tool) 44
  • 45. Thank you! twitter: @tenntenn Qiita: tenntenn connpass: tenntenn 45