node: convert comments to /* */ format, to fix non-statement contexts
This commit is contained in:
parent
df0061041f
commit
3c76a68843
50
node.go
50
node.go
@ -53,6 +53,47 @@ type conversionState struct {
|
||||
|
||||
//
|
||||
|
||||
func normaliseCommentStrFragment(s string) string {
|
||||
if len(s) == 0 {
|
||||
return s
|
||||
}
|
||||
|
||||
lines := strings.Split(s, "\n")
|
||||
for i, _ := range lines {
|
||||
lines[i] = strings.TrimLeft(lines[i], "\t\r\n ")
|
||||
if strings.HasPrefix(lines[i], `//`) {
|
||||
lines[i] = lines[i][2:]
|
||||
}
|
||||
}
|
||||
return `/* ` + strings.TrimRight(strings.Join(lines, "\n"), "\n") + `*/`
|
||||
}
|
||||
|
||||
func normaliseCommentStr(s string) string {
|
||||
|
||||
// A comment may be injected at any point in the source tree
|
||||
// It's not necessarily valid to use line comments (`//`) mid-AST
|
||||
// Avoid the problem by unconditionally transforming to range comments (`/**/`)
|
||||
|
||||
extents := strings.Split(s, `/*`)
|
||||
ret := make([]string, 0, len(extents)*2)
|
||||
for _, extent := range extents {
|
||||
parts := strings.SplitN(extent, `*/`, 2) // any further */ after this has no effect
|
||||
if len(parts) == 1 {
|
||||
// No range comment, only line comment/whitespace
|
||||
// Transform single range only
|
||||
ret = append(ret, normaliseCommentStrFragment(parts[0]))
|
||||
|
||||
} else { // len(parts) == 2
|
||||
// Range comment part is OK
|
||||
// Only second middle part needs normalising
|
||||
ret = append(ret, parts[0], normaliseCommentStrFragment(parts[1]))
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return strings.Join(ret, "")
|
||||
}
|
||||
|
||||
func (this *conversionState) convert(n node.Node) (string, error) {
|
||||
|
||||
// Get any whitespace/comments attached to this node
|
||||
@ -93,9 +134,12 @@ func (this *conversionState) convert(n node.Node) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if len(freePrefix) > 0 && !(strings.HasSuffix(freePrefix, "\n") || strings.HasSuffix(freePrefix, `*/`)) {
|
||||
freePrefix += "\n"
|
||||
}
|
||||
//if len(freePrefix) > 0 && !(strings.HasSuffix(freePrefix, "\n") || strings.HasSuffix(freePrefix, `*/`)) {
|
||||
// freePrefix += "\n"
|
||||
//}
|
||||
|
||||
freePrefix = normaliseCommentStr(freePrefix)
|
||||
freeSuffix = normaliseCommentStr(freeSuffix)
|
||||
|
||||
return freePrefix + ret + freeSuffix, nil
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user