validateBalancedQuotes checks for balanced quotes in an expression
(expr string)
| 166 | |
| 167 | // validateBalancedQuotes checks for balanced quotes in an expression |
| 168 | func validateBalancedQuotes(expr string) error { |
| 169 | inSingleQuote := false |
| 170 | inDoubleQuote := false |
| 171 | inBacktick := false |
| 172 | escaped := false |
| 173 | |
| 174 | for i, ch := range expr { |
| 175 | if escaped { |
| 176 | escaped = false |
| 177 | continue |
| 178 | } |
| 179 | |
| 180 | if ch == '\\' { |
| 181 | escaped = true |
| 182 | continue |
| 183 | } |
| 184 | |
| 185 | switch ch { |
| 186 | case '\'': |
| 187 | if !inDoubleQuote && !inBacktick { |
| 188 | inSingleQuote = !inSingleQuote |
| 189 | } |
| 190 | case '"': |
| 191 | if !inSingleQuote && !inBacktick { |
| 192 | inDoubleQuote = !inDoubleQuote |
| 193 | } |
| 194 | case '`': |
| 195 | if !inSingleQuote && !inDoubleQuote { |
| 196 | inBacktick = !inBacktick |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | // Check if we reached end of string with unclosed quote |
| 201 | if i == len(expr)-1 { |
| 202 | if inSingleQuote { |
| 203 | return NewValidationError( |
| 204 | "expression", |
| 205 | "unclosed single quote", |
| 206 | "found unclosed single quote in expression: "+expr, |
| 207 | "Add the missing closing single quote (') to your expression.", |
| 208 | ) |
| 209 | } |
| 210 | if inDoubleQuote { |
| 211 | return NewValidationError( |
| 212 | "expression", |
| 213 | "unclosed double quote", |
| 214 | "found unclosed double quote in expression: "+expr, |
| 215 | "Add the missing closing double quote (\") to your expression.", |
| 216 | ) |
| 217 | } |
| 218 | if inBacktick { |
| 219 | return NewValidationError( |
| 220 | "expression", |
| 221 | "unclosed backtick", |
| 222 | "found unclosed backtick in expression: "+expr, |
| 223 | "Add the missing closing backtick (`) to your expression.", |
| 224 | ) |
| 225 | } |