@@ -10,8 +10,8 @@ export interface Token<T = TokenType, V = string> {
10
10
// Checks for WGSL-specific `fn foo(`, `var bar =`, `let baz =`, `const qux =`
11
11
const WGSL_REGEX = / \b f n \s + \w + \s * \( | \b ( v a r | l e t | c o n s t ) \s + \w + \s * [: = ] /
12
12
13
- const FLOAT_REGEX = / ^ ( \d + \. \d * | \d * \. \d + ) ( [ e E p P ] [ - + ] ? \d + ) ? [ f F h H ] ? $ /
14
- const INT_REGEX = / ^ ( 0 [ x X ] [ \w \d ] + | \d + ) [ i I u U ] ? $ /
13
+ const FLOAT_REGEX = / ( ( \d + \. \d * | \d * \. \d + ) ( [ e E p P ] [ - + ] ? \d + ) ? | \d + [ e E p P ] [ - + ] ? \d + ) [ f F h H ] ? / y
14
+ const INT_REGEX = / ( 0 [ x X ] [ \w \d ] + | \d + ) [ i I u U ] ? / y
15
15
const BOOL_REGEX = / ^ ( t r u e | f a l s e ) $ /
16
16
17
17
const ZERO = 48
@@ -36,6 +36,12 @@ const isSpace = (c: number) => isLine(c) || c === TAB || c === SPACE
36
36
const isIdent = ( c : number ) => isAlpha ( c ) || isDigit ( c ) || c === UNDERSCORE
37
37
const isMacro = ( c : number ) => c === HASH || c === AT
38
38
39
+ // https://mrale.ph/blog/2016/11/23/making-less-dart-faster.html
40
+ function matchAsPrefix ( regex : RegExp , string : string , start : number ) : string | undefined {
41
+ regex . lastIndex = start
42
+ return regex . exec ( string ) ?. [ 0 ]
43
+ }
44
+
39
45
/**
40
46
* Tokenizes a string of GLSL or WGSL code.
41
47
*/
@@ -52,9 +58,13 @@ export function tokenize(code: string, index: number = 0): Token[] {
52
58
while ( isSpace ( code . charCodeAt ( index ) ) ) value += code [ index ++ ]
53
59
tokens . push ( { type : 'whitespace' , value } )
54
60
} else if ( isDigit ( char ) || ( char === DOT && isDigit ( code . charCodeAt ( index ) ) ) ) {
55
- while ( FLOAT_REGEX . test ( value + code [ index ] ) || INT_REGEX . test ( value + code [ index ] ) ) value += code [ index ++ ]
56
- if ( FLOAT_REGEX . test ( value ) ) tokens . push ( { type : 'float' , value } )
57
- else tokens . push ( { type : 'int' , value } )
61
+ if ( ( value = matchAsPrefix ( FLOAT_REGEX , code , index - 1 ) ! ) ) {
62
+ index = FLOAT_REGEX . lastIndex
63
+ tokens . push ( { type : 'float' , value } )
64
+ } else if ( ( value = matchAsPrefix ( INT_REGEX , code , index - 1 ) ! ) ) {
65
+ index = INT_REGEX . lastIndex
66
+ tokens . push ( { type : 'int' , value } )
67
+ }
58
68
} else if ( isIdent ( char ) ) {
59
69
while ( isIdent ( code . charCodeAt ( index ) ) ) value += code [ index ++ ]
60
70
if ( BOOL_REGEX . test ( value ) ) tokens . push ( { type : 'bool' , value } )
0 commit comments