| 1 |
{ |
| 2 |
Copyright 2001-2022 Michalis Kamburelis. |
| 3 |
|
| 4 |
This file is part of "Castle Game Engine". |
| 5 |
|
| 6 |
"Castle Game Engine" is free software; see the file COPYING.txt, |
| 7 |
included in this distribution, for details about the copyright. |
| 8 |
|
| 9 |
"Castle Game Engine" is distributed in the hope that it will be useful, |
| 10 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 12 |
|
| 13 |
---------------------------------------------------------------------------- |
| 14 |
} |
| 15 |
|
| 16 |
{ @abstract(Lexer for CastleScript language, see |
| 17 |
[https://castle-engine.io/castle_script.php].) |
| 18 |
|
| 19 |
For specification of tokens that this lexer understands, |
| 20 |
see documentation of CastleScriptParser unit. } |
| 21 |
|
| 22 |
unit CastleScriptLexer; |
| 23 |
|
| 24 |
{$I castleconf.inc} |
| 25 |
|
| 26 |
interface |
| 27 |
|
| 28 |
uses CastleUtils, CastleScript, SysUtils, Math; |
| 29 |
|
| 30 |
type |
| 31 |
TToken = (tokEnd, |
| 32 |
tokInteger, {< Value of constant integer will be in w TCasScriptLexer.TokenInteger. } |
| 33 |
tokFloat, {< Value of constant float will be in w TCasScriptLexer.TokenFloat. } |
| 34 |
tokBoolean, {< Value of constant boolean will be in w TCasScriptLexer.TokenBoolean. } |
| 35 |
tokString, {< Value of constant string will be in w TCasScriptLexer.TokenString. } |
| 36 |
|
| 37 |
tokIdentifier, {< Identifier will be in TCasScriptLexer.TokenString. } |
| 38 |
tokFuncName, {< Function class of given function will be in TCasScriptLexer.TokenFunctionClass. } |
| 39 |
tokFunctionKeyword, |
| 40 |
|
| 41 |
tokMinus, tokPlus, |
| 42 |
|
| 43 |
tokMultiply, tokFloatDivide, tokIntDivide, tokPower, tokModulo, |
| 44 |
|
| 45 |
tokGreater, tokLesser, tokGreaterEqual, tokLesserEqual, tokEqual, tokNotEqual, |
| 46 |
|
| 47 |
tokLParen, tokRParen, |
| 48 |
tokLQaren, tokRQaren, |
| 49 |
tokComma, tokSemicolon, tokAssignment); |
| 50 |
|
| 51 |
TCasScriptLexer = class |
| 52 |
private |
| 53 |
FToken: TToken; |
| 54 |
FTokenInteger: Int64; |
| 55 |
FTokenFloat: Float; |
| 56 |
FTokenBoolean: boolean; |
| 57 |
FTokenString: string; |
| 58 |
FTokenFunctionClass: TCasScriptFunctionClass; |
| 59 |
|
| 60 |
FTextPos: Integer; |
| 61 |
FText: string; |
| 62 |
public |
| 63 |
property Token: TToken read FToken; |
| 64 |
|
| 65 |
property TokenInteger: Int64 read FTokenInteger; |
| 66 |
property TokenFloat: Float read FTokenFloat; |
| 67 |
property TokenString: string read FTokenString; |
| 68 |
property TokenBoolean: boolean read FTokenBoolean; |
| 69 |
property TokenFunctionClass: TCasScriptFunctionClass read FTokenFunctionClass; |
| 70 |
|
| 71 |
{ Position of lexer in the @link(Text) string. } |
| 72 |
property TextPos: Integer read FTextPos; |
| 73 |
|
| 74 |
{ Text that this lexer reads. } |
| 75 |
property Text: string read FText; |
| 76 |
|
| 77 |
{ NextToken moves to next token (updating fields @link(Token), |
| 78 |
and eventually TokenFloat, TokenString and TokenFunctionClass) |
| 79 |
and returns the value of field @link(Token). |
| 80 |
|
| 81 |
When @link(Token) is tokEnd, then NextToken doesn't do anything, |
| 82 |
i.e. @link(Token) will remain tokEnd forever. |
| 83 |
|
| 84 |
@raises ECasScriptLexerError } |
| 85 |
function NextToken: TToken; |
| 86 |
|
| 87 |
constructor Create(const AText: string); |
| 88 |
|
| 89 |
{ Current token textual description. Useful mainly for debugging lexer. } |
| 90 |
function TokenDescription: string; |
| 91 |
|
| 92 |
{ Check is current token Tok, eventually rise parser error. |
| 93 |
This is an utility for parser. |
| 94 |
|
| 95 |
@raises(ECasScriptParserError |
| 96 |
if current Token doesn't match required Tok.) } |
| 97 |
procedure CheckTokenIs(Tok: TToken); |
| 98 |
end; |
| 99 |
|
| 100 |
{ A common class for ECasScriptLexerError and ECasScriptParserError } |
| 101 |
ECasScriptSyntaxError = class(ECasScriptError) |
| 102 |
private |
| 103 |
FLexerTextPos: Integer; |
| 104 |
FLexerText: string; |
| 105 |
public |
| 106 |
{ Those things are copied from Lexer at exception creation. |
| 107 |
We do not copy reference to Lexer since this would be too dangerous |
| 108 |
in usual situation (you would have to be always sure that you will |
| 109 |
not access it before you Freed it; too troublesome, usually) } |
| 110 |
property LexerTextPos: Integer read FLexerTextPos; |
| 111 |
property LexerText: string read FLexerText; |
| 112 |
constructor Create(Lexer: TCasScriptLexer; const s: string); |
| 113 |
constructor CreateFmt(Lexer: TCasScriptLexer; const s: string; |
| 114 |
const args: array of const); |
| 115 |
end; |
| 116 |
|
| 117 |
ECasScriptLexerError = class(ECasScriptSyntaxError); |
| 118 |
|
| 119 |
ECasScriptParserError = class(ECasScriptSyntaxError); |
| 120 |
|
| 121 |
implementation |
| 122 |
|
| 123 |
uses StrUtils, |
| 124 |
CastleStringUtils; |
| 125 |
|
| 126 |
function Int64Power(base: Integer; power: Cardinal): Int64; |
| 127 |
begin |
| 128 |
result := 1; |
| 129 |
while power > 0 do begin |
| 130 |
result := result*base; |
| 131 |
Dec(power); |
| 132 |
end; |
| 133 |
end; |
| 134 |
|
| 135 |
constructor TCasScriptLexer.Create(const atext: string); |
| 136 |
begin |
| 137 |
inherited Create; |
| 138 |
ftext := atext; |
| 139 |
fTextPos := 1; |
| 140 |
NextToken; |
| 141 |
end; |
| 142 |
|
| 143 |
function TCasScriptLexer.NextToken: TToken; |
| 144 |
const |
| 145 |
whiteChars = [' ', #9, #10, #13]; |
| 146 |
digits = ['0'..'9']; |
| 147 |
Letters = ['a'..'z', 'A'..'Z', '_']; |
| 148 |
|
| 149 |
procedure OmitWhiteSpace; |
| 150 |
begin |
| 151 |
while SCharIs(text, TextPos, whiteChars) do Inc(fTextPos); |
| 152 |
if SCharIs(text, TextPos, '{') then |
| 153 |
begin |
| 154 |
while Text[TextPos] <> '}' do |
| 155 |
begin |
| 156 |
Inc(fTextPos); |
| 157 |
if TextPos > Length(Text) then |
| 158 |
raise ECasScriptLexerError.Create(Self, 'Unfinished comment'); |
| 159 |
end; |
| 160 |
Inc(FTextPos); |
| 161 |
OmitWhiteSpace; { recusively omit the rest of whitespace } |
| 162 |
end; |
| 163 |
end; |
| 164 |
|
| 165 |
function ReadSimpleToken: boolean; |
| 166 |
const |
| 167 |
{ Order on TokensStrs matters - first one wins. |
| 168 |
So if something is a prefix of another thing, the prefix should be latter. |
| 169 |
E.g. "<>" should be detected before "<" gets detected. |
| 170 |
This makes lexer "greedy", as is standard for programming languages lexels. } |
| 171 |
TokensStrs: array [0..19] of string = ( |
| 172 |
'<>', '<=', '>=', '<', '>', |
| 173 |
'=', '+', '-', '*', '/', 'div', ',', |
| 174 |
'(', ')', '^', '[', ']', '%', ';', ':=' |
| 175 |
); |
| 176 |
{ Order and count of Tokens must match TokensStrs. } |
| 177 |
Tokens: array[0..High(TokensStrs)]of TToken = ( |
| 178 |
tokNotEqual, tokLesserEqual, tokGreaterEqual, tokLesser, tokGreater, |
| 179 |
tokEqual, tokPlus, tokMinus, tokMultiply, tokFloatDivide, tokIntDivide, tokComma, |
| 180 |
tokLParen, tokRParen, tokPower, tokLQaren, tokRQaren, tokModulo, tokSemicolon, tokAssignment |
| 181 |
); |
| 182 |
var |
| 183 |
i: integer; |
| 184 |
begin |
| 185 |
for i := 0 to High(TokensStrs) do |
| 186 |
if Copy(text, TextPos, Length(TokensStrs[i])) = TokensStrs[i] then |
| 187 |
begin |
| 188 |
ftoken := Tokens[i]; |
| 189 |
Inc(fTextPos, Length(TokensStrs[i])); |
| 190 |
result := true; |
| 191 |
exit; |
| 192 |
end; |
| 193 |
result := false; |
| 194 |
end; |
| 195 |
|
| 196 |
{ Read a string, to a tokString token. |
| 197 |
Read from current TexPos. |
| 198 |
Update ftoken and fTokenString, and advance TextPos, and return true |
| 199 |
if success. |
| 200 |
|
| 201 |
Results in false if we're not standing at an apostrophe now. } |
| 202 |
function ReadString: boolean; |
| 203 |
var |
| 204 |
NextApos: Integer; |
| 205 |
begin |
| 206 |
Result := Text[FTextPos] = ''''; |
| 207 |
if not Result then Exit; |
| 208 |
|
| 209 |
FToken := tokString; |
| 210 |
FTokenString := ''; |
| 211 |
|
| 212 |
repeat |
| 213 |
NextApos := PosEx('''', Text, FTextPos + 1); |
| 214 |
if NextApos = 0 then |
| 215 |
raise ECasScriptLexerError.Create(Self, 'Unfinished string'); |
| 216 |
FTokenString := FTokenString + CopyPos(Text, FTextPos + 1, NextApos - 1); |
| 217 |
FTextPos := NextApos + 1; |
| 218 |
|
| 219 |
if SCharIs(Text, FTextPos, '''') then |
| 220 |
FTokenString := FTokenString + '''' |
| 221 |
else |
| 222 |
Break; |
| 223 |
until false; |
| 224 |
end; |
| 225 |
|
| 226 |
{ Read a number, to a tokFloat or tokInteger token. |
| 227 |
Read from current TexPos. |
| 228 |
Update ftoken and fTokenFloat, and advance TextPos, and return true |
| 229 |
if success. |
| 230 |
|
| 231 |
Results in false if we're not standing at a digit now. } |
| 232 |
function ReadNumber: boolean; |
| 233 |
var |
| 234 |
digitsCount: cardinal; |
| 235 |
val: Int64; |
| 236 |
begin |
| 237 |
result := text[fTextPos] in digits; |
| 238 |
if not result then exit; |
| 239 |
|
| 240 |
{ Assume it's an integer token at first, until we will encounter the dot. } |
| 241 |
|
| 242 |
Ftoken := tokInteger; |
| 243 |
FTokenInteger := DigitAsByte(text[fTextPos]); |
| 244 |
Inc(fTextPos); |
| 245 |
while SCharIs(text, fTextPos, digits) do |
| 246 |
begin |
| 247 |
FTokenInteger := 10 * FTokenInteger + DigitAsByte(text[fTextPos]); |
| 248 |
Inc(fTextPos); |
| 249 |
end; |
| 250 |
|
| 251 |
if SCharIs(text, fTextPos, '.') then |
| 252 |
begin |
| 253 |
{ So it's a float. Read fractional part. } |
| 254 |
FToken := tokFloat; |
| 255 |
FTokenFloat := FTokenInteger; |
| 256 |
|
| 257 |
Inc(fTextPos); |
| 258 |
if not SCharIs(text, fTextPos, digits) then |
| 259 |
raise ECasScriptLexerError.Create(Self, 'Digit expected'); |
| 260 |
digitsCount := 1; |
| 261 |
val := DigitAsByte(text[fTextPos]); |
| 262 |
Inc(fTextPos); |
| 263 |
while SCharIs(text, fTextPos, digits) do |
| 264 |
begin |
| 265 |
val := 10*val+DigitAsByte(text[fTextPos]); |
| 266 |
Inc(digitsCount); |
| 267 |
Inc(fTextPos); |
| 268 |
end; |
| 269 |
fTokenFloat := fTokenFloat + (val / Int64Power(10, digitsCount)); |
| 270 |
end; |
| 271 |
end; |
| 272 |
|
| 273 |
function ReadIdentifier: string; |
| 274 |
{ czytaj identyfikator - to znaczy, czytaj nazwe zmiennej co do ktorej nie |
| 275 |
jestesmy pewni czy nie jest przypadkiem nazwa funkcji. Uwaga - powinien |
| 276 |
zbadac kazdy znak, poczynajac od text[fTextPos], czy rzeczywiscie |
| 277 |
nalezy do identChars. |
| 278 |
|
| 279 |
Always returns non-empty string (length >= 1) } |
| 280 |
const identStartChars = Letters; |
| 281 |
identChars = identStartChars + digits; |
| 282 |
var startPos: integer; |
| 283 |
begin |
| 284 |
if not (text[fTextPos] in identStartChars) then |
| 285 |
raise ECasScriptLexerError.CreateFmt(Self, |
| 286 |
'Invalid character "%s" not allowed in CastleScript', [text[fTextPos]]); |
| 287 |
startPos := fTextPos; |
| 288 |
Inc(fTextPos); |
| 289 |
while SCharIs(text, fTextPos, identChars) do Inc(fTextPos); |
| 290 |
result := CopyPos(text, startPos, fTextPos-1); |
| 291 |
end; |
| 292 |
|
| 293 |
const |
| 294 |
FloatConsts: array [0..1] of string = ('pi', 'enat'); |
| 295 |
FloatConstsValues: array [0..High(FloatConsts)] of float = (pi, enatural); |
| 296 |
BooleanConsts: array [0..1] of string = ('false', 'true'); |
| 297 |
BooleanConstsValues: array [0..High(BooleanConsts)] of boolean = (false, true); |
| 298 |
IntConsts: array [0..19] of string = ( |
| 299 |
'ACTION_KEY_F1', |
| 300 |
'ACTION_KEY_F2', |
| 301 |
'ACTION_KEY_F3', |
| 302 |
'ACTION_KEY_F4', |
| 303 |
'ACTION_KEY_F5', |
| 304 |
'ACTION_KEY_F6', |
| 305 |
'ACTION_KEY_F7', |
| 306 |
'ACTION_KEY_F8', |
| 307 |
'ACTION_KEY_F9', |
| 308 |
'ACTION_KEY_F10', |
| 309 |
'ACTION_KEY_F11', |
| 310 |
'ACTION_KEY_F12', |
| 311 |
'ACTION_KEY_HOME', |
| 312 |
'ACTION_KEY_END', |
| 313 |
'ACTION_KEY_PGUP', |
| 314 |
'ACTION_KEY_PGDN', |
| 315 |
'ACTION_KEY_UP', |
| 316 |
'ACTION_KEY_DOWN', |
| 317 |
'ACTION_KEY_LEFT', |
| 318 |
'ACTION_KEY_RIGHT' |
| 319 |
); |
| 320 |
IntConstsValues: array [0..High(IntConsts)] of Integer = ( |
| 321 |
1, 2, 3, 4, 5, 6, 7, 8, 9,10, |
| 322 |
11,12,13,14,15,16,17,18,19,20 ); |
| 323 |
var |
| 324 |
p: integer; |
| 325 |
fc: TCasScriptFunctionClass; |
| 326 |
begin |
| 327 |
OmitWhiteSpace; |
| 328 |
|
| 329 |
if TextPos > Length(text) then |
| 330 |
ftoken := tokEnd else |
| 331 |
begin |
| 332 |
if not ReadString then |
| 333 |
if not ReadNumber then |
| 334 |
if not ReadSimpleToken then |
| 335 |
begin |
| 336 |
{ It's something that *may* be an identifier. |
| 337 |
Unless it matches some keyword, built-in function or constant. } |
| 338 |
ftoken := tokIdentifier; |
| 339 |
fTokenString := ReadIdentifier; |
| 340 |
|
| 341 |
{ Maybe it's tokFunctionKeyword (the only keyword for now) } |
| 342 |
if ftoken = tokIdentifier then |
| 343 |
begin |
| 344 |
if SameText(fTokenString, 'function') then |
| 345 |
begin |
| 346 |
ftoken := tokFunctionKeyword; |
| 347 |
end; |
| 348 |
end; |
| 349 |
|
| 350 |
{ Maybe it's tokFuncName } |
| 351 |
if ftoken = tokIdentifier then |
| 352 |
begin |
| 353 |
fc := FunctionHandlers.SearchFunctionShortName(fTokenString); |
| 354 |
if fc <> nil then |
| 355 |
begin |
| 356 |
ftoken := tokFuncName; |
| 357 |
fTokenFunctionClass := fc; |
| 358 |
end; |
| 359 |
end; |
| 360 |
|
| 361 |
{ Maybe it's a named constant float } |
| 362 |
if ftoken = tokIdentifier then |
| 363 |
begin |
| 364 |
p := ArrayPosText(fTokenString, FloatConsts); |
| 365 |
if p >= 0 then |
| 366 |
begin |
| 367 |
ftoken := tokFloat; |
| 368 |
fTokenFloat := FloatConstsValues[p]; |
| 369 |
end; |
| 370 |
end; |
| 371 |
|
| 372 |
{ Maybe it's a named constant boolean } |
| 373 |
if ftoken = tokIdentifier then |
| 374 |
begin |
| 375 |
p := ArrayPosText(fTokenString, BooleanConsts); |
| 376 |
if p >= 0 then |
| 377 |
begin |
| 378 |
ftoken := tokBoolean; |
| 379 |
fTokenBoolean := BooleanConstsValues[p]; |
| 380 |
end; |
| 381 |
end; |
| 382 |
|
| 383 |
{ Maybe it's a named constant integer } |
| 384 |
if ftoken = tokIdentifier then |
| 385 |
begin |
| 386 |
p := ArrayPosText(fTokenString, IntConsts); |
| 387 |
if p >= 0 then |
| 388 |
begin |
| 389 |
ftoken := tokInteger; |
| 390 |
fTokenInteger := IntConstsValues[p]; |
| 391 |
end; |
| 392 |
end; |
| 393 |
end; |
| 394 |
end; |
| 395 |
result := token; |
| 396 |
end; |
| 397 |
|
| 398 |
const |
| 399 |
TokenShortDescription: array [TToken] of string = |
| 400 |
( 'end of stream', |
| 401 |
'integer', |
| 402 |
'float', |
| 403 |
'boolean', |
| 404 |
'string', |
| 405 |
'identifier', |
| 406 |
'built-in function', |
| 407 |
'function', |
| 408 |
'-', '+', |
| 409 |
'*', '/', 'div', '^', '%', |
| 410 |
'>', '<', '>=', '<=', '=', '<>', |
| 411 |
'(', ')', |
| 412 |
'[', ']', |
| 413 |
',', ';', ':='); |
| 414 |
|
| 415 |
function TCasScriptLexer.TokenDescription: string; |
| 416 |
begin |
| 417 |
Result := TokenShortDescription[Token]; |
| 418 |
case Token of |
| 419 |
tokInteger: Result := Result + Format(' %d', [TokenInteger]); |
| 420 |
tokFloat: Result := Result + Format(' %g', [TokenFloat]); |
| 421 |
tokBoolean: Result := Result + Format(' %s', [BoolToStr(TokenBoolean, true)]); |
| 422 |
tokString: Result := Result + Format(' ''%s''', [TokenString]); |
| 423 |
tokIdentifier: Result := Result + Format(' %s', [TokenString]); |
| 424 |
tokFuncName: Result := Result + Format(' %s', [TokenFunctionClass.Name]); |
| 425 |
else ; |
| 426 |
end; |
| 427 |
end; |
| 428 |
|
| 429 |
procedure TCasScriptLexer.CheckTokenIs(Tok: TToken); |
| 430 |
begin |
| 431 |
if Token <> Tok then |
| 432 |
raise ECasScriptParserError.CreateFmt(Self, |
| 433 |
'Expected "%s", but got "%s"', |
| 434 |
[ TokenShortDescription[Tok], TokenDescription ]); |
| 435 |
end; |
| 436 |
|
| 437 |
{ ECasScriptSyntaxError --------------------------------------- } |
| 438 |
|
| 439 |
constructor ECasScriptSyntaxError.Create(Lexer: TCasScriptLexer; const s: string); |
| 440 |
begin |
| 441 |
inherited Create(s); |
| 442 |
FLexerTextPos := Lexer.TextPos; |
| 443 |
FLexerText := Lexer.Text; |
| 444 |
end; |
| 445 |
|
| 446 |
constructor ECasScriptSyntaxError.CreateFmt(Lexer: TCasScriptLexer; const s: string; |
| 447 |
const args: array of const); |
| 448 |
begin |
| 449 |
Create(Lexer, Format(s, args)) |
| 450 |
end; |
| 451 |
|
| 452 |
end. |