@@ -13,54 +13,48 @@ export class Lexer {
1313 scanner:
1414 while ( this . current < code . length ) {
1515 const startIndex = this . current
16- // 查找最近的换行符(\r\n, \n, \r)
17- const nextCR = code . indexOf ( '\r' , startIndex )
18- const nextLF = code . indexOf ( '\n' , startIndex )
16+
17+ // 使用正则表达式匹配换行符,更优雅地处理各种换行符类型
18+ const newlineMatch = code . slice ( startIndex ) . match ( / ( \r \n | \n | \r ) / )
19+
1920 let endIndex : number
21+ let nextIndex : number
22+ let newlineChar : string | undefined
2023
21- if ( nextCR === - 1 && nextLF === - 1 ) {
22- // 没有找到换行符,说明是最后一行
23- endIndex = code . length
24- }
25- else if ( nextCR === - 1 ) {
26- // 只有 \n
27- endIndex = nextLF
28- }
29- else if ( nextLF === - 1 ) {
30- // 只有 \r
31- endIndex = nextCR
32- }
33- else if ( nextCR < nextLF ) {
34- // 如果是 \r\n,跳过 \n
35- endIndex = nextCR
36- if ( nextLF === nextCR + 1 ) {
37- endIndex += 2
38- }
24+ if ( newlineMatch ) {
25+ newlineChar = newlineMatch [ 0 ]
26+ endIndex = startIndex + newlineMatch . index !
27+ nextIndex = endIndex + newlineChar . length
3928 }
4029 else {
41- // \n
42- endIndex = nextLF
30+ // 没有找到换行符,说明是最后一行
31+ endIndex = code . length
32+ nextIndex = code . length
4333 }
4434
45- const rawLine = code . slice ( startIndex , endIndex )
46- const line = rawLine . trim ( )
47- if ( isComment ( line ) ) {
35+ // 获取原始行内容,对于 code 类型,我们需要包含换行符
36+ const rawLine = code . slice ( startIndex , nextIndex )
37+ const lineWithoutNewline = code . slice ( startIndex , endIndex ) . trim ( )
38+
39+ if ( isComment ( lineWithoutNewline ) ) {
4840 for ( const lex of this . lexers ) {
49- const comment = parseComment ( line )
41+ const comment = parseComment ( lineWithoutNewline )
5042
5143 const token = lex . bind ( this ) ( comment . content ! )
5244 if ( token ) {
5345 this . tokens . push ( { comment : comment . type , ...token } )
54- this . current = endIndex
46+ this . current = nextIndex
5547 continue scanner
5648 }
5749 }
5850 }
51+
52+ // 对于 code 类型,保留原始行内容(包括换行符)
5953 this . tokens . push ( {
6054 type : 'code' ,
6155 value : rawLine ,
6256 } as CodeToken )
63- this . current = endIndex
57+ this . current = nextIndex
6458 }
6559 return this . tokens
6660 }
0 commit comments