library-ts/browser/text/lexer/LexerMatcher.ts

85 lines
2.0 KiB
TypeScript
Raw Permalink Normal View History

2025-03-08 08:16:54 +00:00
import { RegExpUtility } from "../RegExpUtitlity";
import { Lexer } from "./Lexer";
export class LexerMatcher
{
_mode:string;
_type:string;
_nextMode:string;
_matcher:RegExp;
compressTokens:boolean = false;
get mode(){ return this._mode; }
get type(){ return this._type; }
get nextMode(){ return this._nextMode ? this._nextMode : this._mode; }
get matcher() { return this._matcher; }
constructor( type:string, matcher:RegExp, mode:string = Lexer.defaultMode, nextMode:string=null )
{
this._type = type;
this._matcher = RegExpUtility.makeSticky( matcher );
this._mode = mode;
this._nextMode = nextMode;
}
getMatch( value:string, index:number = 0, alternative:string = null)
{
let result = this._matcher.exec( value );
if ( ! result || result.length <= index )
{
return alternative;
}
return result[ index ];
}
matchLength( source:string, offset:number )
{
this._matcher.lastIndex = offset;
var result = this._matcher.exec( source );
if ( result && result.index != offset )
{
var message = "Illegal match index! Not a sticky matcher: " + this._matcher + ".";
message += "Offset: " + offset + " Matched Index: " + result.index ;
throw message;
}
if ( result )
{
return result[ 0 ].length;
}
return -1;
}
getMatchResult( source:string, offset:number )
{
this._matcher.lastIndex = offset;
var result = this._matcher.exec( source );
if ( result && result.index != offset )
{
var message = "Illegal match index! Not a sticky matcher: " + this._matcher + ".";
message += "Offset: " + offset + " Matched Index: " + result.index ;
throw message;
}
return result;
}
isMatching( source:string )
{
let matchLength = this.matchLength( source, 0 );
if ( matchLength === source.length )
{
return true;
}
return false;
}
}