Skip to content

Commit

Permalink
Detect when in a string literal (#47)
Browse files Browse the repository at this point in the history
* [tests] Add failing test case for quoting issue #46
* [asmfmt.go] Detect when in a string literal

Fixes #46
  • Loading branch information
hughdavenport authored Mar 30, 2022
1 parent b745a68 commit ef134b9
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 5 deletions.
36 changes: 31 additions & 5 deletions asmfmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,18 @@ func newStatement(s string, defs map[string]struct{}) *statement {
st := statement{}

// Fix where a comment start if any
// We need to make sure that the comment isn't embedded in a string literal
startcom := strings.Index(s, "//")
startstr := strings.Index(s, "\"")
for endstr := 0; startcom > startstr && startstr > endstr; {
// This does not check for any escaping (i.e. "\"")
endstr = startstr + 1 + strings.Index(s[startstr+1:], "\"")
startcom = endstr + strings.Index(s[endstr:], "//")
if startcom < endstr {
startcom = 0
}
startstr = endstr + 1 + strings.Index(s[endstr+1:], "\"")
}
if startcom > 0 {
st.comment = strings.TrimSpace(s[startcom+2:])
s = strings.TrimSpace(s[:startcom])
Expand Down Expand Up @@ -417,11 +428,25 @@ func (st *statement) setParams(s string) {
runes := []rune(s)
last := '\n'
inComment := false
inStringLiteral := false
inCharLiteral := false
out := make([]rune, 0, len(runes))
for _, r := range runes {
switch r {
case '"':
if last != '\\' && inStringLiteral {
inStringLiteral = false
} else if last != '\\' && !inStringLiteral {
inStringLiteral = true
}
case '\'':
if last != '\\' && inCharLiteral {
inCharLiteral = false
} else if last != '\\' && !inCharLiteral {
inCharLiteral = true
}
case ',':
if inComment {
if inComment || inStringLiteral || inCharLiteral {
break
}
c := strings.TrimSpace(string(out))
Expand All @@ -443,11 +468,12 @@ func (st *statement) setParams(s string) {
r = ' '
}
case ';':
if !inComment {
out = []rune(strings.TrimSpace(string(out)) + "; ")
last = r
continue
if inComment || inStringLiteral || inCharLiteral {
break
}
out = []rune(strings.TrimSpace(string(out)) + "; ")
last = r
continue
}
if last == ';' && unicode.IsSpace(r) {
continue
Expand Down
7 changes: 7 additions & 0 deletions testdata/quoting.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
db ","
db ";"
db "http://example.com"
db "2 strings", "http://example.com"
db "3 strings", "2//slash groups", "http://example.com"
db ','
db ';'
7 changes: 7 additions & 0 deletions testdata/quoting.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
db ","
db ";"
db "http://example.com"
db "2 strings", "http://example.com"
db "3 strings", "2//slash groups", "http://example.com"
db ','
db ';'

0 comments on commit ef134b9

Please sign in to comment.