Skip to content

Commit

Permalink
JS: fix newlines in literals in ExprStmt after last commit
Browse files Browse the repository at this point in the history
  • Loading branch information
tdewolff committed May 27, 2024
1 parent f7c565f commit 6c18dfd
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
15 changes: 14 additions & 1 deletion js/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,14 @@ func (n ExprStmt) String() string {
// JS writes JavaScript to writer.
func (n ExprStmt) JS(w io.Writer) {
buf := &bytes.Buffer{}
n.Value.JS(buf)
wb := io.Writer(buf)
if wi, ok := w.(parse.Indenter); ok {
// make sure that buf is indenter if w is so as well
// this is to prevent newlines in literals from indenting
wb = parse.NewIndenter(wb, wi.Indent())
w = wi.Writer
}
n.Value.JS(wb)
expr := buf.Bytes()

group := bytes.HasPrefix(expr, []byte("let "))
Expand Down Expand Up @@ -1686,6 +1693,9 @@ func (n LiteralExpr) JS(w io.Writer) {

// JSON writes JSON to writer.
func (n LiteralExpr) JSON(w io.Writer) error {
if wi, ok := w.(parse.Indenter); ok {
w = wi.Writer
}
if n.TokenType == TrueToken || n.TokenType == FalseToken || n.TokenType == NullToken || n.TokenType == DecimalToken || n.TokenType == IntegerToken {
w.Write(n.Data)
return nil
Expand Down Expand Up @@ -1974,6 +1984,9 @@ func (n TemplateExpr) JS(w io.Writer) {

// JSON writes JSON to writer.
func (n TemplateExpr) JSON(w io.Writer) error {
if wi, ok := w.(parse.Indenter); ok {
w = wi.Writer
}
if n.Tag != nil || len(n.List) != 0 {
js := &strings.Builder{}
n.JS(js)
Expand Down
1 change: 1 addition & 0 deletions js/ast_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ func TestJS(t *testing.T) {
{"//!\nn=>{ return n }", "//! (n) => { return n; };"}, // space after //! is newline
{"//!\n{//!\n}", "//! { //! }"}, // space after //! is newline
{`for(;;)let = 5`, `for ( ; ; ) { (let = 5); }`},
{"{`\n`}", "{ ` `; }"}, // space in template literal is newline
}

re := regexp.MustCompile("\n *")
Expand Down
4 changes: 4 additions & 0 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,10 @@ func NewIndenter(w io.Writer, n int) Indenter {
}
}

func (in Indenter) Indent() int {
return len(in.b)
}

func (in Indenter) Write(b []byte) (int, error) {
n, j := 0, 0
for i, c := range b {
Expand Down

0 comments on commit 6c18dfd

Please sign in to comment.