Created
February 24, 2024 00:14
-
-
Save ras0q/57f67b8d67622aaefbcbffd041e44e7d to your computer and use it in GitHub Desktop.
assert(a<b)を渡した時にassertの内側からa<bを文字列として出力する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "bytes" | |
| "fmt" | |
| "go/ast" | |
| "go/parser" | |
| "go/printer" | |
| "go/token" | |
| "runtime" | |
| ) | |
| func main() { | |
| assert(1 < 2) | |
| assert(1 > 2) | |
| } | |
| func assert(cond bool) { | |
| if cond { | |
| return | |
| } | |
| pc, file, line, ok := runtime.Caller(0) | |
| fmt.Println(pc, file, line, ok) | |
| fset := token.NewFileSet() | |
| f, err := parser.ParseFile(fset, file, nil, parser.ParseComments) | |
| if err != nil { | |
| panic(err) | |
| } | |
| ast.Inspect(f, func(node ast.Node) bool { | |
| if callExpr, ok := node.(*ast.CallExpr); ok { | |
| ident, ok := callExpr.Fun.(*ast.Ident) | |
| if !ok { | |
| return true | |
| } | |
| if ident.Name == "assert" { // TODO: use runtime.FuncForPC | |
| var buf bytes.Buffer | |
| printer.Fprint(&buf, fset, callExpr.Args[0]) | |
| fmt.Println("args", buf.String()) | |
| } | |
| } | |
| return true | |
| }) | |
| } | |
| // Output: | |
| // 5112365 /tmp/main.go 25 true | |
| // args 1 < 2 | |
| // args 1 > 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment