func IsSpace(b byte) bool {
	return b == ' ' || b == '\t' || b == '\n' || b == '\r'
}
IsSpace reports whether the byte is a space character.
IsSpace defines a space as being among the following bytes: ' ', '\t', '\n' and '\r'.
package format
import (
	"bytes"
	"github.com/tcard/sgo/sgo/ast"
	"github.com/tcard/sgo/sgo/parser"
	"github.com/tcard/sgo/sgo/printer"
	"github.com/tcard/sgo/sgo/token"
	"strings"
)
const parserMode = parser.ParseComments
func Parse(fset *token.FileSet, filename string, src []byte, fragmentOk bool) (
	file *ast.File,
	sourceAdj func(src []byte, indent int) []byte,
	indentAdj int,
	err error,
) {
	file, err = parser.ParseFile(fset, filename, src, parserMode)
	if err == nil || !fragmentOk || !strings.Contains(err.Error(), "expected 'package'") {
		return
	}
	psrc := append([]byte("package p;"), src...)
	file, err = parser.ParseFile(fset, filename, psrc, parserMode)
	if err == nil {
		sourceAdj = func(src []byte, indent int) []byte {
			src = src[indent+len("package p\n"):]
			return bytes.TrimSpace(src)
		}
		return
	}
	if !strings.Contains(err.Error(), "expected declaration") {
		return
	}
	fsrc := append(append([]byte("package p; func _() {"), src...), '\n', '\n', '}')
	file, err = parser.ParseFile(fset, filename, fsrc, parserMode)
	if err == nil {
		sourceAdj = func(src []byte, indent int) []byte {
			if indent < 0 {
				indent = 0
			}
			src = src[2*indent+len("package p\n\nfunc _() {"):]
			src = src[:len(src)-len("}\n")]
			return bytes.TrimSpace(src)
		}
		indentAdj = -1
	}
	return
}
func Format(
	fset *token.FileSet,
	file *ast.File,
	sourceAdj func(src []byte, indent int) []byte,
	indentAdj int,
	src []byte,
	cfg printer.Config,
) ([]byte, error) {
	if sourceAdj == nil {
		var buf bytes.Buffer
		err := cfg.Fprint(&buf, fset, file)
		if err != nil {
			return nil, err
		}
		return buf.Bytes(), nil
	}
	i, j := 0, 0
	for j < len(src) && IsSpace(src[j]) {
		if src[j] == '\n' {
			i = j + 1  
		}
		j++
	}
	var res []byte
	res = append(res, src[:i]...)
	indent := 0
	hasSpace := false
	for _, b := range src[i:j] {
		switch b {
		case ' ':
			hasSpace = true
		case '\t':
			indent++
		}
	}
	if indent == 0 && hasSpace {
		indent = 1
	}
	for i := 0; i < indent; i++ {
		res = append(res, '\t')
	}
	cfg.Indent = indent + indentAdj
	var buf bytes.Buffer
	err := cfg.Fprint(&buf, fset, file)
	if err != nil {
		return nil, err
	}
	res = append(res, sourceAdj(buf.Bytes(), cfg.Indent)...)
	i = len(src)
	for i > 0 && IsSpace(src[i-1]) {
		i--
	}
	return append(res, src[i:]...), nil
}