Skip to content

Instantly share code, notes, and snippets.

@BrentFarris
Created October 14, 2023 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrentFarris/41c3a305406a3c569e81ccc50a9506bf to your computer and use it in GitHub Desktop.
Save BrentFarris/41c3a305406a3c569e81ccc50a9506bf to your computer and use it in GitHub Desktop.
Go Generate and AST
fs := token.NewFileSet()
ast, err := parser.ParseFile(fs, filePath, orFileSrc, parser.ParseComments)
file := os.Getenv("GOFILE")
//pkg := os.Getenv("GOPACKAGE")
fs := token.NewFileSet()
astRes, _ := parser.ParseFile(fs, file, "", parser.ParseComments)
allStructs := []*ast.TypeSpec{}
for _, d := range astRes.Decls {
if g, ok := d.(*ast.GenDecl); ok {
allStructs = append(allStructs, g.Specs[0].(*ast.TypeSpec))
}
}
log.Println(len(allStructs))
file := os.Getenv("GOFILE")
//pkg := os.Getenv("GOPACKAGE")
fs := token.NewFileSet()
pos := 1 // The linear position of this generate comment
lineNum, _ := strconv.Atoi(os.Getenv("GOLINE"))
fileSrc, _ := os.ReadFile(file)
reader := strings.NewReader(string(fileSrc))
for lineNum > 0 {
if r, _, _ := reader.ReadRune(); r == '\n' {
lineNum--
}
pos++
}
astRes, _ := parser.ParseFile(fs, "", fileSrc, parser.ParseComments)
var structSpec *ast.TypeSpec = nil
for _, d := range astRes.Decls {
if d.Pos() == token.Pos(pos) {
if g, ok := d.(*ast.GenDecl); ok {
structSpec = g.Specs[0].(*ast.TypeSpec)
}
}
}
log.Println(structSpec.Name.Name)
//go:generate go run ../generators/serialized/main.go
type SerializableThing struct {
number int
name string
position [4]float32
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment