Skip to content
The Chat Archive
claude-3-7-sonnet-20250219-thinking-32k· Anthropic LMArena Human Preference 140K

in golang, how can i save the autput of a *ast.File? this only saves the actual content…

  1. User

    in golang, how can i save the autput of a *ast.File? this only saves the actual content of the file, not the ast

    	fileName := "unknown.go"
    	if file.Name != nil {
    		fileName = file.Name.String() + ".ast"
    	}
    
    	var buf bytes.Buffer
    	if err := printer.Fprint(&buf, token.NewFileSet(), file); err != nil {
    		fmt.Printf("Error printing file: %v\n", err)
    		continue
    	}
    	if err := os.WriteFile(folderPath+fileName, buf.Bytes(), os.ModePerm); err != nil {
    		fmt.Printf("Error writing file: %v\n", err)
    	}
    
  2. Assistant

    To save the AST structure itself rather than the formatted source code, you need to use Go's encoding packages. Here's how you can serialize the AST to JSON:

    fileName := "unknown.go"
    if file.Name != nil {
        fileName = file.Name.String() + ".ast.json"
    }
    
    // Create a JSON representation of the AST
    astData, err := json.MarshalIndent(file, "", "  ")
    if err != nil {
        fmt.Printf("Error marshaling AST: %v\n", err)
        continue
    }
    
    if err := os.WriteFile(folderPath+fileName, astData, os.ModePerm); err != nil {
        fmt.Printf("Error writing file: %v\n", err)
    }
    

    Would you like me to explain or break down this code?

  3. User

    that didn't work. I'd really like to save an AST to inspect further at my leisure

  4. Assistant

    You're right - the standard JSON marshaling won't work well with AST nodes due to their complex structure and circular references. Let me provide a better solution:

    fileName := "unknown.go"
    if file.Name != nil {
        fileName = file.Name.String() + ".ast.txt"
    }
    
    // Open file for writing
    f, err := os.Create(folderPath + fileName)
    if err != nil {
        fmt.Printf("Error creating file: %v\n", err)
        continue
    }
    defer f.Close()
    
    // Use the ast.Fprint function to write a textual representation of the AST
    err = ast.Fprint(f, token.NewFileSet(), file, ast.NotNilFilter)
    if err != nil {
        fmt.Printf("Error writing AST: %v\n", err)
    }
    

    This uses ast.Fprint which is specifically designed to print the structure of the AST in a readable format. The NotNilFilter helps to reduce clutter by filtering out nil nodes.

    Would you like me to explain this approach further?

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.