-
Notifications
You must be signed in to change notification settings - Fork 79
/
ScriptParser.py
1681 lines (1525 loc) · 65 KB
/
ScriptParser.py
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# GPL License and Copyright Notice ============================================
# This file is part of Wrye Bash.
#
# Wrye Bash is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3
# of the License, or (at your option) any later version.
#
# Wrye Bash 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. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Wrye Bash. If not, see <https://www.gnu.org/licenses/>.
#
# Wrye Bash copyright (C) 2005-2009 Wrye, 2010-2024 Wrye Bash Team
# https://github.com/wrye-bash
#
# =============================================================================
from __future__ import annotations
# Parser.py =======================================
# A generic class for handling parsing of
# scripts and equations.
# - The following operators are supported by default:
# + Addition
# - Subtraction
# * Multiplication
# / Division
# % Modulus
# ^ Exponent
# () Parenthesis
# - The parser follows the order of operations
# - Variables are also handled, all are treated
# as float's. The variable is initialized
# on its first appearance to '0.0'. Multiple
# assignment is allowed, but only the default
# assignment operator is defined by default
# - Constants can be defined
# - Keywords can be defined
# - Functions can be defined
#
# Defined functions to use are:
# SetOperator
# SetKeyword
# SetFunction
# SetConstant
# SetVariable
# PushFlow
# PopFlow
# PeekFlow
# LenFlow
# PurgeFlow
# RunLine
# error
# ExecuteTokens
# TokensToRPN
# ExecuteRPN
#==================================================
import operator
import os
from collections import defaultdict
from string import digits, whitespace
from . import bolt # no other Bash imports!
from .bolt import FName
#--------------------------------------------------
name_start = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_'
name_chars = f'{name_start}0123456789'
# validName ---------------------------------------
# Test if a string can be used as a valid name
#--------------------------------------------------
def validName(string):
try:
if string[0] not in name_start: return False
for i in string:
if i not in name_chars: return False
return True
except (TypeError, KeyError): # TypeError means not iterable
return False
# validNumber -------------------------------------
# Test if a string can be used as a valid number
#--------------------------------------------------
def validNumber(string):
try:
float(string)
if string == '.': return False
return True
except ValueError:
return False
# Define Some Constants ---------------------------
# Some error string
def _err_too_few_args(obj_type, obj_name, got, expected):
error(_("Too few arguments to %(obj_type)s '%(obj_name)s': got %(got)s, "
"expected %(expected)s.") % {'obj_type': obj_type,
'obj_name': obj_name, 'got': got,
'expected': expected})
def _err_too_many_args(obj_type, obj_name, got, expected):
error(_("Too many arguments to %(obj_type)s '%(obj_name)s': got %(got)s, "
"expected %(expected)s.") % {'obj_type': obj_type,
'obj_name': obj_name, 'got': got,
'expected': expected})
def _err_cant_set(obj_type, obj_name, type_enum):
error(_("Cannot set %(obj_type)s '%(obj_name)s': type is "
"'%(conflicting_type)s'.") % {
'obj_type': obj_type, 'obj_name': obj_name,
'conflicting_type': Types[type_enum]})
def _err_unexpected(unexp_keyword):
error(_("Unexpected '%(unexpected_keyword)s'.") % {
'unexpected_keyword': unexp_keyword})
def _err_only_strings(function_name):
error(_("Function '%(string_only_function)s' only operates on string "
"types.") % {'string_only_function': function_name})
class KEY(object):
# Constants for keyword args
NO_MAX = -1 # No maximum arguments
NA = 0 # Not a variable argument keyword
class OP(object):
# Constants for operator precedences
PAR = 0 # Parenthesis
EXP = 1 # Exponent
UNA = 2 # Unary (++, --)
MUL = 3 # Multiplication (*, /, %)
ADD = 4 # Addition (+, -)
CO1 = 5 # Comparison (>=,<=,>,<)
CO2 = 6 # Comparison (!=, ==)
MEM = 7 # Membership test (a in b)
NOT = 8 # Logical not (not, !)
AND = 9 # Logical and (and, &)
OR = 10 # Logical or (or, |)
ASS = 11 # Assignment (=,+=,etc
# Constants for operator associations
LEFT = 0
RIGHT = 1
# Constants for the type of a token
UNKNOWN = 0
NAME = 1 # Can be a name token, but not used yet
CONSTANT = 2
VARIABLE = 3
FUNCTION = 4
KEYWORD = 5
OPERATOR = 6
INTEGER = 7
DECIMAL = 8
OPEN_PARENS = 9
CLOSE_PARENS = 10
COMMA = 11
WHITESPACE = 12
STRING = 13
OPEN_BRACKET = 14
CLOSE_BRACKET = 15
COLON = 16
Types = {UNKNOWN:u'UNKNOWN',
NAME:u'NAME',
CONSTANT:u'CONSTANT',
VARIABLE:u'VARIABLE',
FUNCTION:u'FUNCTION',
KEYWORD:u'KEYWORD',
OPERATOR:u'OPERATOR',
INTEGER:u'INTEGER',
DECIMAL:u'DECIMAL',
OPEN_PARENS:u'OPEN_PARENS',
CLOSE_PARENS:u'CLOSE_PARENS',
COMMA:u'COMMA',
WHITESPACE:u'WHITESPACE',
STRING:u'STRING',
OPEN_BRACKET:u'OPEN_BRACKET',
CLOSE_BRACKET:u'CLOSE_BRACKET',
COLON:u'COLON',
}
# FlowControl -------------------------------------
# Flow control object, to hold info about a flow
# control statement
#--------------------------------------------------
class FlowControl(object):
def __init__(self, statement_type, active, keywords=[], **attribs):
self.type = statement_type
self.active = active
self.keywords = keywords
for i in attribs:
setattr(self, i, attribs[i])
# Token -------------------------------------------
# Token object, to hold info about a token
#--------------------------------------------------
# ParserError -------------------------------------
# So when we catch exceptions we know if it's a
# problem with the parser, or a problem with the
# script
#--------------------------------------------------
##: Refactor to use exception.ParserError instead?
class ParserError(SyntaxError): pass
gParser: Parser | None = None
def error(msg):
if gParser:
raise ParserError(
f'(Line {gParser.cLine}, Column {gParser.cCol}): {msg}')
else:
raise ParserError(msg)
# Parser ------------------------------------------
# This is where the magic happens
#--------------------------------------------------
def _get_type_basic(token_or_num):
"""Determines a token's type without considering a parser's type system."""
if isinstance(token_or_num, str): return STRING
if isinstance(token_or_num, int): return INTEGER
if isinstance(token_or_num, float): return DECIMAL
return UNKNOWN
class Parser(object):
def getType(self, token_or_num):
"""Determine a token's type in self's type system."""
if isinstance(token_or_num, str): ##: use a dict here?
if token_or_num in self.constants: return CONSTANT
if token_or_num in self.variables: return VARIABLE
if token_or_num in self.keywords : return KEYWORD
if token_or_num in self.functions: return FUNCTION
if token_or_num in self.operators: return OPERATOR
if token_or_num == u'(': return OPEN_PARENS
if token_or_num == u')': return CLOSE_PARENS
if token_or_num == u'[': return OPEN_BRACKET
if token_or_num == u']': return CLOSE_BRACKET
if token_or_num == u':': return COLON
if token_or_num == u',': return COMMA
if validName(token_or_num): return NAME
if validNumber(token_or_num):
if u'.' in token_or_num: return DECIMAL
return INTEGER
for i in token_or_num:
if i not in whitespace: return UNKNOWN
return WHITESPACE
return _get_type_basic(token_or_num)
class Callable:
def __init__(self, callable_name, function, min_args=0,
max_args=KEY.NA, passTokens=False, passCommas=False):
self.callable_name = callable_name
self.function = function
self.passTokens = passTokens
self.passCommas = passCommas
if max_args == KEY.NA: max_args = min_args
if min_args > max_args >= 0: max_args = min_args
self.minArgs = min_args
self.maxArgs = max_args
@property
def Type(self): return self.__class__.__name__
def __call__(self, *args):
# Remove commas if necessary, pass values if necessary
if not self.passCommas or not self.passTokens:
args = [(x.tkn,x)[self.passTokens] for x in args if x.type != COMMA or self.passCommas]
return self.execute(*args)
def execute(self, *args):
# Ensure correct number of arguments
numArgs = len(args)
if self.maxArgs != KEY.NO_MAX and numArgs > self.maxArgs:
if self.minArgs == self.maxArgs:
_err_too_many_args(self.Type, self.callable_name, numArgs,
self.minArgs)
else:
_err_too_many_args(self.Type, self.callable_name, numArgs,
f'min: {self.minArgs}, max: {self.maxArgs}')
if numArgs < self.minArgs:
args = self.Type, self.callable_name, numArgs
if self.maxArgs == KEY.NO_MAX:
_err_too_few_args(*args, f'>= {self.minArgs}')
elif self.minArgs == self.maxArgs:
_err_too_few_args(*args, self.minArgs)
else:
_err_too_few_args(*args,
f'>= {self.minArgs} && <= {self.maxArgs}')
return self.function(*args)
class Operator(Callable):
def __init__(self, operator_name, function, precedence,
association=LEFT, passTokens=True):
self.precedence = precedence
self.association = association
if self.precedence in (OP.UNA, OP.NOT):
min_args = 1
else:
min_args = 2
super().__init__(operator_name, function, min_args,
passTokens=passTokens)
class Keyword(Callable):
def __init__(self, keyword_name, function, min_args=0, max_args=KEY.NA,
passTokens=False, splitCommas=True, passCommas=False):
self.splitCommas = splitCommas
super().__init__(keyword_name, function, min_args, max_args,
passTokens, passCommas)
def __call__(self, *args):
gParser.StripOuterParens(args)
if not self.splitCommas:
return super().__call__(*args)
args = gParser.SplitAtCommas(args)
if not self.passTokens:
if len(args) == 1:
if len(args[0]) > 0:
args = [gParser.ExecuteTokens(args[0])]
else:
args = []
else:
for i,arg in enumerate(args):
if len(arg) > 0:
args[i] = gParser.ExecuteTokens(arg)
else:
args[i] = None
return self.execute(*args)
class Function(Callable):
def __init__(self, function_name, function, min_args=0,
max_args=KEY.NA, passTokens=False, dotFunction=False):
"""function: function that will be called with the args
num_args: number of args required for the function
passTokens: whether tokens or the data within should be passed as args
dotFunction: whether this function can be called using the dot operator
"""
super().__init__(function_name, function, min_args, max_args,
passTokens)
self.dotFunction = dotFunction
class Token(object):
def __init__(self, token_or_text, Type=None, parser=None, line=None,
pos=(None, None)):
if isinstance(token_or_text, Parser.Token):
self.text = token_or_text.text
self.type = token_or_text.type
self.parser = token_or_text.parser
self.line = token_or_text.line
self.pos = token_or_text.pos
self.numArgs = token_or_text.numArgs
else:
self.text = token_or_text
if Type:
# We were passed a type, so use that
self.type = Type
elif parser:
# We have a parser, so we can query for reliable type info
self.type = parser.getType(token_or_text)
else:
# We do not have a parser, so we can only query for basic
# type info
self.type = _get_type_basic(token_or_text)
self.parser = parser
self.line = line
self.pos = pos
self.numArgs = 0
def GetData(self):
""":rtype: Parser.Function | Parser.Keyword | Parser.Operator |
str | int | float
"""
if self.parser:
if self.type == FUNCTION: return self.parser.functions[self.text]
if self.type == KEYWORD : return self.parser.keywords[self.text]
if self.type == OPERATOR: return self.parser.operators[self.text]
if self.type == VARIABLE: return self.parser.variables[self.text]
if self.type == CONSTANT: return self.parser.constants[self.text]
if self.type == DECIMAL : return float(self.text)
if self.type == INTEGER : return int(self.text)
return self.text
tkn = property(GetData) # did I catch all uses ?
# Implement rich comparisons, __cmp__ is deprecated
def __eq__(self, other):
if isinstance(other, Parser.Token):
return self.tkn == other.tkn
return self.tkn == other
def __ne__(self, other):
if isinstance(other, Parser.Token):
return self.tkn != other.tkn
return self.tkn != other
def __lt__(self, other):
if isinstance(other, Parser.Token):
return self.tkn < other.tkn
return self.tkn < other
def __le__(self, other):
if isinstance(other, Parser.Token):
return self.tkn <= other.tkn
return self.tkn <= other
def __gt__(self, other):
if isinstance(other, Parser.Token):
return self.tkn > other.tkn
return self.tkn > other
def __ge__(self, other):
if isinstance(other, Parser.Token):
return self.tkn >= other.tkn
return self.tkn >= other
def __add__(self, other): return Parser.Token(self.tkn + other.tkn)
def __sub__(self, other): return Parser.Token(self.tkn - other.tkn)
def __mul__(self, other): return Parser.Token(self.tkn * other.tkn)
def __mod__(self, other): return Parser.Token(self.tkn % other.tkn)
def __truediv__(self, other): return Parser.Token(self.tkn / other.tkn)
def __floordiv__(self, other): return Parser.Token(self.tkn // other.tkn)
def __divmod__(self, other): return Parser.Token(divmod(self.tkn, other.tkn))
def __pow__(self, other): return Parser.Token(self.tkn ** other.tkn)
def __lshift__(self, other): return Parser.Token(self.tkn << other.tkn)
def __rshift__(self, other): return Parser.Token(self.tkn >> other.tkn)
def __and__(self, other): return Parser.Token(self.tkn & other.tkn)
def __xor__(self, other): return Parser.Token(self.tkn ^ other.tkn)
def __or__(self, other): return Parser.Token(self.tkn | other.tkn)
def __bool__(self): return bool(self.tkn)
def __neg__(self): return Parser.Token(-self.tkn)
def __pos__(self): return Parser.Token(+self.tkn)
def __abs__(self): return abs(self.tkn)
def __int__(self): return int(self.tkn)
def __index__(self): return operator.index(self.tkn)
def __float__(self): return float(self.tkn)
def __str__(self): return str(self.tkn)
def __repr__(self): return f'<Token-{Types[self.type]}:{self.text}>'
# Fall through to function/keyword
def __call__(self, *args, **kwdargs): return self.tkn(*args, **kwdargs)
# Now for the Parser class
def __init__(self,
doImplicit=u'*',
dotOperator=u'.',
comment=u';',
constants={u'True':True,u'False':False},
variables=None
):
self.doImplicit = doImplicit
self.dotOperator = dotOperator
self.comment = comment
self.runon = False
self.cLineStart = 0
self.cCol = 0
self.cLine = 0
self.tokens = []
self.Flow = []
self.opChars = u''
self.operators = {}
self.keywords = {}
self.functions = {}
self.constants = constants or {}
self.variables = variables or {}
self.escapes = {u'n':u'\n',
u't':u'\t'
}
self.word = None
self.wordStart = None
if dotOperator:
self.SetOperator(dotOperator, self.opDotOperator, OP.PAR)
# Special function
self.functions[u']index['] = Parser.Function(u'<index>', self.fnIndex,
2, 4)
global gParser
gParser = self
# Dummy function for the dot operator
def opDotOperator(self, l, r): pass
# Indexing operator function
_marker = object()
def fnIndex(self, item, start, stop=None, step=None):
try:
fn = u'item['
# Start
if start is not Parser._marker:
fn += u'%i'% start
elif stop is None:
fn += u':'
# Stop
if stop is Parser._marker:
fn += u':'
elif stop is not None:
fn += u':%i' % stop
# Step
if step is Parser._marker:
fn += u':'
elif step is not None:
fn += u':%i' % step
fn += u']'
return eval(fn)
except:
error(_(u'Index out of bounds.'))
def SetOperator(self, op_name, *args, **kwdargs):
type_ = self.getType(op_name)
if type_ not in [NAME,OPERATOR,UNKNOWN]:
_err_cant_set(u'operator', op_name, type_)
self.operators[op_name] = Parser.Operator(op_name, *args, **kwdargs)
for i in op_name:
if i not in self.opChars: self.opChars += i
def SetKeyword(self, keywrd_name, *args, **kwdargs):
type_ = self.getType(keywrd_name)
if type_ not in [NAME,KEYWORD]:
_err_cant_set(u'keyword', keywrd_name, type_)
self.keywords[keywrd_name] = Parser.Keyword(keywrd_name, *args, **kwdargs)
def SetFunction(self, fun_name, *args, **kwdargs):
type_ = self.getType(fun_name)
if type_ not in [NAME,FUNCTION]:
_err_cant_set(u'function', fun_name, type_)
self.functions[fun_name] = Parser.Function(fun_name, *args, **kwdargs)
def SetConstant(self, const_name, value):
type_ = self.getType(const_name)
if type_ not in [NAME,CONSTANT]:
_err_cant_set(u'constant', const_name, type_)
self.constants[const_name] = value
def SetVariable(self, var_name, value):
type_ = self.getType(var_name)
if type_ not in [NAME, VARIABLE]:
_err_cant_set(u'variable', var_name, type_)
self.variables[var_name] = value
# Flow control stack
def PushFlow(self, stmnt_type, active, keywords, **attribs):
self.Flow.append(FlowControl(stmnt_type, active, keywords, **attribs))
def PopFlow(self): return self.Flow.pop()
def PopFrontFlow(self): return self.Flow.pop(0)
def PeekFlow(self,index=-1): return self.Flow[index]
def LenFlow(self): return len(self.Flow)
def PurgeFlow(self): self.Flow = []
# Run a line of code: returns True if more lines are needed to make a complete line, False if not
def RunLine(self, line):
# First reset tokens if we're starting a new line
if not self.runon:
self.cLineStart = self.cLine
self.tokens = []
# Now parse the tokens
self.cLine += 1
self.TokenizeLine(line)
if self.runon: return True
# No tokens?
if len(self.tokens) == 0: return False
# See if we're in currently within a flow control construct
if self.LenFlow() > 0:
i = self.PeekFlow()
if not i.active and self.tokens[0].text not in i.keywords:
return False
# If we have a keyword, just run it
if self.tokens[0].type == KEYWORD:
kwrd = self.tokens.pop(0)
kwrd(*self.tokens)
# It's just an expression, didnt start with a keyword
else:
# Convert to reverse-polish notation and execute
self.ExecuteTokens()
return False
# Removes any commas from a list of tokens
def SkipCommas(self, tokens=None):
if tokens is None:
self.tokens = [x for x in self.tokens if x.type != COMMA]
return self.tokens
tokens = [x for x in tokens if x.type != COMMA]
return tokens
# Split tokens at commas
def SplitAtCommas(self, tokens=None):
tokens = tokens or self.tokens
parenDepth = 0
bracketDepth = 0
result = [[]]
for tok in tokens:
if tok.type == OPEN_PARENS:
parenDepth += 1
elif tok.type == CLOSE_PARENS:
parenDepth -= 1
if parenDepth < 0:
error(_(u'Mismatched parenthesis.'))
elif tok.type == OPEN_BRACKET:
bracketDepth += 1
elif tok.type == CLOSE_BRACKET:
bracketDepth -= 1
if bracketDepth < 0:
error(_(u'Mismatched brackets.'))
if tok.type == COMMA and parenDepth == 0 and bracketDepth == 0:
result.append([])
else:
result[-1].append(tok)
return result
def StripOuterParens(self, tokens=None):
tokens = tokens or self.tokens
while len(tokens) > 2 and tokens[0].type == OPEN_PARENS and tokens[-1].type == CLOSE_PARENS:
tokens = tokens[1:-1]
return tokens
# Split a string into tokens
def TokenizeLine(self, line):
self.word = None
self.wordStart = None
self.cCol = 0
self.runon = False
state = self._stateSpace
for i in line:
state = state(i)
if not state: return None
self.cCol += 1
self._emit()
return self.tokens
# Run a list of tokens
def ExecuteTokens(self, tokens=None):
tokens = tokens or self.tokens
self.TokensToRPN(list(tokens))
return self.ExecuteRPN()
# Convert a list of tokens to rpn
def TokensToRPN(self, tokens=None):
tokens = tokens or self.tokens
rpn = []
stack = []
# Add an item to the rpn, and increase arg count for
# the last parens
def rpnAppend(item):
for i in reversed(stack):
if i.type in [OPEN_PARENS,OPEN_BRACKET]:
i.numArgs = 1
break
rpn.append(item)
# Now the rest of it
for idex,i in enumerate(tokens):
if i.type in [INTEGER,DECIMAL,CONSTANT,VARIABLE,NAME,STRING]:
rpnAppend(i)
elif i.type == COMMA:
while len(stack) > 0 and stack[-1].type != OPEN_PARENS:
rpn.append(stack.pop())
if len(stack) == 0:
error(_("Misplaced ',' or missing parenthesis."))
if len(stack) > 1 and stack[-2].type == FUNCTION:
stack[-2].numArgs += stack[-1].numArgs
stack[-1].numArgs = 0
elif i.type == COLON:
temp_tokens = []
while len(stack) > 0 and stack[-1].type != OPEN_BRACKET:
temp_tokens.append(stack.pop())
if len(stack) <= 1:
error(_("Misplaced ':' or missing bracket."))
stack[-2].numArgs += stack[-1].numArgs
if len(temp_tokens) == 0 and stack[-1].numArgs == 0:
rpn.append(Parser.Token(Parser._marker,Type=UNKNOWN,parser=self))
stack[-2].numArgs += 1
else:
rpn.extend(temp_tokens)
stack[-1].numArgs = 0
elif i.type == FUNCTION:
stack.append(i)
elif i.type == OPERATOR:
# Dot operator
if i.text == self.dotOperator:
if idex + 1 >= len(tokens):
error(_('Dot operator: no function to call.'))
next_token = tokens[idex + 1]
if next_token.type != FUNCTION:
error(_("Dot operator: cannot access non-function "
"'%(other_token)s'.") % {
'other_token': next_token.text})
if not next_token.tkn.dotFunction:
error(_("Dot operator: cannot access function "
"'%(non_dot_function)s'.") % {
'non_dot_function': next_token.text})
next_token.numArgs += 1
# Other operators
else:
while len(stack) > 0 and stack[-1].type == OPERATOR:
if i.tkn.association == LEFT and i.tkn.precedence >= stack[-1].tkn.precedence:
rpn.append(stack.pop())
elif i.tkn.association == RIGHT and i.tkn.precedence > stack[-1].tkn.precedence:
rpn.append(stack.pop())
else:
break
if i.text == '-':
# Special unary minus type
if idex == 0 or tokens[idex-1].type in [OPEN_BRACKET,OPEN_PARENS,COMMA,COLON,OPERATOR,KEYWORD]:
rpnAppend(Parser.Token('0', parser=self))
stack.append(i)
elif i.type == OPEN_PARENS:
stack.append(i)
elif i.type == OPEN_BRACKET:
stack.append(Parser.Token(']index[', parser=self))
stack.append(i)
elif i.type == CLOSE_PARENS:
while len(stack) > 0 and stack[-1].type != OPEN_PARENS:
rpn.append(stack.pop())
if len(stack) == 0:
error(_('Unmatched parenthesis.'))
numArgs = stack[-1].numArgs
stack.pop()
if len(stack) > 0 and stack[-1].type == FUNCTION:
stack[-1].numArgs += numArgs
rpn.append(stack.pop())
elif i.type == CLOSE_BRACKET:
temp_tokens = []
while len(stack) > 0 and stack[-1].type != OPEN_BRACKET:
temp_tokens.append(stack.pop())
if len(stack) == 0:
error(_('Unmatched brackets.'))
numArgs = stack[-1].numArgs
stack.pop()
if len(temp_tokens) == 0 and numArgs == 0 and stack[-1].numArgs != 0:
rpn.append(Parser.Token(Parser._marker,Type=UNKNOWN,parser=self))
numArgs += 1
rpn.extend(temp_tokens)
stack[-1].numArgs += numArgs + 1
if stack[-1].numArgs == 1:
error(_('Index out of bounds.'))
rpn.append(stack.pop())
else:
error(_("Unrecognized token: '%(unknown_token_text)s', type: "
"%(unknown_token_type)s") % {
'unknown_token_text': i.text,
'unknown_token_type': Types[i.type]})
while len(stack) > 0:
i = stack.pop()
if i.type in [OPEN_PARENS,CLOSE_PARENS]:
error(_('Unmatched parenthesis.'))
rpn.append(i)
self.rpn = rpn
return rpn
def ExecuteRPN(self, rpn=None):
rpn = rpn or self.rpn
stack = []
for i in rpn:
if i.type == OPERATOR:
if len(stack) < (tkn_min_args := i.tkn.minArgs):
_err_too_few_args('operator', i.text, len(stack),
tkn_min_args)
args = []
while len(args) < tkn_min_args:
args.append(stack.pop())
args.reverse()
res = i(*args)
if isinstance(res, list):
stack.extend([Parser.Token(x) for x in res])
else:
stack.append(Parser.Token(res))
elif i.type == FUNCTION:
if len(stack) < i.numArgs:
_err_too_few_args('function', i.text, len(stack),
i.numArgs)
args = []
while len(args) < i.numArgs:
args.append(stack.pop())
args.reverse()
res = i(*args)
if isinstance(res, list):
stack.extend([Parser.Token(x) for x in res])
else:
stack.append(Parser.Token(res))
else:
stack.append(i)
if len(stack) == 1:
return stack[0].tkn
error(_(u'Too many values left at the end of evaluation.'))
def error(self, msg):
raise ParserError(f'(Line {self.cLine}, Column {self.cCol}): {msg}')
#Functions for parsing a line into tokens
def _grow(self, c):
if self.word: self.word += c
else:
self.word = c
self.wordStart = self.cCol
def _emit(self, word=None, type_=None):
word = word or self.word
if word is None: return
if self.wordStart is None: self.wordStart = self.cCol - 1
type_ = type_ or self.getType(word)
# Try to figure out if it's multiple operators bunched together
rightWord = None
if type_ == UNKNOWN:
for idex in range(len(word),0,-1):
newType = self.getType(word[0:idex])
if newType != UNKNOWN:
rightWord = word[idex:]
rightWordStart = self.wordStart + idex
word = word[0:idex]
break
# Implicit multiplication
if self.doImplicit:
if len(self.tokens) > 0:
left = self.tokens[-1].type
if left in [CLOSE_PARENS,CLOSE_BRACKET]:
if type_ in [OPEN_PARENS, DECIMAL, INTEGER, FUNCTION, VARIABLE, CONSTANT, NAME]:
self.tokens.append(Parser.Token(self.doImplicit,OPERATOR,self,self.cLine))
elif left in [DECIMAL,INTEGER]:
if type_ in [OPEN_PARENS, FUNCTION, VARIABLE, CONSTANT, NAME]:
self.tokens.append(Parser.Token(self.doImplicit,OPERATOR,self,self.cLine))
elif left in [VARIABLE, CONSTANT, NAME]:
if type_ == OPEN_PARENS:
self.tokens.append(Parser.Token(self.doImplicit,OPERATOR,self,self.cLine))
self.tokens.append(Parser.Token(word, type_, self, self.cLine, (self.wordStart, self.cCol)))
self.word = None
self.wordStart = None
if rightWord is not None:
state = self._stateSpace
self.cCol = rightWordStart
for i in rightWord:
state = state(i)
if not state: return
self.cCol += 1
def _stateSpace(self, c):
self._emit()
if c in whitespace: return self._stateSpace
if c == "'": return self._stateSQuote
if c == '"': return self._stateDQuote
if c == '\\': return self._stateEscape
if c == self.comment: return self._stateComment
self._grow(c)
if c in name_start: return self._stateName
if c in self.opChars: return self._stateOperator
if c in digits: return self._stateNumber
if c == '.': return self._stateDecimal
if c == '(': return self._stateSpace
if c == '[': return self._stateSpace
if c == ')': return self._stateEndBracket
if c == ']': return self._stateEndBracket
if c == ',': return self._stateSpace
error(_("Invalid character: '%(invalid_char)s'") % {'invalid_char': c})
def _stateSQuote(self, c):
if c == u'\\': return self._stateSQuoteEscape
if c == u"'":
if not self.word: self.word = u''
self._emit(type_=STRING)
return self._stateSpace
if c == u'\n':
error(_(u'Unterminated single quote.'))
self._grow(c)
return self._stateSQuote
def _stateSQuoteEscape(self, c):
if c in self.escapes: self._grow(self.escapes[c])
else: self._grow(c)
return self._stateSQuote
def _stateDQuote(self, c):
if c == u'\\': return self._stateDQuoteEscape
if c == u'"':
if not self.word: self.word = u''
self._emit(type_=STRING)
return self._stateSpace
if c == u'\n':
error(_(u'Unterminated double quote.'))
self._grow(c)
return self._stateDQuote
def _stateDQuoteEscape(self, c):
if c in self.escapes: self._grow(self.escapes[c])
else: self._grow(c)
return self._stateDQuote
def _stateEscape(self, c):
if c == u'\n':
self.runon = True
return
return self._stateSpace(c)
def _stateComment(self, c): return self._stateComment
def _stateName(self, c):
if c in name_chars:
self._grow(c)
return self._stateName
if c in ("'", '"'):
error(_('Unexpected quotation mark (%(wrong_mark)s) following '
'name token.') % {'wrong_mark': c})
if c == ':' and self.word.endswith('in'):
self._grow(c)
return self._stateOperator
return self._stateSpace(c)
def _stateOperator(self, c):
if c in self.opChars:
self._grow(c)
return self._stateOperator
return self._stateSpace(c)
def _stateNumber(self, c):
if c in digits:
self._grow(c)
return self._stateNumber
if c == '.':
self._grow(c)
return self._stateDecimal
if c in ('"', "'"):
error(_('Unexpected quotation mark (%(wrong_mark)s) following '
'number token.') % {'wrong_mark': c})
return self._stateSpace(c)
def _stateDecimal(self, c):
if c in digits:
self._grow(c)
return self._stateDecimal
if c in ('"', "'", '.'):
error(_('Unexpected symbol (%(wrong_symbol)s) following decimal '
'token.') % {'wrong_symbol': c})
return self._stateSpace(c)
def _stateEndBracket(self, c):
if c in ('"', "'"):
error(_('Unexpected quotation mark (%(wrong_mark)s) following '
'parenthesis.') % {'wrong_mark': c})
return self._stateSpace(c)
class PreParser(Parser):
def __init__(self):
super().__init__()
#--Constants
self.SetConstant('SubPackages', 'SubPackages')
#--Operators
#Assignment
self.SetOperator('=' , self.Ass, OP.ASS, RIGHT)
self.SetOperator('+=', self.AssAdd, OP.ASS, RIGHT)
self.SetOperator('-=', self.AssMin, OP.ASS, RIGHT)
self.SetOperator('*=', self.AssMul, OP.ASS, RIGHT)
self.SetOperator('/=', self.AssDiv, OP.ASS, RIGHT)
self.SetOperator('%=', self.AssMod, OP.ASS, RIGHT)
self.SetOperator('^=', self.AssExp, OP.ASS, RIGHT)
#Comparison
self.SetOperator('==', self.opE, OP.CO2)
self.SetOperator('!=', self.opNE, OP.CO2)
self.SetOperator('>=', self.opGE, OP.CO1)
self.SetOperator('>' , self.opG, OP.CO1)
self.SetOperator('<=', self.opLE, OP.CO1)
self.SetOperator('<' , self.opL, OP.CO1)
self.SetOperator('==:', self.opEc, OP.CO2, passTokens=False) # Case insensitive ==
self.SetOperator('!=:', self.opNEc, OP.CO2, passTokens=False) # Case insensitive !=
self.SetOperator('>=:', self.opGEc, OP.CO1, passTokens=False) # Case insensitive >=
self.SetOperator('>:', self.opGc, OP.CO1, passTokens=False) # Case insensitive >
self.SetOperator('<=:', self.opLEc, OP.CO1, passTokens=False) # Case insensitive <=
self.SetOperator('<:', self.opLc, OP.CO1, passTokens=False) # Case insensitive <
#Membership operators
self.SetOperator('in', self.opIn, OP.MEM, passTokens=False)
self.SetOperator('in:', self.opInCase, OP.MEM, passTokens=False) # Case insensitive in
#Boolean
self.SetOperator('&' , self.opAnd, OP.AND)
self.SetOperator('and', self.opAnd, OP.AND)
self.SetOperator('|', self.opOr, OP.OR)
self.SetOperator('or', self.opOr, OP.OR)
self.SetOperator('!', self.opNot, OP.NOT, RIGHT)
self.SetOperator('not', self.opNot, OP.NOT, RIGHT)
#Pre-increment/decrement
self.SetOperator('++', self.opInc, OP.UNA)
self.SetOperator('--', self.opDec, OP.UNA)
#Math
self.SetOperator('+', self.opAdd, OP.ADD)
self.SetOperator('-', self.opMin, OP.ADD)
self.SetOperator('*', self.opMul, OP.MUL)
self.SetOperator('/', self.opDiv, OP.MUL)
self.SetOperator('%', self.opMod, OP.MUL)
self.SetOperator('^', self.opExp, OP.EXP, RIGHT)
#--Functions
self.SetFunction('CompareObVersion', self.fnCompareGameVersion, 1) # Retained for compatibility
self.SetFunction('CompareGameVersion', self.fnCompareGameVersion, 1)
self.SetFunction('CompareOBSEVersion', self.fnCompareSEVersion, 1) # Retained for compatibility
self.SetFunction('CompareSEVersion', self.fnCompareSEVersion, 1)