1
0
mirror of https://github.com/go-task/task.git synced 2024-12-16 10:59:23 +02:00
task/vendor/github.com/mvdan/sh/syntax/printer.go

1006 lines
19 KiB
Go
Raw Normal View History

2017-04-24 14:47:10 +02:00
// Copyright (c) 2016, Daniel Martí <mvdan@mvdan.cc>
// See LICENSE for licensing information
package syntax
import (
"bufio"
"io"
2017-05-17 19:49:27 +02:00
"strings"
2017-04-24 14:47:10 +02:00
)
2017-05-17 19:49:27 +02:00
func Indent(spaces int) func(*Printer) {
return func(p *Printer) { p.indentSpaces = spaces }
2017-04-24 14:47:10 +02:00
}
2017-05-17 19:49:27 +02:00
func BinaryNextLine(p *Printer) { p.binNextLine = true }
func NewPrinter(options ...func(*Printer)) *Printer {
p := &Printer{
bufWriter: bufio.NewWriter(nil),
lenPrinter: new(Printer),
}
for _, opt := range options {
opt(p)
}
return p
2017-04-24 14:47:10 +02:00
}
2017-05-17 19:49:27 +02:00
// Print "pretty-prints" the given AST file to the given writer.
func (p *Printer) Print(w io.Writer, f *File) error {
2017-04-24 14:47:10 +02:00
p.reset()
p.lines, p.comments = f.lines, f.Comments
p.bufWriter.Reset(w)
p.stmts(f.Stmts)
p.commentsUpTo(0)
p.newline(0)
2017-05-27 16:17:49 +02:00
return p.bufWriter.Flush()
2017-04-24 14:47:10 +02:00
}
type bufWriter interface {
WriteByte(byte) error
WriteString(string) (int, error)
Reset(io.Writer)
2017-05-27 16:17:49 +02:00
Flush() error
2017-04-24 14:47:10 +02:00
}
2017-05-17 19:49:27 +02:00
type Printer struct {
2017-04-24 14:47:10 +02:00
bufWriter
2017-05-17 19:49:27 +02:00
indentSpaces int
binNextLine bool
2017-04-24 14:47:10 +02:00
lines []Pos
wantSpace bool
wantNewline bool
wroteSemi bool
commentPadding int
// nline is the position of the next newline
nline Pos
nlineIndex int
// lastLevel is the last level of indentation that was used.
lastLevel int
// level is the current level of indentation.
level int
// levelIncs records which indentation level increments actually
// took place, to revert them once their section ends.
levelIncs []bool
nestedBinary bool
// comments is the list of pending comments to write.
comments []*Comment
// pendingHdocs is the list of pending heredocs to write.
pendingHdocs []*Redirect
2017-05-17 19:49:27 +02:00
// used in stmtCols to align comments
lenPrinter *Printer
2017-04-24 14:47:10 +02:00
lenCounter byteCounter
}
2017-05-17 19:49:27 +02:00
func (p *Printer) reset() {
2017-04-24 14:47:10 +02:00
p.wantSpace, p.wantNewline = false, false
p.commentPadding = 0
p.nline, p.nlineIndex = 0, 0
p.lastLevel, p.level = 0, 0
p.levelIncs = p.levelIncs[:0]
p.nestedBinary = false
p.pendingHdocs = p.pendingHdocs[:0]
}
2017-05-17 19:49:27 +02:00
func (p *Printer) incLine() {
2017-04-24 14:47:10 +02:00
if p.nlineIndex++; p.nlineIndex >= len(p.lines) {
p.nline = maxPos
} else {
p.nline = p.lines[p.nlineIndex]
}
}
2017-05-17 19:49:27 +02:00
func (p *Printer) incLines(pos Pos) {
2017-04-24 14:47:10 +02:00
for p.nline < pos {
p.incLine()
}
}
2017-05-17 19:49:27 +02:00
func (p *Printer) spaces(n int) {
2017-04-24 14:47:10 +02:00
for i := 0; i < n; i++ {
p.WriteByte(' ')
}
}
2017-05-17 19:49:27 +02:00
func (p *Printer) bslashNewl() {
2017-04-24 14:47:10 +02:00
if p.wantSpace {
p.WriteByte(' ')
}
p.WriteString("\\\n")
p.wantSpace = false
p.incLine()
}
2017-05-17 19:49:27 +02:00
func (p *Printer) spacedString(s string) {
2017-04-24 14:47:10 +02:00
if p.wantSpace {
p.WriteByte(' ')
}
p.WriteString(s)
p.wantSpace = true
}
2017-05-17 19:49:27 +02:00
func (p *Printer) semiOrNewl(s string, pos Pos) {
2017-04-24 14:47:10 +02:00
if p.wantNewline {
p.newline(pos)
p.indent()
} else {
if !p.wroteSemi {
p.WriteByte(';')
}
p.WriteByte(' ')
p.incLines(pos)
}
p.WriteString(s)
p.wantSpace = true
}
2017-05-17 19:49:27 +02:00
func (p *Printer) incLevel() {
2017-04-24 14:47:10 +02:00
inc := false
if p.level <= p.lastLevel || len(p.levelIncs) == 0 {
p.level++
inc = true
} else if last := &p.levelIncs[len(p.levelIncs)-1]; *last {
*last = false
inc = true
}
p.levelIncs = append(p.levelIncs, inc)
}
2017-05-17 19:49:27 +02:00
func (p *Printer) decLevel() {
2017-04-24 14:47:10 +02:00
if p.levelIncs[len(p.levelIncs)-1] {
p.level--
}
p.levelIncs = p.levelIncs[:len(p.levelIncs)-1]
}
2017-05-17 19:49:27 +02:00
func (p *Printer) indent() {
2017-04-24 14:47:10 +02:00
p.lastLevel = p.level
switch {
case p.level == 0:
2017-05-17 19:49:27 +02:00
case p.indentSpaces == 0:
2017-04-24 14:47:10 +02:00
for i := 0; i < p.level; i++ {
p.WriteByte('\t')
}
2017-05-17 19:49:27 +02:00
case p.indentSpaces > 0:
p.spaces(p.indentSpaces * p.level)
2017-04-24 14:47:10 +02:00
}
}
2017-05-17 19:49:27 +02:00
func (p *Printer) newline(pos Pos) {
2017-04-24 14:47:10 +02:00
p.wantNewline, p.wantSpace = false, false
p.WriteByte('\n')
if pos > p.nline {
p.incLine()
}
hdocs := p.pendingHdocs
p.pendingHdocs = p.pendingHdocs[:0]
for _, r := range hdocs {
2017-05-27 16:17:49 +02:00
if r.Hdoc != nil {
p.word(r.Hdoc)
p.incLines(r.Hdoc.End())
}
2017-04-24 14:47:10 +02:00
p.unquotedWord(r.Word)
p.WriteByte('\n')
p.incLine()
p.wantSpace = false
}
}
2017-05-17 19:49:27 +02:00
func (p *Printer) newlines(pos Pos) {
2017-04-24 14:47:10 +02:00
p.newline(pos)
if pos > p.nline {
// preserve single empty lines
p.WriteByte('\n')
p.incLine()
}
p.indent()
}
2017-05-17 19:49:27 +02:00
func (p *Printer) commentsAndSeparate(pos Pos) {
2017-04-24 14:47:10 +02:00
p.commentsUpTo(pos)
if p.wantNewline || pos > p.nline {
p.newlines(pos)
}
}
2017-05-17 19:49:27 +02:00
func (p *Printer) sepTok(s string, pos Pos) {
2017-04-24 14:47:10 +02:00
p.level++
p.commentsUpTo(pos)
p.level--
if p.wantNewline || pos > p.nline {
p.newlines(pos)
}
p.WriteString(s)
p.wantSpace = true
}
2017-05-17 19:49:27 +02:00
func (p *Printer) semiRsrv(s string, pos Pos, fallback bool) {
2017-04-24 14:47:10 +02:00
p.level++
p.commentsUpTo(pos)
p.level--
if p.wantNewline || pos > p.nline {
p.newlines(pos)
2017-05-27 16:17:49 +02:00
} else {
if fallback && !p.wroteSemi {
2017-04-24 14:47:10 +02:00
p.WriteByte(';')
}
2017-05-27 16:17:49 +02:00
if p.wantSpace {
p.WriteByte(' ')
}
2017-04-24 14:47:10 +02:00
}
p.WriteString(s)
p.wantSpace = true
}
2017-05-17 19:49:27 +02:00
func (p *Printer) anyCommentsBefore(pos Pos) bool {
2017-04-24 14:47:10 +02:00
if !pos.IsValid() || len(p.comments) < 1 {
return false
}
return p.comments[0].Hash < pos
}
2017-05-17 19:49:27 +02:00
func (p *Printer) commentsUpTo(pos Pos) {
2017-04-24 14:47:10 +02:00
if len(p.comments) < 1 {
return
}
c := p.comments[0]
if pos.IsValid() && c.Hash >= pos {
return
}
p.comments = p.comments[1:]
switch {
case p.nlineIndex == 0:
case c.Hash > p.nline:
p.newlines(c.Hash)
case p.wantSpace:
p.spaces(p.commentPadding + 1)
}
p.incLines(c.Hash)
p.WriteByte('#')
p.WriteString(c.Text)
p.commentsUpTo(pos)
}
2017-05-17 19:49:27 +02:00
func (p *Printer) wordPart(wp WordPart) {
2017-04-24 14:47:10 +02:00
switch x := wp.(type) {
case *Lit:
p.WriteString(x.Value)
case *SglQuoted:
if x.Dollar {
p.WriteByte('$')
}
p.WriteByte('\'')
p.WriteString(x.Value)
p.WriteByte('\'')
p.incLines(x.End())
case *DblQuoted:
2017-05-27 16:17:49 +02:00
p.dblQuoted(x)
2017-04-24 14:47:10 +02:00
case *CmdSubst:
p.incLines(x.Pos())
2017-05-27 16:17:49 +02:00
switch {
2017-06-04 21:06:04 +02:00
case x.TempFile:
2017-05-27 16:17:49 +02:00
p.WriteString("${")
p.wantSpace = true
p.nestedStmts(x.Stmts, x.Right)
p.wantSpace = false
p.semiRsrv("}", x.Right, true)
2017-06-04 21:06:04 +02:00
case x.ReplyVar:
2017-05-27 16:17:49 +02:00
p.WriteString("${|")
p.nestedStmts(x.Stmts, x.Right)
p.wantSpace = false
p.semiRsrv("}", x.Right, true)
default:
p.WriteString("$(")
p.wantSpace = len(x.Stmts) > 0 && startsWithLparen(x.Stmts[0])
p.nestedStmts(x.Stmts, x.Right)
p.sepTok(")", x.Right)
}
2017-04-24 14:47:10 +02:00
case *ParamExp:
2017-05-01 00:50:22 +02:00
p.paramExp(x)
2017-04-24 14:47:10 +02:00
case *ArithmExp:
p.WriteString("$((")
2017-05-27 16:17:49 +02:00
if x.Unsigned {
p.WriteString("# ")
}
2017-05-17 19:49:27 +02:00
p.arithmExpr(x.X, false, false)
2017-04-24 14:47:10 +02:00
p.WriteString("))")
case *ExtGlob:
p.WriteString(x.Op.String())
p.WriteString(x.Pattern.Value)
p.WriteByte(')')
case *ProcSubst:
// avoid conflict with << and others
if p.wantSpace {
p.WriteByte(' ')
p.wantSpace = false
}
p.WriteString(x.Op.String())
p.nestedStmts(x.Stmts, 0)
p.WriteByte(')')
}
}
2017-05-27 16:17:49 +02:00
func (p *Printer) dblQuoted(dq *DblQuoted) {
if dq.Dollar {
p.WriteByte('$')
}
p.WriteByte('"')
for i, n := range dq.Parts {
p.wordPart(n)
if i == len(dq.Parts)-1 {
p.incLines(n.End())
}
}
p.WriteByte('"')
}
func (p *Printer) wroteIndex(index ArithmExpr, key *DblQuoted) bool {
if index == nil && key == nil {
return false
}
p.WriteByte('[')
if index != nil {
p.arithmExpr(index, false, false)
} else {
p.dblQuoted(key)
}
p.WriteByte(']')
return true
}
2017-05-17 19:49:27 +02:00
func (p *Printer) paramExp(pe *ParamExp) {
2017-05-27 16:17:49 +02:00
if pe.nakedIndex() { // arr[x]
2017-05-17 19:49:27 +02:00
p.WriteString(pe.Param.Value)
2017-05-27 16:17:49 +02:00
p.wroteIndex(pe.Index, pe.Key)
2017-05-17 19:49:27 +02:00
return
}
if pe.Short { // $var
2017-05-01 00:50:22 +02:00
p.WriteByte('$')
p.WriteString(pe.Param.Value)
return
}
2017-05-17 19:49:27 +02:00
// ${var...}
2017-05-01 00:50:22 +02:00
p.WriteString("${")
switch {
case pe.Length:
p.WriteByte('#')
2017-05-27 16:17:49 +02:00
case pe.Width:
p.WriteByte('%')
2017-05-01 00:50:22 +02:00
case pe.Indirect:
p.WriteByte('!')
}
2017-06-04 21:06:04 +02:00
p.WriteString(pe.Param.Value)
2017-05-27 16:17:49 +02:00
p.wroteIndex(pe.Index, pe.Key)
2017-05-01 00:50:22 +02:00
if pe.Slice != nil {
p.WriteByte(':')
2017-05-17 19:49:27 +02:00
p.arithmExpr(pe.Slice.Offset, true, true)
2017-05-01 00:50:22 +02:00
if pe.Slice.Length != nil {
p.WriteByte(':')
2017-05-17 19:49:27 +02:00
p.arithmExpr(pe.Slice.Length, true, false)
2017-05-01 00:50:22 +02:00
}
} else if pe.Repl != nil {
if pe.Repl.All {
p.WriteByte('/')
}
p.WriteByte('/')
2017-05-27 16:17:49 +02:00
if pe.Repl.Orig != nil {
p.word(pe.Repl.Orig)
}
2017-05-01 00:50:22 +02:00
p.WriteByte('/')
2017-05-27 16:17:49 +02:00
if pe.Repl.With != nil {
p.word(pe.Repl.With)
}
2017-05-01 00:50:22 +02:00
} else if pe.Exp != nil {
p.WriteString(pe.Exp.Op.String())
2017-05-27 16:17:49 +02:00
if pe.Exp.Word != nil {
p.word(pe.Exp.Word)
}
2017-05-01 00:50:22 +02:00
}
p.WriteByte('}')
}
2017-05-17 19:49:27 +02:00
func (p *Printer) loop(loop Loop) {
2017-04-24 14:47:10 +02:00
switch x := loop.(type) {
case *WordIter:
p.WriteString(x.Name.Value)
2017-05-27 16:17:49 +02:00
if len(x.Items) > 0 {
2017-04-24 14:47:10 +02:00
p.spacedString(" in")
2017-05-27 16:17:49 +02:00
p.wordJoin(x.Items)
2017-04-24 14:47:10 +02:00
}
case *CStyleLoop:
p.WriteString("((")
if x.Init == nil {
p.WriteByte(' ')
}
2017-05-17 19:49:27 +02:00
p.arithmExpr(x.Init, false, false)
2017-04-24 14:47:10 +02:00
p.WriteString("; ")
2017-05-17 19:49:27 +02:00
p.arithmExpr(x.Cond, false, false)
2017-04-24 14:47:10 +02:00
p.WriteString("; ")
2017-05-17 19:49:27 +02:00
p.arithmExpr(x.Post, false, false)
2017-04-24 14:47:10 +02:00
p.WriteString("))")
}
}
2017-05-17 19:49:27 +02:00
func (p *Printer) arithmExpr(expr ArithmExpr, compact, spacePlusMinus bool) {
2017-04-24 14:47:10 +02:00
switch x := expr.(type) {
2017-05-27 16:17:49 +02:00
case *Word:
p.word(x)
2017-04-24 14:47:10 +02:00
case *BinaryArithm:
if compact {
2017-05-17 19:49:27 +02:00
p.arithmExpr(x.X, compact, spacePlusMinus)
2017-04-24 14:47:10 +02:00
p.WriteString(x.Op.String())
2017-05-17 19:49:27 +02:00
p.arithmExpr(x.Y, compact, false)
2017-04-24 14:47:10 +02:00
} else {
2017-05-17 19:49:27 +02:00
p.arithmExpr(x.X, compact, spacePlusMinus)
2017-04-24 14:47:10 +02:00
if x.Op != Comma {
p.WriteByte(' ')
}
p.WriteString(x.Op.String())
p.WriteByte(' ')
2017-05-17 19:49:27 +02:00
p.arithmExpr(x.Y, compact, false)
2017-04-24 14:47:10 +02:00
}
case *UnaryArithm:
if x.Post {
2017-05-17 19:49:27 +02:00
p.arithmExpr(x.X, compact, spacePlusMinus)
2017-04-24 14:47:10 +02:00
p.WriteString(x.Op.String())
} else {
2017-05-17 19:49:27 +02:00
if spacePlusMinus {
switch x.Op {
case Plus, Minus:
p.WriteByte(' ')
}
}
2017-04-24 14:47:10 +02:00
p.WriteString(x.Op.String())
2017-05-17 19:49:27 +02:00
p.arithmExpr(x.X, compact, false)
2017-04-24 14:47:10 +02:00
}
case *ParenArithm:
p.WriteByte('(')
2017-05-17 19:49:27 +02:00
p.arithmExpr(x.X, false, false)
2017-04-24 14:47:10 +02:00
p.WriteByte(')')
}
}
2017-05-17 19:49:27 +02:00
func (p *Printer) testExpr(expr TestExpr) {
2017-04-24 14:47:10 +02:00
switch x := expr.(type) {
case *Word:
p.word(x)
case *BinaryTest:
p.testExpr(x.X)
p.WriteByte(' ')
p.WriteString(x.Op.String())
p.WriteByte(' ')
p.testExpr(x.Y)
case *UnaryTest:
p.WriteString(x.Op.String())
p.WriteByte(' ')
p.testExpr(x.X)
case *ParenTest:
p.WriteByte('(')
p.testExpr(x.X)
p.WriteByte(')')
}
}
2017-05-17 19:49:27 +02:00
func (p *Printer) word(w *Word) {
2017-04-24 14:47:10 +02:00
for _, n := range w.Parts {
p.wordPart(n)
}
p.wantSpace = true
}
2017-05-17 19:49:27 +02:00
func (p *Printer) unquotedWord(w *Word) {
2017-04-24 14:47:10 +02:00
for _, wp := range w.Parts {
switch x := wp.(type) {
case *SglQuoted:
p.WriteString(x.Value)
case *DblQuoted:
for _, qp := range x.Parts {
p.wordPart(qp)
}
case *Lit:
for i := 0; i < len(x.Value); i++ {
if b := x.Value[i]; b == '\\' {
if i++; i < len(x.Value) {
p.WriteByte(x.Value[i])
}
} else {
p.WriteByte(b)
}
}
}
}
}
2017-05-27 16:17:49 +02:00
func (p *Printer) wordJoin(ws []*Word) {
2017-04-24 14:47:10 +02:00
anyNewline := false
for _, w := range ws {
if pos := w.Pos(); pos > p.nline {
p.commentsUpTo(pos)
2017-05-27 16:17:49 +02:00
p.bslashNewl()
2017-04-24 14:47:10 +02:00
if !anyNewline {
p.incLevel()
anyNewline = true
}
p.indent()
} else if p.wantSpace {
p.WriteByte(' ')
p.wantSpace = false
}
p.word(w)
}
if anyNewline {
p.decLevel()
}
}
2017-05-27 16:17:49 +02:00
func (p *Printer) elemJoin(elems []*ArrayElem) {
anyNewline := false
for _, el := range elems {
if pos := el.Pos(); pos > p.nline {
p.commentsUpTo(pos)
p.WriteByte('\n')
p.incLine()
if !anyNewline {
p.incLevel()
anyNewline = true
}
p.indent()
} else if p.wantSpace {
p.WriteByte(' ')
p.wantSpace = false
}
if p.wroteIndex(el.Index, el.Key) {
p.WriteByte('=')
}
p.word(el.Value)
}
if anyNewline {
p.decLevel()
}
}
2017-05-17 19:49:27 +02:00
func (p *Printer) stmt(s *Stmt) {
2017-04-24 14:47:10 +02:00
if s.Negated {
p.spacedString("!")
}
2017-05-27 16:17:49 +02:00
p.assigns(s.Assigns, true)
2017-04-24 14:47:10 +02:00
var startRedirs int
if s.Cmd != nil {
startRedirs = p.command(s.Cmd, s.Redirs)
}
anyNewline := false
for _, r := range s.Redirs[startRedirs:] {
if r.OpPos > p.nline {
p.bslashNewl()
if !anyNewline {
p.incLevel()
anyNewline = true
}
p.indent()
}
p.commentsAndSeparate(r.OpPos)
if p.wantSpace {
p.WriteByte(' ')
}
if r.N != nil {
p.WriteString(r.N.Value)
}
p.WriteString(r.Op.String())
2017-05-27 16:17:49 +02:00
p.wantSpace = true
2017-04-24 14:47:10 +02:00
p.word(r.Word)
if r.Op == Hdoc || r.Op == DashHdoc {
p.pendingHdocs = append(p.pendingHdocs, r)
}
}
p.wroteSemi = false
2017-05-27 16:17:49 +02:00
switch {
case s.Semicolon.IsValid() && s.Semicolon > p.nline:
2017-04-24 14:47:10 +02:00
p.incLevel()
p.bslashNewl()
p.indent()
p.decLevel()
p.WriteByte(';')
p.wroteSemi = true
2017-05-27 16:17:49 +02:00
case s.Background:
2017-04-24 14:47:10 +02:00
p.WriteString(" &")
2017-05-27 16:17:49 +02:00
case s.Coprocess:
p.WriteString(" |&")
2017-04-24 14:47:10 +02:00
}
if anyNewline {
p.decLevel()
}
}
2017-05-17 19:49:27 +02:00
func (p *Printer) command(cmd Command, redirs []*Redirect) (startRedirs int) {
2017-04-24 14:47:10 +02:00
if p.wantSpace {
p.WriteByte(' ')
p.wantSpace = false
}
switch x := cmd.(type) {
case *CallExpr:
if len(x.Args) <= 1 {
2017-05-27 16:17:49 +02:00
p.wordJoin(x.Args)
2017-04-24 14:47:10 +02:00
return 0
}
2017-05-27 16:17:49 +02:00
p.wordJoin(x.Args[:1])
2017-04-24 14:47:10 +02:00
for _, r := range redirs {
if r.Pos() > x.Args[1].Pos() || r.Op == Hdoc || r.Op == DashHdoc {
break
}
if p.wantSpace {
p.WriteByte(' ')
}
if r.N != nil {
p.WriteString(r.N.Value)
}
p.WriteString(r.Op.String())
2017-05-27 16:17:49 +02:00
p.wantSpace = true
2017-04-24 14:47:10 +02:00
p.word(r.Word)
startRedirs++
}
2017-05-27 16:17:49 +02:00
p.wordJoin(x.Args[1:])
2017-04-24 14:47:10 +02:00
case *Block:
p.WriteByte('{')
p.wantSpace = true
p.nestedStmts(x.Stmts, x.Rbrace)
p.semiRsrv("}", x.Rbrace, true)
case *IfClause:
p.spacedString("if")
p.nestedStmts(x.CondStmts, 0)
p.semiOrNewl("then", x.Then)
p.nestedStmts(x.ThenStmts, 0)
for _, el := range x.Elifs {
p.semiRsrv("elif", el.Elif, true)
p.nestedStmts(el.CondStmts, 0)
p.semiOrNewl("then", el.Then)
p.nestedStmts(el.ThenStmts, 0)
}
if len(x.ElseStmts) > 0 {
p.semiRsrv("else", x.Else, true)
p.nestedStmts(x.ElseStmts, 0)
} else if x.Else.IsValid() {
p.incLines(x.Else)
}
p.semiRsrv("fi", x.Fi, true)
case *Subshell:
p.WriteByte('(')
p.wantSpace = len(x.Stmts) > 0 && startsWithLparen(x.Stmts[0])
p.nestedStmts(x.Stmts, x.Rparen)
p.sepTok(")", x.Rparen)
case *WhileClause:
2017-05-17 19:49:27 +02:00
if x.Until {
p.spacedString("until")
} else {
p.spacedString("while")
}
2017-04-24 14:47:10 +02:00
p.nestedStmts(x.CondStmts, 0)
p.semiOrNewl("do", x.Do)
p.nestedStmts(x.DoStmts, 0)
p.semiRsrv("done", x.Done, true)
case *ForClause:
p.WriteString("for ")
p.loop(x.Loop)
p.semiOrNewl("do", x.Do)
p.nestedStmts(x.DoStmts, 0)
p.semiRsrv("done", x.Done, true)
case *BinaryCmd:
p.stmt(x.X)
2017-05-27 16:17:49 +02:00
if x.Y.Pos() < p.nline {
// leave p.nestedBinary untouched
p.spacedString(x.Op.String())
p.stmt(x.Y)
break
}
2017-04-24 14:47:10 +02:00
indent := !p.nestedBinary
if indent {
p.incLevel()
}
2017-05-17 19:49:27 +02:00
if p.binNextLine {
2017-05-27 16:17:49 +02:00
if len(p.pendingHdocs) == 0 {
2017-05-01 00:50:22 +02:00
p.bslashNewl()
p.indent()
}
p.spacedString(x.Op.String())
if p.anyCommentsBefore(x.Y.Pos()) {
p.wantSpace = false
p.WriteByte('\n')
p.indent()
p.incLines(p.comments[0].Pos())
p.commentsUpTo(x.Y.Pos())
p.WriteByte('\n')
p.indent()
}
} else {
2017-05-17 19:49:27 +02:00
p.wantSpace = true
2017-05-01 00:50:22 +02:00
p.spacedString(x.Op.String())
2017-05-27 16:17:49 +02:00
if x.OpPos > p.nline {
p.incLines(x.OpPos)
2017-05-01 00:50:22 +02:00
}
2017-05-27 16:17:49 +02:00
p.commentsUpTo(x.Y.Pos())
p.newline(0)
p.indent()
2017-04-24 14:47:10 +02:00
}
p.incLines(x.Y.Pos())
2017-05-27 16:17:49 +02:00
_, p.nestedBinary = x.Y.Cmd.(*BinaryCmd)
2017-04-24 14:47:10 +02:00
p.stmt(x.Y)
if indent {
p.decLevel()
}
p.nestedBinary = false
case *FuncDecl:
2017-06-04 21:06:04 +02:00
if x.RsrvWord {
2017-04-24 14:47:10 +02:00
p.WriteString("function ")
}
p.WriteString(x.Name.Value)
p.WriteString("() ")
p.incLines(x.Body.Pos())
p.stmt(x.Body)
case *CaseClause:
p.WriteString("case ")
p.word(x.Word)
p.WriteString(" in")
2017-05-27 16:17:49 +02:00
for _, ci := range x.Items {
p.commentsAndSeparate(ci.Patterns[0].Pos())
for i, w := range ci.Patterns {
2017-04-24 14:47:10 +02:00
if i > 0 {
p.spacedString("|")
}
if p.wantSpace {
p.WriteByte(' ')
}
p.word(w)
}
p.WriteByte(')')
p.wantSpace = true
2017-05-27 16:17:49 +02:00
sep := len(ci.Stmts) > 1 || (len(ci.Stmts) > 0 && ci.Stmts[0].Pos() > p.nline)
p.nestedStmts(ci.Stmts, 0)
2017-04-24 14:47:10 +02:00
p.level++
if sep {
2017-05-27 16:17:49 +02:00
p.commentsUpTo(ci.OpPos)
p.newlines(ci.OpPos)
2017-04-24 14:47:10 +02:00
}
2017-05-27 16:17:49 +02:00
p.spacedString(ci.Op.String())
p.incLines(ci.OpPos)
2017-04-24 14:47:10 +02:00
p.level--
2017-05-27 16:17:49 +02:00
if sep || ci.OpPos == x.Esac {
2017-04-24 14:47:10 +02:00
p.wantNewline = true
}
}
2017-05-27 16:17:49 +02:00
p.semiRsrv("esac", x.Esac, len(x.Items) == 0)
2017-04-24 14:47:10 +02:00
case *ArithmCmd:
p.WriteString("((")
2017-05-27 16:17:49 +02:00
if x.Unsigned {
p.WriteString("# ")
}
2017-05-17 19:49:27 +02:00
p.arithmExpr(x.X, false, false)
2017-04-24 14:47:10 +02:00
p.WriteString("))")
case *TestClause:
p.WriteString("[[ ")
p.testExpr(x.X)
p.spacedString("]]")
case *DeclClause:
2017-05-27 16:17:49 +02:00
p.spacedString(x.Variant)
2017-04-24 14:47:10 +02:00
for _, w := range x.Opts {
p.WriteByte(' ')
p.word(w)
}
2017-05-27 16:17:49 +02:00
p.assigns(x.Assigns, false)
case *TimeClause:
p.spacedString("time")
if x.Stmt != nil {
p.stmt(x.Stmt)
}
2017-04-24 14:47:10 +02:00
case *CoprocClause:
p.spacedString("coproc")
if x.Name != nil {
p.WriteByte(' ')
p.WriteString(x.Name.Value)
}
p.stmt(x.Stmt)
case *LetClause:
p.spacedString("let")
for _, n := range x.Exprs {
p.WriteByte(' ')
2017-05-17 19:49:27 +02:00
p.arithmExpr(n, true, false)
2017-04-24 14:47:10 +02:00
}
}
return startRedirs
}
func startsWithLparen(s *Stmt) bool {
switch x := s.Cmd.(type) {
case *Subshell:
return true
case *BinaryCmd:
return startsWithLparen(x.X)
}
return false
}
2017-05-17 19:49:27 +02:00
func (p *Printer) hasInline(pos, npos, nline Pos) bool {
2017-04-24 14:47:10 +02:00
for _, c := range p.comments {
if c.Hash > nline {
return false
}
if c.Hash > pos && (npos == 0 || c.Hash < npos) {
return true
}
}
return false
}
2017-05-17 19:49:27 +02:00
func (p *Printer) stmts(stmts []*Stmt) {
2017-04-24 14:47:10 +02:00
switch len(stmts) {
case 0:
return
case 1:
s := stmts[0]
pos := s.Pos()
p.commentsUpTo(pos)
if pos <= p.nline {
p.stmt(s)
} else {
if p.nlineIndex > 0 {
p.newlines(pos)
}
p.incLines(pos)
p.stmt(s)
p.wantNewline = true
}
return
}
inlineIndent := 0
for i, s := range stmts {
pos := s.Pos()
ind := p.nlineIndex
p.commentsUpTo(pos)
if p.nlineIndex > 0 {
p.newlines(pos)
}
p.incLines(pos)
p.stmt(s)
var npos Pos
if i+1 < len(stmts) {
npos = stmts[i+1].Pos()
}
if !p.hasInline(pos, npos, p.nline) {
inlineIndent = 0
p.commentPadding = 0
continue
}
if ind < len(p.lines)-1 && s.End() > p.lines[ind+1] {
inlineIndent = 0
}
if inlineIndent == 0 {
ind2 := p.nlineIndex
nline2 := p.nline
follow := stmts[i:]
for j, s2 := range follow {
pos2 := s2.Pos()
var npos2 Pos
if j+1 < len(follow) {
npos2 = follow[j+1].Pos()
}
2017-05-17 19:49:27 +02:00
if !p.hasInline(pos2, npos2, nline2) {
2017-04-24 14:47:10 +02:00
break
}
2017-05-17 19:49:27 +02:00
if l := p.stmtCols(s2); l > inlineIndent {
2017-04-24 14:47:10 +02:00
inlineIndent = l
}
if ind2++; ind2 >= len(p.lines) {
nline2 = maxPos
} else {
nline2 = p.lines[ind2]
}
}
if ind2 == p.nlineIndex+1 {
// no inline comments directly after this one
continue
}
}
if inlineIndent > 0 {
2017-05-17 19:49:27 +02:00
if l := p.stmtCols(s); l > 0 {
p.commentPadding = inlineIndent - l
}
2017-04-24 14:47:10 +02:00
}
}
p.wantNewline = true
}
type byteCounter int
func (c *byteCounter) WriteByte(b byte) error {
2017-05-17 19:49:27 +02:00
switch {
case *c < 0:
case b == '\n':
*c = -1
default:
*c++
}
2017-04-24 14:47:10 +02:00
return nil
}
func (c *byteCounter) WriteString(s string) (int, error) {
2017-05-17 19:49:27 +02:00
switch {
case *c < 0:
case strings.Contains(s, "\n"):
*c = -1
default:
*c += byteCounter(len(s))
}
2017-04-24 14:47:10 +02:00
return 0, nil
}
func (c *byteCounter) Reset(io.Writer) { *c = 0 }
2017-05-27 16:17:49 +02:00
func (c *byteCounter) Flush() error { return nil }
2017-04-24 14:47:10 +02:00
2017-05-17 19:49:27 +02:00
// stmtCols reports the length that s will take when formatted in a
// single line. If it will span multiple lines, stmtCols will return -1.
func (p *Printer) stmtCols(s *Stmt) int {
*p.lenPrinter = Printer{
bufWriter: &p.lenCounter,
lines: p.lines,
}
2017-04-24 14:47:10 +02:00
p.lenPrinter.bufWriter.Reset(nil)
p.lenPrinter.incLines(s.Pos())
p.lenPrinter.stmt(s)
return int(p.lenCounter)
}
2017-05-17 19:49:27 +02:00
func (p *Printer) nestedStmts(stmts []*Stmt, closing Pos) {
2017-04-24 14:47:10 +02:00
p.incLevel()
if len(stmts) == 1 && closing > p.nline && stmts[0].End() <= p.nline {
p.newline(0)
p.indent()
}
p.stmts(stmts)
p.decLevel()
}
2017-05-27 16:17:49 +02:00
func (p *Printer) assigns(assigns []*Assign, alwaysEqual bool) {
2017-04-24 14:47:10 +02:00
anyNewline := false
for _, a := range assigns {
if a.Pos() > p.nline {
p.bslashNewl()
if !anyNewline {
p.incLevel()
anyNewline = true
}
p.indent()
} else if p.wantSpace {
p.WriteByte(' ')
}
if a.Name != nil {
p.WriteString(a.Name.Value)
2017-05-27 16:17:49 +02:00
p.wroteIndex(a.Index, a.Key)
2017-04-24 14:47:10 +02:00
if a.Append {
p.WriteByte('+')
}
2017-05-27 16:17:49 +02:00
if alwaysEqual || a.Value != nil || a.Array != nil {
p.WriteByte('=')
}
2017-04-24 14:47:10 +02:00
}
if a.Value != nil {
p.word(a.Value)
2017-05-17 19:49:27 +02:00
} else if a.Array != nil {
p.wantSpace = false
p.WriteByte('(')
2017-05-27 16:17:49 +02:00
p.elemJoin(a.Array.Elems)
2017-05-17 19:49:27 +02:00
p.sepTok(")", a.Array.Rparen)
2017-04-24 14:47:10 +02:00
}
p.wantSpace = true
}
if anyNewline {
p.decLevel()
}
}