Skip to content

Commit

Permalink
feat: parse multi-line comments
Browse files Browse the repository at this point in the history
  • Loading branch information
coderbyheart committed Sep 21, 2022
1 parent 17e5623 commit 7df18f1
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 10 deletions.
29 changes: 29 additions & 0 deletions parser/tokens/comment.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,33 @@ describe('comment()', () => {
},
},
))

it('should parse multi-line comments', () =>
assert.deepEqual(
comment(
tokenStream(
[
'<!--',
'Comment line 1. @tag1',
'Comment line 2. @tag2',
'Comment line 3. @tag3',
'-->',
'',
'Second line',
].join(os.EOL),
),
),
{
text: [
'Comment line 1. @tag1',
'Comment line 2. @tag2',
'Comment line 3. @tag3',
].join(os.EOL),
tags: {
tag1: true,
tag2: true,
tag3: true,
},
},
))
})
20 changes: 10 additions & 10 deletions parser/tokens/comment.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import os from 'node:os'
import { InvalidSyntaxError } from '../errors/InvalidSyntaxError.js'
import { Comment } from '../grammar.js'
import { TokenStream } from '../tokenStream.js'
import { parseTags } from './parseTags.js'

const commentStart = (s: TokenStream): boolean => {
if (s.char() !== '<') return false
if (s.next() !== '!') return false
if (s.next() !== '-') return false
if (s.next() !== '-') return false
if (s.peekNext() !== '!') return false
s.next()
if (s.peekNext() !== '-') return false
s.next()
if (s.peekNext() !== '-') return false
s.next()
s.next()
return true
}
Expand All @@ -17,19 +19,17 @@ const endComment = '-->'

export const comment = (s: TokenStream): Comment | null => {
if (!commentStart(s)) return null
const commentTokens = []
const commentTokens: string[] = []
const end = () => commentTokens.slice(-endComment.length).join('')
while (true) {
const char = s.char()
if (char === os.EOL) break
if (s.isEoF()) break
commentTokens.push(char)
s.next()
if (end() === endComment) break
}

if (
commentTokens.join('').slice(commentTokens.length - endComment.length) !==
endComment
)
if (end() !== endComment)
throw new InvalidSyntaxError(s, `Comment not closed with ${endComment}`)
const commentText = commentTokens
.join('')
Expand Down

0 comments on commit 7df18f1

Please sign in to comment.