Skip to content

Commit

Permalink
Merge pull request #131 from goccy/feature/fix-printer
Browse files Browse the repository at this point in the history
Fix processing of PrintErrorToken ( clone token.Token )
  • Loading branch information
goccy authored Jun 12, 2020
2 parents ea7dd73 + 75a8a01 commit 862b061
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
20 changes: 12 additions & 8 deletions printer/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ func (p *Printer) printBeforeTokens(tk *token.Token, minLine, extLine int) token
}
tk = tk.Prev
}
minTk := tk
minTk := tk.Clone()
if minTk.Prev != nil {
// add white spaces to minTk by prev token
prev := minTk.Prev
Expand All @@ -266,20 +266,23 @@ func (p *Printer) printBeforeTokens(tk *token.Token, minLine, extLine int) token
tokens := token.Tokens{minTk}
tk = minTk.Next
for tk != nil && tk.Position.Line <= extLine {
tokens.Add(tk)
tk = tk.Next
clonedTk := tk.Clone()
tokens.Add(clonedTk)
tk = clonedTk.Next
}
lastTk := tokens[len(tokens)-1]
trimmedOrigin := p.removeRightSideWhiteSpaceChar(lastTk.Origin)
suffix := lastTk.Origin[len(trimmedOrigin):]
lastTk.Origin = trimmedOrigin

if lastTk.Next != nil && len(suffix) > 1 {
next := lastTk.Next.Clone()
// add suffix to header of next token
if suffix[0] == '\n' || suffix[0] == '\r' {
suffix = suffix[1:]
}
lastTk.Next.Origin = suffix + lastTk.Next.Origin
next.Origin = suffix + next.Origin
lastTk.Next = next
}
return tokens
}
Expand Down Expand Up @@ -307,14 +310,15 @@ func (p *Printer) printAfterTokens(tk *token.Token, maxLine int) token.Tokens {
if tk.Position.Line > maxLine {
return tokens
}
minTk := tk
minTk := tk.Clone()
minTk.Origin = p.removeLeftSideNewLineChar(minTk.Origin)
tokens.Add(minTk)
tk = minTk.Next
for tk != nil && tk.Position.Line <= maxLine {
p.addNewLineCharIfDocumentHeader(tk)
tokens.Add(tk)
tk = tk.Next
clonedTk := tk.Clone()
p.addNewLineCharIfDocumentHeader(clonedTk)
tokens.Add(clonedTk)
tk = clonedTk.Next
}
return tokens
}
Expand Down
13 changes: 13 additions & 0 deletions token/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -681,6 +681,19 @@ func (t *Token) AddColumn(col int) {
t.Position.Column += col
}

// Clone copy token ( preserve Prev/Next reference )
func (t *Token) Clone() *Token {
if t == nil {
return nil
}
copied := *t
if t.Position != nil {
pos := *(t.Position)
copied.Position = &pos
}
return &copied
}

// Tokens type of token collection
type Tokens []*Token

Expand Down

0 comments on commit 862b061

Please sign in to comment.