aboutsummaryrefslogtreecommitdiff
path: root/formatter.go
diff options
context:
space:
mode:
authorFuwn <[email protected]>2026-01-31 08:48:22 +0000
committerFuwn <[email protected]>2026-01-31 08:48:22 +0000
commitbe453569984b1b0fae60eeb352dd7561173b09e4 (patch)
treea86c734fc8d3618fb853146068d5cb86b9a2aaf4 /formatter.go
parentperf(formatter): Optimise regular expressions and string operations (diff)
downloadiku-be453569984b1b0fae60eeb352dd7561173b09e4.tar.xz
iku-be453569984b1b0fae60eeb352dd7561173b09e4.zip
fix(formatter): Handle backticks inside strings and character literals
Diffstat (limited to 'formatter.go')
-rw-r--r--formatter.go59
1 files changed, 58 insertions, 1 deletions
diff --git a/formatter.go b/formatter.go
index fce3af4..8231bb7 100644
--- a/formatter.go
+++ b/formatter.go
@@ -34,6 +34,62 @@ func isPackageLine(trimmed string) bool {
return len(trimmed) > 8 && trimmed[:8] == "package "
}
+func countRawStringDelimiters(line string) int {
+ count := 0
+ inString := false
+ inCharacter := false
+
+ for index := 0; index < len(line); index++ {
+ character := line[index]
+
+ if inCharacter {
+ if character == '\\' && index+1 < len(line) {
+ index++
+
+ continue
+ }
+
+ if character == '\'' {
+ inCharacter = false
+ }
+
+ continue
+ }
+
+ if inString {
+ if character == '\\' && index+1 < len(line) {
+ index++
+
+ continue
+ }
+
+ if character == '"' {
+ inString = false
+ }
+
+ continue
+ }
+
+ if character == '\'' {
+ inCharacter = true
+
+ continue
+ }
+
+ if character == '"' {
+ inString = true
+
+ continue
+ }
+
+ if character == '`' {
+ count++
+ }
+ }
+
+ return count
+}
+
type CommentMode int
const (
@@ -205,7 +261,7 @@ func (f *Formatter) rewrite(source []byte, lineInfoMap map[int]*lineInfo) []byte
insideRawString := false
for index, line := range lines {
- backtickCount := strings.Count(line, "`")
+ backtickCount := countRawStringDelimiters(line)
wasInsideRawString := insideRawString
if backtickCount%2 == 1 {
@@ -214,6 +270,7 @@ func (f *Formatter) rewrite(source []byte, lineInfoMap map[int]*lineInfo) []byte
if wasInsideRawString {
result = append(result, line)
+
continue
}