Skip to content

Commit 4ae6290

Browse files
authored
Distinguish between /regexp/ and "regexp" in stringified output (#222)
1 parent 0fd695b commit 4ae6290

3 files changed

Lines changed: 16 additions & 5 deletions

File tree

internal/ast/ast.go

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -292,12 +292,16 @@ func (e *NumExpr) String() string {
292292
}
293293
}
294294

295-
// StrExpr is a literal string like "foo".
295+
// StrExpr is a literal string like "foo" or a regex constant like /foo/.
296296
type StrExpr struct {
297297
Value string
298+
Regex bool
298299
}
299300

300301
func (e *StrExpr) String() string {
302+
if e.Regex {
303+
return formatRegex(e.Value)
304+
}
301305
return strconv.Quote(e.Value)
302306
}
303307

@@ -308,8 +312,7 @@ type RegExpr struct {
308312
}
309313

310314
func (e *RegExpr) String() string {
311-
escaped := strings.Replace(e.Regex, "/", `\/`, -1)
312-
return "/" + escaped + "/"
315+
return formatRegex(e.Regex)
313316
}
314317

315318
// VarExpr is a variable reference (special var, global, or local).
@@ -460,6 +463,12 @@ func IsLValue(expr Expr) bool {
460463
}
461464
}
462465

466+
// formatRegex formats the regex string r.
467+
func formatRegex(r string) string {
468+
escaped := strings.Replace(r, "/", `\/`, -1)
469+
return "/" + escaped + "/"
470+
}
471+
463472
// Stmt is the abstract syntax tree for any AWK statement.
464473
type Stmt interface {
465474
Node

parser/parser.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -726,7 +726,7 @@ func (p *parser) primary() ast.Expr {
726726
case STRING:
727727
s := p.val
728728
p.next()
729-
return &ast.StrExpr{s}
729+
return &ast.StrExpr{Value: s}
730730
case DIV, DIV_ASSIGN:
731731
// If we get to DIV or DIV_ASSIGN as a primary expression,
732732
// it's actually a regex.
@@ -967,7 +967,7 @@ func (p *parser) optionalLValue() ast.Expr {
967967
func (p *parser) regexStr(parse func() ast.Expr) ast.Expr {
968968
if p.matches(DIV, DIV_ASSIGN) {
969969
regex := p.nextRegex()
970-
return &ast.StrExpr{regex}
970+
return &ast.StrExpr{Value: regex, Regex: true}
971971
}
972972
return parse()
973973
}

parser/parser_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,8 @@ $0 {
124124
a[x, y, z]
125125
f()
126126
set(a, k, v)
127+
sub(/regex/, repl, s)
128+
sub("regex", repl, s)
127129
sub(regex, repl)
128130
sub(regex, repl, s)
129131
gsub(regex, repl)

0 commit comments

Comments
 (0)