Skip to content

Commit

Permalink
fix: comment type matching (#117)
Browse files Browse the repository at this point in the history
  • Loading branch information
huozhi authored Jan 18, 2025
1 parent ced4a49 commit 19dded5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
18 changes: 13 additions & 5 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,18 @@ function isStringQuotation(chr) {
return isSingleQuotes(chr) || isStrTemplateChr(chr)
}

/** @returns {0|1|2} */
function isCommentStart_Js(curr, next) {
const str = curr + next
return str === '//' || str === '/*'
if (str === '/*') return 2
return str === '//' ? 1 : 0
}

/** @returns {0|1|2} */
function isCommentEnd_Js(prev, curr) {
return curr === '\n' || (prev + curr) === '*/'
return (prev + curr) === '*/'
? 2
: curr === '\n' ? 1 : 0
}

function isRegexStart(str) {
Expand Down Expand Up @@ -555,13 +560,16 @@ function tokenize(code, options) {
} else if (onCommentStart(curr, next)) {
append()
const start = i
const commentType = onCommentStart(curr, next)
const startCommentType = onCommentStart(curr, next)

// just match the comment, commentType === true
// inline comment, commentType === 1
// block comment, commentType === 2
if (commentType) {
for (; i < code.length && !onCommentEnd(code[i - 1], code[i]); i++);
if (startCommentType) {
for (; i < code.length; i++) {
const endCommentType = onCommentEnd(code[i - 1], code[i])
if (endCommentType == startCommentType) break
}
}
current = code.slice(start, i + 1)
append(T_COMMENT)
Expand Down
16 changes: 16 additions & 0 deletions test/ast.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,22 @@ describe('comments', () => {
]
`)
})

it('multi-line comments with annotations', () => {
const code = `/**
* @param {string} names
* @return {Promise<string[]>}
*/`
const tokens = tokenize(code)
expect(getTokensAsString(tokens)).toMatchInlineSnapshot(`
[
"/**
* @param {string} names
* @return {Promise<string[]>}
*/ => comment",
]
`)
})
})

describe('regex', () => {
Expand Down

0 comments on commit 19dded5

Please sign in to comment.