Debian Codegraph @

src/castlescript/castlescriptparser.pas

raw
1 {
2 Copyright 2001-2023 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 { Parser for @url(https://castle-engine.io/castle_script.php CastleScript),
17 along with high-level utilities like @link(ParseConstantFloatExpression).
18
19 This can parse whole program in CastleScript language, is also prepared
20 to parse only a single expression (usefull for cases when I need
21 to input only a mathematical expression, like for glplotter function
22 expression). }
23 unit CastleScriptParser;
24
25 {$I castleconf.inc}
26
27 interface
28
29 uses CastleScript, CastleScriptLexer, Math, CastleUtils;
30
31 type
32 { Error when parsing CastleScript expression. }
33 ECasScriptSyntaxError = CastleScriptLexer.ECasScriptSyntaxError;
34
35 { Parse a CastleScript expression that should be calculated to a float value.
36 The easiest way to evaluate such expression
37 is to call @link(TCasScriptExpression.AsFloat) method.
38
39 This creates and returns an instance of TCasScriptExpression,
40 that represents parsed tree of expression in S,
41 casted to float.
42 This parses a subset of CastleScript language, that allows you
43 to define only one expression without any assignments.
44 Also the end result is always casted to the float() type
45 (just like it would be wrapped inside float() function call ---
46 in fact this is exactly what happens.)
47
48 The end result is that this is perfect for describing things
49 like function expressions, ideal e.g. for
50 [https://castle-engine.io/glplotter_and_gen_function.php].
51
52 @param(Variables contains a list of named values you want
53 to allow in this expression.
54
55 Important: They will all have
56 OwnedByParentExpression set to @false, and you will have to
57 free them yourself.
58 That's because given expression may use the same variable more than once
59 (so freeing it twice would cause bugs), or not use it at all
60 (so it will be automatically freed at all).
61
62 So setting OwnedByParentExpression and freeing it yourself
63 is the only sensible thing to do.)
64
65 @raises(ECasScriptSyntaxError in case of error when parsing expression.) }
66 function ParseFloatExpression(const S: string;
67 const Variables: array of TCasScriptValue): TCasScriptExpression;
68
69 { Parse a CastleScript expression that should be calculated to a float value.
70 The easiest way to evaluate such expression
71 is to call @link(TCasScriptExpression.AsInt) method.
72
73 See @link(ParseFloatExpression) for more details, this procedure is equivalent
74 but it operates on floats. }
75 function ParseIntExpression(const S: string;
76 const Variables: array of TCasScriptValue): TCasScriptExpression;
77
78 { Parse a CastleScript expression that should be calculated to a string value.
79 The easiest way to evaluate such expression
80 is to call @link(TCasScriptExpression.AsString) method.
81
82 See @link(ParseFloatExpression) for more details, this procedure is equivalent
83 but it operates on strings. }
84 function ParseStringExpression(const S: string;
85 const Variables: array of TCasScriptValue): TCasScriptExpression;
86
87 { Parse a CastleScript expression that should be calculated to a boolean value.
88 The easiest way to evaluate such expression
89 is to call @link(TCasScriptExpression.AsBool) method.
90
91 See @link(ParseFloatExpression) for more details, this procedure is equivalent
92 but it operates on booleans. }
93 function ParseBoolExpression(const S: string;
94 const Variables: array of TCasScriptValue): TCasScriptExpression;
95
96 { Creates and returns instance of TCasScriptExpression,
97 that represents parsed tree of expression in S.
98 @param(Variables contains a list of named values you want
99 to allow in this expression.
100 See ParseFloatExpression for description.)
101 @raises(ECasScriptSyntaxError in case of error when parsing expression.) }
102 function ParseExpression(const S: string;
103 const Variables: array of TCasScriptValue): TCasScriptExpression;
104
105 { Parse constant float expression.
106 This can be used as a drop-in replacement for StrToFloatDot.
107 Takes a string with any constant mathematical expression,
108 according to CastleScript syntax, parses it and calculates.
109
110 @raises(ECasScriptSyntaxError in case of error when parsing expression.) }
111 function ParseConstantFloatExpression(const S: string): Float;
112
113 { Parse constant Int64 expression.
114 This can be used as a drop-in replacement for StrToInt.
115 Takes a string with any constant mathematical expression,
116 according to CastleScript syntax, parses it and calculates.
117
118 @raises(ECasScriptSyntaxError in case of error when parsing expression.) }
119 function ParseConstantIntExpression(const S: string): Int64;
120
121 { Parse CastleScript program.
122
123 Variable list works like for ParseFloatExpression, see there for
124 description.
125
126 @raises(ECasScriptSyntaxError in case of error when parsing expression.)
127
128 @groupBegin }
129 function ParseProgram(const S: string;
130 const Variables: array of TCasScriptValue): TCasScriptProgram; overload;
131 function ParseProgram(const S: string;
132 const Variables: TCasScriptValueList): TCasScriptProgram; overload;
133 { @groupEnd }
134
135 implementation
136
137 uses SysUtils, CastleScriptCoreFunctions;
138
139 function Expression(
140 const Lexer: TCasScriptLexer;
141 Environment: TCasScriptEnvironment;
142 const Variables: array of TCasScriptValue): TCasScriptExpression; forward; overload;
143
144 function NonAssignmentExpression(
145 const Lexer: TCasScriptLexer;
146 Environment: TCasScriptEnvironment;
147 const AllowFullExpressionInFactor: boolean;
148 const Variables: array of TCasScriptValue): TCasScriptExpression;
149
150 function BinaryOper(tok: TToken): TCasScriptFunctionClass;
151 begin
152 case tok of
153 tokPlus: Result := TCasScriptAdd;
154 tokMinus: Result := TCasScriptSubtract;
155
156 tokMultiply: Result := TCasScriptMultiply;
157 tokFloatDivide: Result := TCasScriptFloatDivide;
158 tokIntDivide: Result := TCasScriptIntDivide;
159 tokPower: Result := TCasScriptPower;
160 tokModulo: Result := TCasScriptModulo;
161
162 tokGreater: Result := TCasScriptGreater;
163 tokLesser: Result := TCasScriptLesser;
164 tokGreaterEqual: Result := TCasScriptGreaterEq;
165 tokLesserEqual: Result := TCasScriptLesserEq;
166 tokEqual: Result := TCasScriptEqual;
167 tokNotEqual: Result := TCasScriptNotEqual;
168
169 else raise ECasScriptParserError.Create(Lexer,
170 'internal error : token not a binary operator');
171 end
172 end;
173
174 const
175 FactorOperator = [tokMultiply, tokFloatDivide, tokIntDivide, tokPower, tokModulo];
176 TermOperator = [tokPlus, tokMinus];
177 ComparisonOperator = [tokGreater, tokLesser, tokGreaterEqual, tokLesserEqual, tokEqual, tokNotEqual];
178
179 function Operand: TCasScriptValue;
180 var
181 I: Integer;
182 begin
183 Lexer.CheckTokenIs(tokIdentifier);
184
185 Result := nil;
186 for I := 0 to Length(Variables) - 1 do
187 if SameText(Variables[I].Name, Lexer.TokenString) then
188 begin
189 Result := Variables[I];
190 Break;
191 end;
192
193 if Result = nil then
194 raise ECasScriptParserError.CreateFmt(Lexer, 'Undefined identifier "%s"',
195 [Lexer.TokenString]);
196
197 Lexer.NextToken;
198 end;
199
200 { Returns either Expression or NonAssignmentExpression, depending on
201 AllowFullExpressionInFactor value. }
202 function ExpressionInsideFactor: TCasScriptExpression;
203 begin
204 if AllowFullExpressionInFactor then
205 Result := Expression(Lexer, Environment, Variables) else
206 Result := NonAssignmentExpression(Lexer, Environment,
207 AllowFullExpressionInFactor, Variables);
208 end;
209
210 function Factor: TCasScriptExpression;
211 var
212 FC: TCasScriptFunctionClass;
213 FParams: TCasScriptExpressionList;
214 begin
215 Result := nil;
216 try
217 case Lexer.Token of
218 tokIdentifier: Result := Operand;
219 tokInteger: begin
220 Result := TCasScriptInteger.Create(false, Lexer.TokenInteger);
221 Result.Environment := Environment;
222 Lexer.NextToken;
223 end;
224 tokFloat: begin
225 Result := TCasScriptFloat.Create(false, Lexer.TokenFloat);
226 Result.Environment := Environment;
227 Lexer.NextToken;
228 end;
229 tokBoolean: begin
230 Result := TCasScriptBoolean.Create(false, Lexer.TokenBoolean);
231 Result.Environment := Environment;
232 Lexer.NextToken;
233 end;
234 tokString: begin
235 Result := TCasScriptString.Create(false, Lexer.TokenString);
236 Result.Environment := Environment;
237 Lexer.NextToken;
238 end;
239 tokMinus: begin
240 Lexer.NextToken;
241 Result := TCasScriptNegate.Create([Factor()]);
242 Result.Environment := Environment;
243 end;
244 tokLParen: begin
245 Lexer.NextToken;
246 Result := ExpressionInsideFactor;
247 Lexer.CheckTokenIs(tokRParen);
248 Lexer.NextToken;
249 end;
250 tokFuncName: begin
251 FC := Lexer.TokenFunctionClass;
252 Lexer.NextToken;
253 FParams := TCasScriptExpressionList.Create(false);
254 try
255 try
256 Lexer.CheckTokenIs(tokLParen);
257 Lexer.NextToken;
258
259 if Lexer.Token <> tokRParen then
260 begin
261 repeat
262 FParams.Add(ExpressionInsideFactor);
263 if Lexer.Token = tokRParen then
264 Break;
265 Lexer.CheckTokenIs(tokComma);
266 Lexer.NextToken;
267 until false;
268 end;
269
270 Lexer.CheckTokenIs(tokRParen);
271 Lexer.NextToken;
272 except FParams.FreeContentsByParentExpression; raise; end;
273 Result := FC.Create(FParams);
274 Result.Environment := Environment;
275 finally FParams.Free end;
276 end;
277 else raise ECasScriptParserError.Create(Lexer, 'Incorrect expression factor: "' + Lexer.TokenDescription + '"');
278 end;
279 except Result.FreeByParentExpression; raise end;
280 end;
281
282 function Term: TCasScriptExpression;
283 var
284 FC: TCasScriptFunctionClass;
285 begin
286 Result := nil;
287 try
288 Result := Factor;
289 while Lexer.Token in FactorOperator do
290 begin
291 FC := BinaryOper(Lexer.Token);
292 Lexer.NextToken;
293 Result := FC.Create([Result, Factor]);
294 Result.Environment := Environment;
295 end;
296 except Result.FreeByParentExpression; raise end;
297 end;
298
299 function ComparisonArgument: TCasScriptExpression;
300 var
301 FC: TCasScriptFunctionClass;
302 begin
303 Result := nil;
304 try
305 Result := Term;
306 while Lexer.Token in TermOperator do
307 begin
308 FC := BinaryOper(Lexer.Token);
309 Lexer.NextToken;
310 Result := FC.Create([Result, Term]);
311 Result.Environment := Environment;
312 end;
313 except Result.FreeByParentExpression; raise end;
314 end;
315
316 var
317 FC: TCasScriptFunctionClass;
318 begin
319 Result := nil;
320 try
321 Result := ComparisonArgument;
322 while Lexer.Token in ComparisonOperator do
323 begin
324 FC := BinaryOper(Lexer.Token);
325 Lexer.NextToken;
326 Result := FC.Create([Result, ComparisonArgument]);
327 Result.Environment := Environment;
328 end;
329 except Result.FreeByParentExpression; raise end;
330 end;
331
332 function Expression(
333 const Lexer: TCasScriptLexer;
334 Environment: TCasScriptEnvironment;
335 const Variables: TCasScriptValueList): TCasScriptExpression; overload;
336 begin
337 Result := Expression(Lexer, Environment, Variables.ToArray);
338 end;
339
340 function Expression(
341 const Lexer: TCasScriptLexer;
342 Environment: TCasScriptEnvironment;
343 const Variables: array of TCasScriptValue): TCasScriptExpression; overload;
344
345 function PossiblyAssignmentExpression: TCasScriptExpression;
346 { How to parse this?
347
348 Straighforward approach is to try parsing
349 Operand, then check is it followed by ":=".
350 In case of parsing errors (we can catch them by ECasScriptParserError),
351 or something else than ":=", we rollback and parse NonAssignmentExpression.
352
353 The trouble with this approach: "rollback". This is uneasy,
354 as you have to carefully remember all tokens eaten during
355 Operand parsing, and unget them to lexer (or otherwise reparse them).
356
357 Simpler and faster approach used: just always parse an
358 NonAssignmentExpression. This uses the fact that Operand is
359 also a valid NonAssignmentExpression, and NonAssignmentExpression
360 will not eat anything after ":=" (following the grammar, ":="
361 cannot occur within NonAssignmentExpression without parenthesis).
362 After parsing NonAssignmentExpression, we can check for ":=". }
363 var
364 Operand, AssignedValue: TCasScriptExpression;
365 begin
366 Result := NonAssignmentExpression(Lexer, Environment, true, Variables);
367 try
368 if Lexer.Token = tokAssignment then
369 begin
370 Lexer.NextToken;
371
372 AssignedValue := PossiblyAssignmentExpression();
373
374 Operand := Result;
375 { set Result to nil, in case of exception from TCasScriptAssignment
376 constructor. }
377 Result := nil;
378
379 { TCasScriptAssignment in constructor checks that
380 Operand is actually a simple writeable operand. }
381 Result := TCasScriptAssignment.Create([Operand, AssignedValue]);
382 Result.Environment := Environment;
383 end;
384 except Result.FreeByParentExpression; raise end;
385 end;
386
387 var
388 SequenceArgs: TCasScriptExpressionList;
389 begin
390 Result := nil;
391 try
392 Result := PossiblyAssignmentExpression;
393
394 if Lexer.Token = tokSemicolon then
395 begin
396 SequenceArgs := TCasScriptExpressionList.Create(false);
397 try
398 try
399 SequenceArgs.Add(Result);
400 Result := nil;
401
402 while Lexer.Token = tokSemicolon do
403 begin
404 Lexer.NextToken;
405 SequenceArgs.Add(PossiblyAssignmentExpression);
406 end;
407 except SequenceArgs.FreeContentsByParentExpression; raise end;
408
409 Result := TCasScriptSequence.Create(SequenceArgs);
410 Result.Environment := Environment;
411 finally FreeAndNil(SequenceArgs) end;
412 end;
413 except Result.FreeByParentExpression; raise end;
414 end;
415
416 function AProgram(
417 const Lexer: TCasScriptLexer;
418 const GlobalVariables: array of TCasScriptValue): TCasScriptProgram;
419 var
420 Environment: TCasScriptEnvironment;
421
422 function AFunction: TCasScriptUserFunction;
423 var
424 BodyVariables: TCasScriptValueList;
425 Parameter: TCasScriptValue;
426 begin
427 Result := TCasScriptUserFunction.Create;
428 try
429 Lexer.CheckTokenIs(tokIdentifier);
430 Result.Name := Lexer.TokenString;
431 Lexer.NextToken;
432
433 BodyVariables := TCasScriptValueList.Create(false);
434 try
435 Lexer.CheckTokenIs(tokLParen);
436 Lexer.NextToken;
437
438 if Lexer.Token <> tokRParen then
439 begin
440 repeat
441 Lexer.CheckTokenIs(tokIdentifier);
442 Parameter := TCasScriptParameterValue.Create(true);
443 Parameter.Environment := Environment;
444 Parameter.Name := Lexer.TokenString;
445 Parameter.OwnedByParentExpression := false;
446 Result.Parameters.Add(Parameter);
447 BodyVariables.Add(Parameter);
448 Lexer.NextToken;
449
450 if Lexer.Token = tokRParen then
451 Break else
452 begin
453 Lexer.CheckTokenIs(tokComma);
454 Lexer.NextToken;
455 end;
456 until false;
457 end;
458
459 Lexer.NextToken; { eat ")" }
460
461 { We first added parameters, then added GlobalVariables,
462 so when resolving, parameter names will hide global
463 variable names, just like they should in normal language. }
464 BodyVariables.AddRange(GlobalVariables);
465
466 Result.Body := Expression(Lexer, Environment, BodyVariables);
467 finally FreeAndNil(BodyVariables); end;
468 except FreeAndNil(Result); raise end;
469 end;
470
471 begin
472 Result := TCasScriptProgram.Create;
473 try
474 Environment := Result.Environment;
475 while Lexer.Token = tokFunctionKeyword do
476 begin
477 Lexer.NextToken;
478 Result.Functions.Add(AFunction);
479 end;
480 except FreeAndNil(Result); raise end;
481 end;
482
483 { ParseXxxExpression ------------------------------------------------------- }
484
485 function ParseSimpleExpression(const S: string;
486 const Variables: array of TCasScriptValue): TCasScriptExpression;
487 var
488 Lexer: TCasScriptLexer;
489 I: Integer;
490 begin
491 for I := 0 to Length(Variables) - 1 do
492 Variables[I].OwnedByParentExpression := false;
493
494 Lexer := TCasScriptLexer.Create(s);
495 try
496 Result := nil;
497 try
498 try
499 try
500 Result := NonAssignmentExpression(Lexer, nil { no Environment }, false, Variables);
501 Lexer.CheckTokenIs(tokEnd);
502 except
503 { Change ECasScriptFunctionArgumentsError (raised when
504 creating functions) to ECasScriptParserError.
505 This allows the caller to catch only ECasScriptSyntaxError,
506 and adds position information to error message. }
507 on E: ECasScriptFunctionArgumentsError do
508 raise ECasScriptParserError.Create(Lexer, E.Message);
509 end;
510 except
511 on E: ECasScriptError do
512 begin
513 if ScriptVerboseMessages then
514 E.Message := E.Message + NL +
515 'The error above is inside expression:' + NL + S;
516 raise;
517 end;
518 end;
519 except Result.FreeByParentExpression; raise end;
520 finally Lexer.Free end;
521 end;
522
523 function ParseFloatExpression(const S: string;
524 const Variables: array of TCasScriptValue): TCasScriptExpression;
525 begin
526 Result := ParseSimpleExpression(S, Variables);
527 { At the end, wrap Result in float() cast. }
528 Result := TCasScriptFloatFun.Create([Result]);
529 end;
530
531 function ParseIntExpression(const S: string;
532 const Variables: array of TCasScriptValue): TCasScriptExpression;
533 begin
534 Result := ParseSimpleExpression(S, Variables);
535 { At the end, wrap Result in int() cast. }
536 Result := TCasScriptInt.Create([Result]);
537 end;
538
539 function ParseStringExpression(const S: string;
540 const Variables: array of TCasScriptValue): TCasScriptExpression;
541 begin
542 Result := ParseSimpleExpression(S, Variables);
543 { At the end, wrap Result in string() cast. }
544 Result := TCasScriptStringFun.Create([Result]);
545 end;
546
547 function ParseBoolExpression(const S: string;
548 const Variables: array of TCasScriptValue): TCasScriptExpression;
549 begin
550 Result := ParseSimpleExpression(S, Variables);
551 { At the end, wrap Result in bool() cast. }
552 Result := TCasScriptBool.Create([Result]);
553 end;
554
555 function ParseExpression(const S: string;
556 const Variables: array of TCasScriptValue): TCasScriptExpression;
557 var
558 Lexer: TCasScriptLexer;
559 I: Integer;
560 begin
561 for I := 0 to Length(Variables) - 1 do
562 Variables[I].OwnedByParentExpression := false;
563
564 Lexer := TCasScriptLexer.Create(s);
565 try
566 Result := nil;
567 try
568 try
569 Result := Expression(Lexer, nil { no Environment }, Variables);
570 Lexer.CheckTokenIs(tokEnd);
571 except
572 { Change ECasScriptFunctionArgumentsError (raised when
573 creating functions) to ECasScriptParserError.
574 This allows the caller to catch only ECasScriptSyntaxError,
575 and adds position information to error message. }
576 on E: ECasScriptFunctionArgumentsError do
577 raise ECasScriptParserError.Create(Lexer, E.Message);
578 end;
579 except Result.FreeByParentExpression; raise end;
580 finally Lexer.Free end;
581 end;
582
583 { ParseConstant*Expression ----------------------------------------------- }
584
585 function ParseConstantFloatExpression(const S: string): Float;
586 var
587 Expr: TCasScriptExpression;
588 begin
589 try
590 Expr := ParseFloatExpression(s, []);
591 except
592 on E: ECasScriptSyntaxError do
593 begin
594 if Trim(S) = '' then
595 // special message in this case, to be friendly to humans
596 E.Message := 'Empty string is not a valid float value'
597 else
598 E.Message := 'Error when parsing constant float expression: ' + E.Message;
599 raise;
600 end;
601 end;
602
603 try
604 Result := (Expr.Execute as TCasScriptFloat).Value;
605 finally Expr.Free end;
606 end;
607
608 function ParseConstantIntExpression(const S: string): Int64;
609 var
610 Expr: TCasScriptExpression;
611 begin
612 try
613 Expr := ParseIntExpression(s, []);
614 except
615 on E: ECasScriptSyntaxError do
616 begin
617 if Trim(S) = '' then
618 // special message in this case, to be friendly to humans
619 E.Message := 'Empty string is not a valid integer value'
620 else
621 E.Message := 'Error when parsing constant integer expression: ' + E.Message;
622 raise;
623 end;
624 end;
625
626 try
627 Result := (Expr.Execute as TCasScriptInteger).Value;
628 finally Expr.Free end;
629 end;
630
631 { ParseProgram --------------------------------------------------------------- }
632
633 function ParseProgram(const S: string;
634 const Variables: TCasScriptValueList): TCasScriptProgram;
635 begin
636 Result := ParseProgram(S, Variables.ToArray);
637 end;
638
639 function ParseProgram(const S: string;
640 const Variables: array of TCasScriptValue): TCasScriptProgram;
641 var
642 Lexer: TCasScriptLexer;
643 I: Integer;
644 begin
645 for I := 0 to Length(Variables) - 1 do
646 Variables[I].OwnedByParentExpression := false;
647
648 Lexer := TCasScriptLexer.Create(s);
649 try
650 Result := nil;
651 try
652 try
653 Result := AProgram(Lexer, Variables);
654 Lexer.CheckTokenIs(tokEnd);
655 except
656 { Change ECasScriptFunctionArgumentsError (raised when
657 creating functions) to ECasScriptParserError.
658 This allows the caller to catch only ECasScriptSyntaxError,
659 and adds position information to error message. }
660 on E: ECasScriptFunctionArgumentsError do
661 raise ECasScriptParserError.Create(Lexer, E.Message);
662 end;
663 except Result.Free; raise end;
664 finally Lexer.Free end;
665 end;
666
667 end.