Skip to content

Commit

Permalink
fix: comments and strings inside of expression attributes (#149)
Browse files Browse the repository at this point in the history
* fix: comments and strings inside of expression attributes

* refactor: remove dead code
  • Loading branch information
natemoo-re authored Nov 16, 2021
1 parent 2d31b6f commit 8800f80
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/new-socks-punch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/compiler': patch
---

Fix comments and strings inside of attribute expressions
14 changes: 14 additions & 0 deletions internal/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -1231,6 +1231,20 @@ func (z *Tokenizer) readTagAttrExpression() {
return
}
switch c {
// Handle comments, strings within attrs
case '/', '"', '\'', '`':
end := z.data.End
if c == '/' {
next := z.readByte()
if next == '/' {
panic("Block comments (//) are not allowed inside of expressions")
}
z.readCommentOrRegExp()
} else {
z.readString(c)
}
z.raw.End = z.data.End
z.data.End = end
case '{':
z.attrExpressionStack++
case '}':
Expand Down
27 changes: 25 additions & 2 deletions internal/token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,21 @@ func TestBasic(t *testing.T) {
`<div>{ value }</div>`,
[]TokenType{StartTagToken, StartExpressionToken, TextToken, EndExpressionToken, EndTagToken},
},
{
"attribute expression with quoted braces",
`<div value={"{"} />`,
[]TokenType{SelfClosingTagToken},
},
{
"attribute expression with quote",
`<div value={/* hello */} />`,
[]TokenType{SelfClosingTagToken},
},
{
"JSX-style comment inside element",
`<div {/* hello */} a=b />`,
[]TokenType{SelfClosingTagToken},
},
{
"quotes within textContent",
`<p>can't</p>`,
Expand Down Expand Up @@ -182,8 +197,6 @@ func TestBasic(t *testing.T) {
`<Fragment>foo</Fragment>`,
[]TokenType{StartTagToken, TextToken, EndTagToken},
},
// Special Case: this should PANIC! Not sure how to test for a panic

}

runTokenTypeTest(t, Basic)
Expand All @@ -201,6 +214,11 @@ To fix this, please change
to use the longhand Fragment syntax:
<Fragment slot="named">`,
},
{
"block comment in attribute",
`<div {// uhh} />`,
`Block comments (//) are not allowed inside of expressions`,
},
}
runPanicTest(t, Panics)
}
Expand Down Expand Up @@ -573,6 +591,11 @@ func TestAttributes(t *testing.T) {
`<div a="value" b='value' c=value/>`,
[]AttributeType{QuotedAttribute, QuotedAttribute, QuotedAttribute},
},
{
"expression with quoted braces",
`<div value={ "{" } />`,
[]AttributeType{ExpressionAttribute},
},
}

runAttributeTypeTest(t, Attributes)
Expand Down

0 comments on commit 8800f80

Please sign in to comment.