Skip to content

Instantly share code, notes, and snippets.

@seafitliu
Forked from zupzup/main.go
Created December 14, 2022 06:19
Show Gist options
  • Select an option

  • Save seafitliu/a1e65313c99eee901afde1f91e7a5883 to your computer and use it in GitHub Desktop.

Select an option

Save seafitliu/a1e65313c99eee901afde1f91e7a5883 to your computer and use it in GitHub Desktop.

Revisions

  1. @zupzup zupzup created this gist Jul 14, 2017.
    63 changes: 63 additions & 0 deletions main.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,63 @@
    package main

    import (
    "fmt"
    "go/ast"
    "go/parser"
    "go/printer"
    "go/token"
    "log"
    "os"
    )

    func main() {
    fset := token.NewFileSet()
    node, err := parser.ParseFile(fset, "test.go", nil, parser.ParseComments)
    if err != nil {
    log.Fatal(err)
    }

    fmt.Println("########### Manual Iteration ###########")

    fmt.Println("Imports:")
    for _, i := range node.Imports {
    fmt.Println(i.Path.Value)
    }

    fmt.Println("Comments:")
    for _, c := range node.Comments {
    fmt.Print(c.Text())
    }

    fmt.Println("Functions:")
    for _, f := range node.Decls {
    fn, ok := f.(*ast.FuncDecl)
    if !ok {
    continue
    }
    fmt.Println(fn.Name.Name)
    }

    fmt.Println("########### Inspect ###########")
    ast.Inspect(node, func(n ast.Node) bool {
    // Find Return Statements
    ret, ok := n.(*ast.ReturnStmt)
    if ok {
    fmt.Printf("return statement found on line %d:\n\t", fset.Position(ret.Pos()).Line)
    printer.Fprint(os.Stdout, fset, ret)
    return true
    }
    // Find Functions
    fn, ok := n.(*ast.FuncDecl)
    if ok {
    var exported string
    if fn.Name.IsExported() {
    exported = "exported "
    }
    fmt.Printf("%sfunction declaration found on line %d: \n\t%s\n", exported, fset.Position(fn.Pos()).Line, fn.Name.Name)
    return true
    }
    return true
    })
    fmt.Println()
    }
    21 changes: 21 additions & 0 deletions test.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    package main

    import "fmt"
    import "strings"

    func main() {
    hello := "Hello"
    world := "World"
    words := []string{hello, world}
    SayHello(words)
    }

    // SayHello says Hello
    func SayHello(words []string) {
    fmt.Println(joinStrings(words))
    }

    // joinStrings joins strings
    func joinStrings(words []string) string {
    return strings.Join(words, ", ")
    }