clove/code4dyslexia
src/go_adapter.go
// src/go_adapter.go
package main
import (
"encoding/json"
"errors"
"fmt"
"go/ast"
"go/parser"
"go/scanner"
"go/token"
"io"
"os"
"sort"
"strings"
)
type request struct {
Source, Path string
Indent, Newlines int
Header, Names bool
}
type issue struct {
Offset int `json:"offset"`
Rule string `json:"rule"`
Message string `json:"message"`
}
type result struct {
Formatted string `json:"formatted"`
Issues []issue `json:"issues"`
Names [][3]any `json:"names"`
Error string `json:"error,omitempty"`
Offset int `json:"offset,omitempty"`
}
type edit struct {
start, end int
replacement, rule, message string
}
type scanned struct {
offset int
kind token.Token
literal string
}
func scan(source string) []scanned {
files := token.NewFileSet()
file := files.AddFile("", -1, len(source))
var lexer scanner.Scanner
lexer.Init(file, []byte(source), nil, scanner.ScanComments)
var tokens []scanned
for {
position, kind, literal := lexer.Scan()
if kind == token.EOF {
return tokens
}
tokens = append(tokens, scanned{file.Offset(position), kind, literal})
}
}
func sameTokens(original, proposed []scanned) bool {
if len(original) != len(proposed) {
return false
}
for index, before := range original {
after := proposed[index]
if before.kind != after.kind || before.literal != after.literal {
return false
}
}
return true
}
func spacing[T ast.Node](source string, file *token.File, nodes []T, width int, edits *[]edit) {
for index := 1; index < len(nodes); index++ {
left, right := nodes[index-1], nodes[index]
if !logicalBlock(left) && !logicalBlock(right) {
continue
}
start := file.Offset(left.End())
rightOffset := file.Offset(right.Pos())
// Preserve comment attachment, including documentation and compiler directives.
end := file.Offset(file.LineStart(file.PositionFor(file.Pos(rightOffset), false).Line))
if end <= start {
continue
}
gap := source[start:end]
count := strings.Count(gap, "\n")
if count == width || strings.Trim(gap, " \t\r\n") != "" {
continue
}
first := strings.IndexByte(gap, '\n')
ending := "\n"
if first > 0 && gap[first-1] == '\r' {
ending = "\r\n"
}
*edits = append(*edits, edit{
start, end, strings.Repeat(ending, width), "formatting.newLineSize",
fmt.Sprintf("Expected %d newline character(s) between logical blocks", width),
})
}
}
func logicalBlock(node ast.Node) bool {
switch node := node.(type) {
case *ast.FuncDecl, *ast.BlockStmt, *ast.IfStmt, *ast.ForStmt, *ast.RangeStmt,
*ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt:
return true
case *ast.GenDecl:
return node.Tok == token.TYPE || node.Lparen.IsValid()
default:
return false
}
}
func indentation(source string, file *token.File, tokens []scanned, width, bom int, edits *[]edit) {
depth := 0
previousLine := -1
for _, entry := range tokens {
if entry.kind == token.COMMENT || (entry.kind == token.SEMICOLON && entry.literal == "\n") {
continue
}
switch entry.kind {
case token.RBRACE, token.RBRACK, token.RPAREN:
depth--
}
line := file.PositionFor(file.Pos(entry.offset), false).Line
lineStart := max(bom, file.Offset(file.LineStart(line)))
if lineStart != previousLine {
prefix := source[lineStart:entry.offset]
wanted := depth * width
if strings.Trim(prefix, " \t") == "" && (len(prefix) != wanted || strings.ContainsRune(prefix, '\t')) {
*edits = append(*edits, edit{
lineStart, entry.offset, strings.Repeat(" ", wanted), "formatting.indentSize",
fmt.Sprintf("Expected %d space(s) of indentation", wanted),
})
}
}
previousLine = lineStart
switch entry.kind {
case token.LBRACE, token.LBRACK, token.LPAREN:
depth++
}
}
}
func header(source, path string, bom int, edits *[]edit) {
if strings.HasPrefix(path, "+build ") || strings.HasPrefix(path, "+build\t") {
path = "./" + path
}
comment := "// " + path
for _, line := range strings.Split(source[bom:], "\n") {
text := strings.TrimSpace(line)
if text == comment {
return
}
if text != "" && !strings.HasPrefix(text, "//") {
break
}
}
ending := "\n"
if first, _, _ := strings.Cut(source, "\n"); strings.HasSuffix(first, "\r") {
ending = "\r\n"
}
*edits = append(*edits, edit{
bom, bom, comment + ending + ending, "formatting.filePathHeader",
"Expected file path header " + comment,
})
}
func names(node ast.Node, add func(*ast.Ident, string)) {
switch node := node.(type) {
case *ast.FuncDecl:
add(node.Name, "functions")
case *ast.TypeSpec:
add(node.Name, "classes")
case *ast.ValueSpec:
for _, name := range node.Names {
add(name, "variables")
}
case *ast.FuncType:
for _, fields := range []*ast.FieldList{node.Params, node.Results} {
if fields == nil {
continue
}
for _, field := range fields.List {
for _, name := range field.Names {
add(name, "variables")
}
}
}
case *ast.AssignStmt:
if node.Tok == token.DEFINE {
for _, expr := range node.Lhs {
if ident, ok := expr.(*ast.Ident); ok {
add(ident, "variables")
}
}
}
case *ast.RangeStmt:
if node.Tok == token.DEFINE {
for _, expr := range []ast.Expr{node.Key, node.Value} {
if ident, ok := expr.(*ast.Ident); ok {
add(ident, "variables")
}
}
}
}
}
func analyze(input request) result {
output := result{
Formatted: input.Source,
Issues: []issue{},
Names: [][3]any{},
}
files := token.NewFileSet()
mode := parser.ParseComments | parser.AllErrors | parser.SkipObjectResolution
tree, err := parser.ParseFile(files, "", input.Source, mode)
if err != nil {
var list scanner.ErrorList
if errors.As(err, &list) && len(list) != 0 {
output.Error, output.Offset = list[0].Msg, list[0].Pos.Offset
} else {
output.Error = err.Error()
}
return output
}
file := files.File(tree.Pos())
var edits []edit
tokens := scan(input.Source)
preserve := false
for _, entry := range tokens {
if entry.kind == token.COMMENT && (strings.HasPrefix(entry.literal, "//line ") || strings.HasPrefix(entry.literal, "/*line ")) {
preserve = true
break
}
}
newlines := input.Newlines
if preserve {
newlines = 0
}
if newlines != 0 {
spacing(input.Source, file, tree.Decls, newlines, &edits)
}
ast.Inspect(tree, func(node ast.Node) bool {
if input.Names {
names(node, func(name *ast.Ident, category string) {
if name.Name != "_" {
output.Names = append(output.Names, [3]any{file.Offset(name.Pos()), category, name.Name})
}
})
}
if newlines != 0 {
switch section := node.(type) {
case *ast.BlockStmt:
spacing(input.Source, file, section.List, newlines, &edits)
case *ast.CaseClause:
spacing(input.Source, file, section.Body, newlines, &edits)
case *ast.CommClause:
spacing(input.Source, file, section.Body, newlines, &edits)
}
}
return true
})
bom := 0
if strings.HasPrefix(input.Source, "\ufeff") {
bom = len("\ufeff")
}
if !preserve && input.Indent != 0 {
indentation(input.Source, file, tokens, input.Indent, bom, &edits)
}
if !preserve && input.Header {
header(input.Source, input.Path, bom, &edits)
}
// Keep zero-length header insertions before any indentation replacement at the same offset.
sort.SliceStable(edits, func(left, right int) bool {
first, second := edits[left], edits[right]
return first.start < second.start || (first.start == second.start && first.end < second.end)
})
var candidate strings.Builder
cursor := 0
for _, change := range edits {
if change.start < cursor {
return result{Error: "Go formatting produced overlapping edits"}
}
candidate.WriteString(input.Source[cursor:change.start])
candidate.WriteString(change.replacement)
cursor = change.end
output.Issues = append(output.Issues, issue{change.start, change.rule, change.message})
}
if len(edits) != 0 {
candidate.WriteString(input.Source[cursor:])
proposal := candidate.String()
if _, err := parser.ParseFile(token.NewFileSet(), "", proposal, mode); err != nil {
return result{Error: "Formatting would make the Go source invalid"}
}
verified := scan(proposal)
if input.Header && len(verified) == len(tokens)+1 && verified[0].kind == token.COMMENT {
verified = verified[1:]
}
if !sameTokens(tokens, verified) {
return result{Error: "Formatting would change the Go token stream"}
}
output.Formatted = proposal
}
return output
}
func main() {
input := json.NewDecoder(os.Stdin)
output := json.NewEncoder(os.Stdout)
for {
var request request
if err := input.Decode(&request); err != nil {
if err == io.EOF {
return
}
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if err := output.Encode(analyze(request)); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
}