From 210897114524136d6a0f063ea022e55f1e779339 Mon Sep 17 00:00:00 2001 From: Colin Cross Date: Tue, 30 Jun 2015 14:33:38 -0700 Subject: [PATCH] Add convenience methods to Comment objects Add String() to print out the Comment, Text() to print out the Comment while stripping /*, //, and */, and EndLine() to return the line number of the last line of the comment. Change-Id: I076bc0990143acfc03c42a8cc569894fced8ee24 --- parser/parser.go | 50 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/parser/parser.go b/parser/parser.go index 498bdcb..a53be9e 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -700,3 +700,53 @@ type Comment struct { Comment []string Pos scanner.Position } + +func (c Comment) String() string { + l := 0 + for _, comment := range c.Comment { + l += len(comment) + 1 + } + buf := make([]byte, 0, l) + for _, comment := range c.Comment { + buf = append(buf, comment...) + buf = append(buf, '\n') + } + + return string(buf) +} + +// Return the text of the comment with // or /* and */ stripped +func (c Comment) Text() string { + l := 0 + for _, comment := range c.Comment { + l += len(comment) + 1 + } + buf := make([]byte, 0, l) + + blockComment := false + if strings.HasPrefix(c.Comment[0], "/*") { + blockComment = true + } + + for i, comment := range c.Comment { + if blockComment { + if i == 0 { + comment = strings.TrimPrefix(comment, "/*") + } + if i == len(c.Comment)-1 { + comment = strings.TrimSuffix(comment, "*/") + } + } else { + comment = strings.TrimPrefix(comment, "//") + } + buf = append(buf, comment...) + buf = append(buf, '\n') + } + + return string(buf) +} + +// Return the line number that the comment ends on +func (c Comment) EndLine() int { + return c.Pos.Line + len(c.Comment) - 1 +}