Skip to content

Commit

Permalink
Distinguish between /regexp/ and "regexp" in stringified output (#222)
Browse files Browse the repository at this point in the history
  • Loading branch information
ypdn authored Feb 28, 2024
1 parent 0fd695b commit 4ae6290
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
15 changes: 12 additions & 3 deletions internal/ast/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,12 +292,16 @@ func (e *NumExpr) String() string {
}
}

// StrExpr is a literal string like "foo".
// StrExpr is a literal string like "foo" or a regex constant like /foo/.
type StrExpr struct {
Value string
Regex bool
}

func (e *StrExpr) String() string {
if e.Regex {
return formatRegex(e.Value)
}
return strconv.Quote(e.Value)
}

Expand All @@ -308,8 +312,7 @@ type RegExpr struct {
}

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

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

// formatRegex formats the regex string r.
func formatRegex(r string) string {
escaped := strings.Replace(r, "/", `\/`, -1)
return "/" + escaped + "/"
}

// Stmt is the abstract syntax tree for any AWK statement.
type Stmt interface {
Node
Expand Down
4 changes: 2 additions & 2 deletions parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -726,7 +726,7 @@ func (p *parser) primary() ast.Expr {
case STRING:
s := p.val
p.next()
return &ast.StrExpr{s}
return &ast.StrExpr{Value: s}
case DIV, DIV_ASSIGN:
// If we get to DIV or DIV_ASSIGN as a primary expression,
// it's actually a regex.
Expand Down Expand Up @@ -967,7 +967,7 @@ func (p *parser) optionalLValue() ast.Expr {
func (p *parser) regexStr(parse func() ast.Expr) ast.Expr {
if p.matches(DIV, DIV_ASSIGN) {
regex := p.nextRegex()
return &ast.StrExpr{regex}
return &ast.StrExpr{Value: regex, Regex: true}
}
return parse()
}
Expand Down
2 changes: 2 additions & 0 deletions parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ $0 {
a[x, y, z]
f()
set(a, k, v)
sub(/regex/, repl, s)
sub("regex", repl, s)
sub(regex, repl)
sub(regex, repl, s)
gsub(regex, repl)
Expand Down

0 comments on commit 4ae6290

Please sign in to comment.