From 75a8a011dbd889f7d0095484e8ea4b883d6e1f80 Mon Sep 17 00:00:00 2001 From: Masaaki Goshima Date: Fri, 12 Jun 2020 15:37:31 +0900 Subject: [PATCH] Fix processing of PrintErrorToken ( clone token.Token ) reason: Currently, PrintErrorToken make disruptive changes token.Token --- printer/printer.go | 20 ++++++++++++-------- token/token.go | 13 +++++++++++++ 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/printer/printer.go b/printer/printer.go index b540524e..bc3d7232 100644 --- a/printer/printer.go +++ b/printer/printer.go @@ -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 @@ -266,8 +266,9 @@ 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) @@ -275,11 +276,13 @@ func (p *Printer) printBeforeTokens(tk *token.Token, minLine, extLine int) token 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 } @@ -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 } diff --git a/token/token.go b/token/token.go index 1016d8f6..860db4a7 100644 --- a/token/token.go +++ b/token/token.go @@ -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