This file is indexed.

/usr/src/castle-game-engine-6.4/castlescript/castlescriptparser.pas is in castle-game-engine-src 6.4+dfsg1-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
{
  Copyright 2001-2017 Michalis Kamburelis.

  This file is part of "Castle Game Engine".

  "Castle Game Engine" is free software; see the file COPYING.txt,
  included in this distribution, for details about the copyright.

  "Castle Game Engine" is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

  ----------------------------------------------------------------------------
}

(*
  @abstract(Parser for CastleScript language, see
  [http://castle-engine.sourceforge.net/castle_script.php].)

  Can parse whole program in CastleScript language, is also prepared
  to parse only a single expression (usefull for cases when I need
  to input only a mathematical expression, like for glplotter function
  expression).
*)

unit CastleScriptParser;

{$I castleconf.inc}

interface

uses CastleScript, CastleScriptLexer, Math;

type
  { Error when parsing CastleScript expression. }
  ECasScriptSyntaxError = CastleScriptLexer.ECasScriptSyntaxError;

{ Parse a CastleScript expression that should be calculated to a float value.
  The easiest way to evaluate such expression
  is to call @link(TCasScriptExpression.AsFloat) method.

  This creates and returns an instance of TCasScriptExpression,
  that represents parsed tree of expression in S,
  casted to float.
  This parses a subset of CastleScript language, that allows you
  to define only one expression without any assignments.
  Also the end result is always casted to the float() type
  (just like it would be wrapped inside float() function call ---
  in fact this is exactly what happens.)

  The end result is that this is perfect for describing things
  like function expressions, ideal e.g. for
  [http://castle-engine.sourceforge.net/glplotter_and_gen_function.php].

  @param(Variables contains a list of named values you want
    to allow in this expression.

    Important: They will all have
    OwnedByParentExpression set to @false, and you will have to
    free them yourself.
    That's because given expression may use the same variable more than once
    (so freeing it twice would cause bugs), or not use it at all
    (so it will be automatically freed at all).

    So setting OwnedByParentExpression and freeing it yourself
    is the only sensible thing to do.)

  @raises(ECasScriptSyntaxError in case of error when parsing expression.) }
function ParseFloatExpression(const S: string;
  const Variables: array of TCasScriptValue): TCasScriptExpression;

{ Parse a CastleScript expression that should be calculated to a float value.
  The easiest way to evaluate such expression
  is to call @link(TCasScriptExpression.AsInt) method.

  See @link(ParseFloatExpression) for more details, this procedure is equivalent
  but it operates on floats. }
function ParseIntExpression(const S: string;
  const Variables: array of TCasScriptValue): TCasScriptExpression;

{ Parse a CastleScript expression that should be calculated to a string value.
  The easiest way to evaluate such expression
  is to call @link(TCasScriptExpression.AsString) method.

  See @link(ParseFloatExpression) for more details, this procedure is equivalent
  but it operates on strings. }
function ParseStringExpression(const S: string;
  const Variables: array of TCasScriptValue): TCasScriptExpression;

{ Parse a CastleScript expression that should be calculated to a boolean value.
  The easiest way to evaluate such expression
  is to call @link(TCasScriptExpression.AsBool) method.

  See @link(ParseFloatExpression) for more details, this procedure is equivalent
  but it operates on booleans. }
function ParseBoolExpression(const S: string;
  const Variables: array of TCasScriptValue): TCasScriptExpression;

{ Creates and returns instance of TCasScriptExpression,
  that represents parsed tree of expression in S.
  @param(Variables contains a list of named values you want
    to allow in this expression.
    See ParseFloatExpression for description.)
  @raises(ECasScriptSyntaxError in case of error when parsing expression.) }
function ParseExpression(const S: string;
  const Variables: array of TCasScriptValue): TCasScriptExpression;

{ Parse constant float expression.
  This can be used as a drop-in replacement for StrToFloat.
  Takes a string with any constant mathematical expression,
  according to CastleScript syntax, parses it and calculates.

  @raises(ECasScriptSyntaxError in case of error when parsing expression.) }
function ParseConstantFloatExpression(const S: string): Float;

{ Parse CastleScript program.

  Variable list works like for ParseFloatExpression, see there for
  description.

  @raises(ECasScriptSyntaxError in case of error when parsing expression.)

  @groupBegin }
function ParseProgram(const S: string;
  const Variables: array of TCasScriptValue): TCasScriptProgram; overload;
function ParseProgram(const S: string;
  const Variables: TCasScriptValueList): TCasScriptProgram; overload;
{ @groupEnd }

implementation

uses SysUtils, CastleScriptCoreFunctions;

function Expression(
  const Lexer: TCasScriptLexer;
  Environment: TCasScriptEnvironment;
  const Variables: array of TCasScriptValue): TCasScriptExpression; forward;

function NonAssignmentExpression(
  const Lexer: TCasScriptLexer;
  Environment: TCasScriptEnvironment;
  const AllowFullExpressionInFactor: boolean;
  const Variables: array of TCasScriptValue): TCasScriptExpression;

  function BinaryOper(tok: TToken): TCasScriptFunctionClass;
  begin
    case tok of
      tokPlus: Result := TCasScriptAdd;
      tokMinus: Result := TCasScriptSubtract;

      tokMultiply: Result := TCasScriptMultiply;
      tokDivide: Result := TCasScriptDivide;
      tokPower: Result := TCasScriptPower;
      tokModulo: Result := TCasScriptModulo;

      tokGreater: Result := TCasScriptGreater;
      tokLesser: Result := TCasScriptLesser;
      tokGreaterEqual: Result := TCasScriptGreaterEq;
      tokLesserEqual: Result := TCasScriptLesserEq;
      tokEqual: Result := TCasScriptEqual;
      tokNotEqual: Result := TCasScriptNotEqual;

      else raise ECasScriptParserError.Create(Lexer,
        'internal error : token not a binary operator');
    end
  end;

const
  SErrWrongFactor = 'wrong factor (expected identifier, constant, "-", "(" or function name)';

  FactorOperator = [tokMultiply, tokDivide, tokPower, tokModulo];
  TermOperator = [tokPlus, tokMinus];
  ComparisonOperator = [tokGreater, tokLesser, tokGreaterEqual, tokLesserEqual, tokEqual, tokNotEqual];

  function Operand: TCasScriptValue;
  var
    I: Integer;
  begin
    Lexer.CheckTokenIs(tokIdentifier);

    Result := nil;
    for I := 0 to Length(Variables) - 1 do
      if SameText(Variables[I].Name, Lexer.TokenString) then
      begin
        Result := Variables[I];
        Break;
      end;

    if Result = nil then
      raise ECasScriptParserError.CreateFmt(Lexer, 'Undefined identifier "%s"',
        [Lexer.TokenString]);

    Lexer.NextToken;
  end;

  { Returns either Expression or NonAssignmentExpression, depending on
    AllowFullExpressionInFactor value. }
  function ExpressionInsideFactor: TCasScriptExpression;
  begin
    if AllowFullExpressionInFactor then
      Result := Expression(Lexer, Environment, Variables) else
      Result := NonAssignmentExpression(Lexer, Environment,
        AllowFullExpressionInFactor, Variables);
  end;

  function Factor: TCasScriptExpression;
  var
    FC: TCasScriptFunctionClass;
    FParams: TCasScriptExpressionList;
  begin
    Result := nil;
    try
      case Lexer.Token of
        tokIdentifier: Result := Operand;
        tokInteger: begin
            Result := TCasScriptInteger.Create(false, Lexer.TokenInteger);
            Result.Environment := Environment;
            Lexer.NextToken;
          end;
        tokFloat: begin
            Result := TCasScriptFloat.Create(false, Lexer.TokenFloat);
            Result.Environment := Environment;
            Lexer.NextToken;
          end;
        tokBoolean: begin
            Result := TCasScriptBoolean.Create(false, Lexer.TokenBoolean);
            Result.Environment := Environment;
            Lexer.NextToken;
          end;
        tokString: begin
            Result := TCasScriptString.Create(false, Lexer.TokenString);
            Result.Environment := Environment;
            Lexer.NextToken;
          end;
        tokMinus: begin
            Lexer.NextToken;
            Result := TCasScriptNegate.Create([Factor()]);
            Result.Environment := Environment;
          end;
        tokLParen: begin
            Lexer.NextToken;
            Result := ExpressionInsideFactor;
            Lexer.CheckTokenIs(tokRParen);
            Lexer.NextToken;
          end;
        tokFuncName: begin
            FC := Lexer.TokenFunctionClass;
            Lexer.NextToken;
            FParams := TCasScriptExpressionList.Create(false);
            try
              try
                Lexer.CheckTokenIs(tokLParen);
                Lexer.NextToken;

                if Lexer.Token <> tokRParen then
                begin
                  repeat
                    FParams.Add(ExpressionInsideFactor);
                    if Lexer.Token = tokRParen then
                      Break;
                    Lexer.CheckTokenIs(tokComma);
                    Lexer.NextToken;
                  until false;
                end;

                Lexer.CheckTokenIs(tokRParen);
                Lexer.NextToken;
              except FParams.FreeContentsByParentExpression; raise; end;
              Result := FC.Create(FParams);
              Result.Environment := Environment;
            finally FParams.Free end;
          end;
        else raise ECasScriptParserError.Create(Lexer, SErrWrongFactor +
          ', but got "' + Lexer.TokenDescription + '"');
      end;
    except Result.FreeByParentExpression; raise end;
  end;

  function Term: TCasScriptExpression;
  var
    FC: TCasScriptFunctionClass;
  begin
    Result := nil;
    try
      Result := Factor;
      while Lexer.Token in FactorOperator do
      begin
        FC := BinaryOper(Lexer.Token);
        Lexer.NextToken;
        Result := FC.Create([Result, Factor]);
        Result.Environment := Environment;
      end;
    except Result.FreeByParentExpression; raise end;
  end;

  function ComparisonArgument: TCasScriptExpression;
  var
    FC: TCasScriptFunctionClass;
  begin
    Result := nil;
    try
      Result := Term;
      while Lexer.Token in TermOperator do
      begin
        FC := BinaryOper(Lexer.Token);
        Lexer.NextToken;
        Result := FC.Create([Result, Term]);
        Result.Environment := Environment;
      end;
    except Result.FreeByParentExpression; raise end;
  end;

var
  FC: TCasScriptFunctionClass;
begin
  Result := nil;
  try
    Result := ComparisonArgument;
    while Lexer.Token in ComparisonOperator do
    begin
      FC := BinaryOper(Lexer.Token);
      Lexer.NextToken;
      Result := FC.Create([Result, ComparisonArgument]);
      Result.Environment := Environment;
    end;
  except Result.FreeByParentExpression; raise end;
end;

function Expression(
  const Lexer: TCasScriptLexer;
  Environment: TCasScriptEnvironment;
  const Variables: TCasScriptValueList): TCasScriptExpression;
begin
  Result := Expression(Lexer, Environment, Variables.ToArray);
end;

function Expression(
  const Lexer: TCasScriptLexer;
  Environment: TCasScriptEnvironment;
  const Variables: array of TCasScriptValue): TCasScriptExpression;

  function PossiblyAssignmentExpression: TCasScriptExpression;
  { How to parse this?

    Straighforward approach is to try parsing
    Operand, then check is it followed by ":=".
    In case of parsing errors (we can catch them by ECasScriptParserError),
    or something else than ":=", we rollback and parse NonAssignmentExpression.

    The trouble with this approach: "rollback". This is uneasy,
    as you have to carefully remember all tokens eaten during
    Operand parsing, and unget them to lexer (or otherwise reparse them).

    Simpler and faster approach used: just always parse an
    NonAssignmentExpression. This uses the fact that Operand is
    also a valid NonAssignmentExpression, and NonAssignmentExpression
    will not eat anything after ":=" (following the grammar, ":="
    cannot occur within NonAssignmentExpression without parenthesis).
    After parsing NonAssignmentExpression, we can check for ":=". }
  var
    Operand, AssignedValue: TCasScriptExpression;
  begin
    Result := NonAssignmentExpression(Lexer, Environment, true, Variables);
    try
      if Lexer.Token = tokAssignment then
      begin
        Lexer.NextToken;

        AssignedValue := PossiblyAssignmentExpression();

        Operand := Result;
        { set Result to nil, in case of exception from TCasScriptAssignment
          constructor. }
        Result := nil;

        { TCasScriptAssignment in constructor checks that
          Operand is actually a simple writeable operand. }
        Result := TCasScriptAssignment.Create([Operand, AssignedValue]);
        Result.Environment := Environment;
      end;
    except Result.FreeByParentExpression; raise end;
  end;

var
  SequenceArgs: TCasScriptExpressionList;
begin
  Result := nil;
  try
    Result := PossiblyAssignmentExpression;

    if Lexer.Token = tokSemicolon then
    begin
      SequenceArgs := TCasScriptExpressionList.Create(false);
      try
        try
          SequenceArgs.Add(Result);
          Result := nil;

          while Lexer.Token = tokSemicolon do
          begin
            Lexer.NextToken;
            SequenceArgs.Add(PossiblyAssignmentExpression);
          end;
        except SequenceArgs.FreeContentsByParentExpression; raise end;

        Result := TCasScriptSequence.Create(SequenceArgs);
        Result.Environment := Environment;
      finally FreeAndNil(SequenceArgs) end;
    end;
  except Result.FreeByParentExpression; raise end;
end;

function AProgram(
  const Lexer: TCasScriptLexer;
  const GlobalVariables: array of TCasScriptValue): TCasScriptProgram;
var
  Environment: TCasScriptEnvironment;

  function AFunction: TCasScriptUserFunction;
  var
    BodyVariables: TCasScriptValueList;
    Parameter: TCasScriptValue;
  begin
    Result := TCasScriptUserFunction.Create;
    try
      Lexer.CheckTokenIs(tokIdentifier);
      Result.Name := Lexer.TokenString;
      Lexer.NextToken;

      BodyVariables := TCasScriptValueList.Create(false);
      try
        Lexer.CheckTokenIs(tokLParen);
        Lexer.NextToken;

        if Lexer.Token <> tokRParen then
        begin
          repeat
            Lexer.CheckTokenIs(tokIdentifier);
            Parameter := TCasScriptParameterValue.Create(true);
            Parameter.Environment := Environment;
            Parameter.Name := Lexer.TokenString;
            Parameter.OwnedByParentExpression := false;
            Result.Parameters.Add(Parameter);
            BodyVariables.Add(Parameter);
            Lexer.NextToken;

            if Lexer.Token = tokRParen then
              Break else
              begin
                Lexer.CheckTokenIs(tokComma);
                Lexer.NextToken;
              end;
          until false;
        end;

        Lexer.NextToken; { eat ")" }

        { We first added parameters, then added GlobalVariables,
          so when resolving, parameter names will hide global
          variable names, just like they should in normal language. }
        BodyVariables.AddRange(GlobalVariables);

        Result.Body := Expression(Lexer, Environment, BodyVariables);
      finally FreeAndNil(BodyVariables); end;
    except FreeAndNil(Result); raise end;
  end;

begin
  Result := TCasScriptProgram.Create;
  try
    Environment := Result.Environment;
    while Lexer.Token = tokFunctionKeyword do
    begin
      Lexer.NextToken;
      Result.Functions.Add(AFunction);
    end;
  except FreeAndNil(Result); raise end;
end;

{ ParseXxxExpression ------------------------------------------------------- }

function ParseSimpleExpression(const S: string;
  const Variables: array of TCasScriptValue): TCasScriptExpression;
var
  Lexer: TCasScriptLexer;
  I: Integer;
begin
  for I := 0 to Length(Variables) - 1 do
    Variables[I].OwnedByParentExpression := false;

  Lexer := TCasScriptLexer.Create(s);
  try
    Result := nil;
    try
      try
        Result := NonAssignmentExpression(Lexer, nil { no Environment }, false, Variables);
        Lexer.CheckTokenIs(tokEnd);
      except
        { Change ECasScriptFunctionArgumentsError (raised when
          creating functions) to ECasScriptParserError.
          This allows the caller to catch only ECasScriptSyntaxError,
          and adds position information to error message. }
        on E: ECasScriptFunctionArgumentsError do
          raise ECasScriptParserError.Create(Lexer, E.Message);
      end;
    except Result.FreeByParentExpression; raise end;
  finally Lexer.Free end;
end;

function ParseFloatExpression(const S: string;
  const Variables: array of TCasScriptValue): TCasScriptExpression;
begin
  Result := ParseSimpleExpression(S, Variables);
  { At the end, wrap Result in float() cast. }
  Result := TCasScriptFloatFun.Create([Result]);
end;

function ParseIntExpression(const S: string;
  const Variables: array of TCasScriptValue): TCasScriptExpression;
begin
  Result := ParseSimpleExpression(S, Variables);
  { At the end, wrap Result in int() cast. }
  Result := TCasScriptInt.Create([Result]);
end;

function ParseStringExpression(const S: string;
  const Variables: array of TCasScriptValue): TCasScriptExpression;
begin
  Result := ParseSimpleExpression(S, Variables);
  { At the end, wrap Result in string() cast. }
  Result := TCasScriptStringFun.Create([Result]);
end;

function ParseBoolExpression(const S: string;
  const Variables: array of TCasScriptValue): TCasScriptExpression;
begin
  Result := ParseSimpleExpression(S, Variables);
  { At the end, wrap Result in bool() cast. }
  Result := TCasScriptBool.Create([Result]);
end;

function ParseExpression(const S: string;
  const Variables: array of TCasScriptValue): TCasScriptExpression;
var
  Lexer: TCasScriptLexer;
  I: Integer;
begin
  for I := 0 to Length(Variables) - 1 do
    Variables[I].OwnedByParentExpression := false;

  Lexer := TCasScriptLexer.Create(s);
  try
    Result := nil;
    try
      try
        Result := Expression(Lexer, nil { no Environment }, Variables);
        Lexer.CheckTokenIs(tokEnd);
      except
        { Change ECasScriptFunctionArgumentsError (raised when
          creating functions) to ECasScriptParserError.
          This allows the caller to catch only ECasScriptSyntaxError,
          and adds position information to error message. }
        on E: ECasScriptFunctionArgumentsError do
          raise ECasScriptParserError.Create(Lexer, E.Message);
      end;
    except Result.FreeByParentExpression; raise end;
  finally Lexer.Free end;
end;

{ ParseConstantFloatExpression ----------------------------------------------- }

function ParseConstantFloatExpression(const S: string): Float;
var
  Expr: TCasScriptExpression;
begin
  try
    Expr := ParseFloatExpression(s, []);
  except
    on E: ECasScriptSyntaxError do
    begin
      E.Message := 'Error when parsing constant expression: ' + E.Message;
      raise;
    end;
  end;

  try
    Result := (Expr.Execute as TCasScriptFloat).Value;
  finally Expr.Free end;
end;

{ ParseProgram --------------------------------------------------------------- }

function ParseProgram(const S: string;
  const Variables: TCasScriptValueList): TCasScriptProgram;
begin
  Result := ParseProgram(S, Variables.ToArray);
end;

function ParseProgram(const S: string;
  const Variables: array of TCasScriptValue): TCasScriptProgram;
var
  Lexer: TCasScriptLexer;
  I: Integer;
begin
  for I := 0 to Length(Variables) - 1 do
    Variables[I].OwnedByParentExpression := false;

  Lexer := TCasScriptLexer.Create(s);
  try
    Result := nil;
    try
      try
        Result := AProgram(Lexer, Variables);
        Lexer.CheckTokenIs(tokEnd);
      except
        { Change ECasScriptFunctionArgumentsError (raised when
          creating functions) to ECasScriptParserError.
          This allows the caller to catch only ECasScriptSyntaxError,
          and adds position information to error message. }
        on E: ECasScriptFunctionArgumentsError do
          raise ECasScriptParserError.Create(Lexer, E.Message);
      end;
    except Result.Free; raise end;
  finally Lexer.Free end;
end;

end.