-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterpreter.py
More file actions
1186 lines (985 loc) · 36.5 KB
/
interpreter.py
File metadata and controls
1186 lines (985 loc) · 36.5 KB
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
import subprocess
try:
import pkg_resources
from pkg_resources import DistributionNotFound
except ModuleNotFoundError:
print(f"\033[93m[WARNING]Required package: ['Setuptools'] not found. Installing missing package...\033[0m")
os.system(f"{sys.executable} -m pip install setuptools")
import time
import random
import re
import math
import argparse
import difflib
import os
from os import path
import platform
import sys
try:
parser_arg = argparse.ArgumentParser(description='UniLang Interpreter')
parser_arg.add_argument('script', nargs="?", help='Path to the UniLang script file')
parser_arg.add_argument('--fo', action='store_true', help='Fail open on syntax errors')
parser_arg.add_argument('--fc', action='store_true', help='Fail close on syntax errors')
parser_arg.add_argument('--init', action='store_true', help='Prapare and ensure the interpreter is ready for first use.')
parser_arg.add_argument('--about', action='store_true', help='Show information about the interpreter.')
parser_arg.add_argument('--version', action='version', version='%(prog)s 1.0.0')
parser_arg.add_argument('--man', nargs='?', const='1', help='Show the ULS manual. Provide a page number optionally.')
parser_arg.add_argument('--debug', action='store_true', help='Enable debug mode.')
parser_arg.add_argument('--check', action='store_true', help='Check for updates.')
args = parser_arg.parse_args()
except argparse.ArgumentError as e:
print(f"\033[93m[WARNING] {e}\033[0m")
exit(1)
manual_pages = [
# Page 1
"""UniLang Script (ULS) Manual - Page 1
====================================
Welcome to UniLang Script!
UniLang Script (ULS) is a simple, interpreted programming language designed for beginners. It is inspired by Python and JavaScript, aiming to be easy to learn and use.
Use the command line argument '--man <page>' to navigate to specific pages of this manual.
Topics:
- Getting Started
- Basic Syntax
- Variables and Data Types
- Operators
- Control Structures
- Functions
- Built-in Functions
Example:
pypy interpreter.py --man 2""",
# Page 2
"""UniLang Script (ULS) Manual - Page 2
====================================
Getting Started:
To run a UniLang Script file, use the interpreter followed by the script filename:
Example:
pypy interpreter.py my_script.uls
Scripts should have the '.uls' extension.
Use '--man 3' to continue to Basic Syntax.""",
# Page 3
"""UniLang Script (ULS) Manual - Page 3
====================================
Basic Syntax:
- Statements end with a newline.
- Use braces { } to denote blocks of code.
- Comments start with '#' and continue to the end of the line.
Example:
# This is a comment
print("Hello, World!")
Use '--man 4' to learn about Variables and Data Types.""",
# Page 4
"""UniLang Script (ULS) Manual - Page 4
====================================
Variables and Data Types:
Variables are used to store information. You can assign a value to a variable using the '=' operator.
Example:
x = 10
name = "Alice"
is_active = true
Data Types:
- Numbers: integers (e.g., 10, -5)
- Strings: text enclosed in double quotes (e.g., "Hello")
- Booleans: true or false
Use '--man 5' to learn about Operators.""",
# Page 5
"""UniLang Script (ULS) Manual - Page 5
====================================
Operators:
Arithmetic Operators:
- Addition: +
- Subtraction: -
- Multiplication: *
- Division: /
- Modulo: %
Comparison Operators:
- Equal to: ==
- Not equal to: !=
- Greater than: >
- Less than: <
- Greater than or equal to: >=
- Less than or equal to: <=
Logical Operators:
- And: and
- Or: or
- Not: not
Example:
if (x > 0) and (x < 10) {
print("x is between 1 and 9")
}
Use '--man 6' to learn about Control Structures.""",
# Page 6
"""UniLang Script (ULS) Manual - Page 6
====================================
Control Structures:
If/Else Statements:
if condition {
# code to execute if condition is true
} else {
# code to execute if condition is false
}
Example:
if x > 10 {
print("x is greater than 10")
} else {
print("x is 10 or less")
}
While Loops:
while condition {
# code to execute while condition is true
}
Example:
i = 0
while i < 5 {
print(i)
i = i + 1
}
For Loops:
for variable in range(start, end) {
# code to execute for each value
}
Example:
for i in range(1, 5) {
print(i)
}
Use '--man 7' to learn about Functions.""",
# Page 7
"""UniLang Script (ULS) Manual - Page 7
====================================
Functions:
Functions are blocks of reusable code that perform a specific task. You can define a function using the 'define' keyword.
Syntax:
define function_name(parameters) {
# code to execute
return value
}
Example:
define greet(name) {
return "Hello, " + name + "!"
}
Call the function:
message = greet("Alice")
print(message)
Use '--man 8' to learn about Built-in Functions.""",
# Page 8
"""UniLang Script (ULS) Manual - Page 8
====================================
Built-in Functions:
UniLang provides several built-in functions to perform common tasks.
- print(value): Display the value to the console.
- input(prompt): Get input from the user.
- str(value): Convert value to a string.
- int(value): Convert value to an integer.
- length(value): Get the length of a string.
- randomint(min, max): Generate a random integer between min and max.
- sqrt(value): Calculate the square root of a number.
Example:
name = input("Enter your name: ")
print("Hello, " + name + "!")
rand_num = randomint(1, 100)
print("Random number between 1 and 100: " + str(rand_num))
Use '--man 9' to see additional resources.""",
# Page 9
"""UniLang Script (ULS) Manual - Page 9
====================================
Additional Resources:
For more examples and detailed documentation, please visit:
https://un7x.net/unilang-script
Thank you for using UniLang Script!
That's all for the manual. Use '--man <page>' to revisit any section.
"""
]
if args.man:
try:
page_number = int(args.man)
except ValueError:
page_number = 1
page_index = page_number - 1
if 0 <= page_index < len(manual_pages):
print(manual_pages[page_index])
else:
print(f"No manual page {page_number}. Available pages: 1-{len(manual_pages)}")
sys.exit(0)
try:
import ply.lex as lex
import ply.yacc as yacc
from colorama import init, Fore, Style
init(autoreset=True)
import requests
import sys
except ImportError or ModuleNotFoundError:
if not args.init:
print("Required packages not found. Please run the interpreter with the --init flag to install the required packages.")
exit(1)
def is_setuptools_installed():
return any(os.path.isdir(os.path.join(path, 'setuptools')) for path in sys.path)
if not is_setuptools_installed():
print("setuptools not found. Installing...")
os.system(f"{sys.executable} -m pip install setuptools")
try:
pkg_resources.get_distribution('ply')
print("\033[36m[INFO]ply is already installed.\033[0m")
pkg_resources.get_distribution('colorama')
print("\033[36m[INFO]colorama is already installed.\033[0m")
pkg_resources.get_distribution('requests')
print("\033[36m[INFO]requests is already installed.\033[0m")
pkg_resources.get_distribution('tqdm')
print("\033[36m[INFO]tqdm is already installed.\033[0m")
except pkg_resources.DistributionNotFound as e:
missing_packages = [str(e).split("'")[1]]
print(f"\033[93m[WARNING]Required package(s): {missing_packages} not found. Installing missing package(s)...\033[0m")
for package in missing_packages:
subprocess.call([sys.executable, "-m", "pip", "install", package])
if not args.init and not args.about and not args.script and not args.check:
parser_arg.error("the following arguments are required: script")
current_version = "1.1.3"
def about():
print(f"""
\033[36mUni\033[97;46mLang\033[0m | \033[107;30mScript Interpreter\033[0m
by UN7X
__ __ __ ______ __
/\ \/\ \ /\ \ /\ ___\ /\ \
\ \ \_\ \ \ \ \____ \ \___ \ \ \ \
\ \_____\ \ \_____\ \/\_____\ \ \_\
\/_____/ \/_____/ \/_____/ \/_/
""")
labels = ["Date:", "Connected to Internet:", "Interpreter path:", "UniLang Version:", "Operating System:", "OS Version:", "Machine Name:", "Processor:", "Architecture:", "Python Version:", "Type:",]
values = [
time.strftime('%Y-%m-%d %H:%M:%S'),
str(requests.get('https://google.com').status_code == 200),
os.path.abspath(__file__),
current_version,
platform.system(),
platform.version(),
platform.machine(),
platform.processor(),
str(platform.architecture()).replace("('", "").replace("', '", ": ").replace("')", ""),
platform.python_version(),
platform.python_implementation()
]
max_label_width = max(len(label) for label in labels)
max_value_width = max(len(value) for value in values)
for label, value in zip(labels, values):
print(f"{label:<{max_label_width}} {value:<{max_value_width}}")
print("""\n\033[36mUni\033[97;46mLang\033[0m is a simple, interpreted programming language designed for beginners.
It is inspired by Python and JavaScript, and aims to be easy to learn and use.
The interpreter is written in Python using the PLY library for lexing and parsing.
And it also includes built-in functions for common tasks such as input/output, math, and string manipulation.
The language supports basic features such as variables, expressions, control structures, functions, and more.
It's designed to be extensible, so additional features and pure-python libraries can be added easily.
The goal of \033[36mUni\033[97;46mLang\033[0m is to provide a simple and fun way to learn programming and create small projects.\n""")
print("For more info, please visit https://un7x.net/unilang-script\n")
exit(0)
def check_and_install_package(package_names):
for package_name in package_names:
try:
pkg_resources.get_distribution(package_name)
print(f"{package_name} is already installed.")
except DistributionNotFound:
print(f"{package_name} not found. Installing...")
subprocess.call(['pip', 'install', package_name])
return True
GITHUB_API_URL = 'https://api.github.com/repos/UN7X/unilang/releases/latest'
def check_for_updates():
try:
response = requests.get(GITHUB_API_URL)
latest_release = response.json()['name']
if current_version < latest_release:
print(f"\033[93m[WARNING] A newer version ({latest_release}) is available. Please update for best stability.\033[0m")
else:
print("\033[92m[INFO] You are using the latest version.\033[0m")
except Exception as e:
print("\033[91m[ERROR] Could not check for updates.\033[0m", e)
if bool(requests.get('https://google.com').status_code == 200) and args.check:
check_for_updates()
if args.init:
check_for_updates()
print("\033[36m[INFO] Initializing interpreter...\033[0m")
if platform.python_implementation() != 'PyPy':
print("\033[93m[WARNING] PyPy interpreter not detected. It is recommended to use PyPy for best performance.\033[0m")
if args.about:
about()
# ---------------- LEXER -----------------
reserved = {
'print': 'PRINT',
'if': 'IF',
'else': 'ELSE',
'while': 'WHILE',
'define': 'DEFINE',
'result': 'RESULT',
'not': 'NOT',
'wait': 'WAIT',
'for': 'FOR',
'in': 'IN',
'or': 'OR',
'and': 'AND',
'range': 'RANGE',
'true': 'TRUE',
'false': 'FALSE',
'import': 'IMPORT',
'break': 'BREAK'
}
tokens = [
'NUMBER', 'STRING', 'IDENTIFIER',
'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'MOD',
'EQUALS', 'LPAREN', 'RPAREN', 'COMMA',
'LT', 'GT', 'EQ', 'NEQ', 'LE', 'GE', 'DOT',
'LBRACE', 'RBRACE', 'INCREMENT', 'DECREMENT', 'PLUS_EQUALS', 'MINUS_EQUALS',
] + list(reserved.values())
t_DOT = r'\.'
t_PLUS = r'\+'
t_MINUS = r'-'
t_TIMES = r'\*'
t_DIVIDE = r'/'
t_MOD = r'%'
t_EQUALS = r'='
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_COMMA = r','
t_LBRACE = r'\{'
t_RBRACE = r'\}'
t_LT = r'<'
t_GT = r'>'
t_EQ = r'=='
t_NEQ = r'!='
t_LE = r'<='
t_GE = r'>='
t_INCREMENT = r'\+\+'
t_DECREMENT = r'--'
t_PLUS_EQUALS = r'\+='
t_MINUS_EQUALS = r'-='
t_ignore = ' \t'
def t_COMMENT(t):
r'\#.*'
def t_IDENTIFIER(t):
r'[a-zA-Z_]\w*'
t.type = reserved.get(t.value, 'IDENTIFIER')
return t
def t_STRING(t):
r'\"([^\\\n]|(\\.))*?\"'
t.value = t.value[1:-1]
return t
def t_NUMBER(t):
r'\d+'
t.value = int(t.value)
return t
def t_newline(t):
r'\n+'
t.lexer.lineno += len(t.value)
def t_error(t):
print(f"{Fore.YELLOW}[WARNING] Illegal character '{t.value[0]}' at line {t.lineno}")
t.lexer.skip(1)
if not args.about:
try:
if args.init:
print("\033[36m[INFO] Initializing lexer...\033[0m")
lexer = lex.lex()
if args.init:
print("\033[32m[SUCCESS] Lexer initialized.\033[0m")
except Exception as e:
print(f"{Fore.LIGHTRED_EX}[FATAL] {e}")
exit(1)
class Node: pass
class Program(Node):
def __init__(self, statements):
self.statements = statements
class Block(Node):
def __init__(self, statements):
self.statements = statements
class Number(Node):
def __init__(self, value):
self.value = value
class String(Node):
def __init__(self, value):
self.value = value
class Variable(Node):
def __init__(self, name):
self.name = name
class BinaryOp(Node):
def __init__(self, op, left, right):
self.op = op
self.left = left
self.right = right
class UnaryOp(Node):
def __init__(self, op, operand):
self.op = op
self.operand = operand
class Assignment(Node):
def __init__(self, name, value):
self.name = name
self.value = value
class Print(Node):
def __init__(self, expression):
self.expression = expression
class If(Node):
def __init__(self, condition, then_branch, else_branch=None):
self.condition = condition
self.then_branch = then_branch
self.else_branch = else_branch
class While(Node):
def __init__(self, condition, body):
self.condition = condition
self.body = body
class FunctionDef(Node):
def __init__(self, name, params, body):
self.name = name
self.params = params
self.body = body
class FunctionCall(Node):
def __init__(self, name, args):
self.name = name
self.args = args
class Return(Node):
def __init__(self, value):
self.value = value
class Wait(Node):
def __init__(self, duration):
self.duration = duration
class Import(Node):
def __init__(self, module_name):
self.module_name = module_name
class MemberAccess(Node):
def __init__(self, obj, member):
self.obj = obj
self.member = member
class CompoundAssignment(Node):
def __init__(self, name, op, value):
self.name = name
self.op = op
self.value = value
class MethodCall(Node):
def __init__(self, obj, method_name, args):
self.obj = obj
self.method_name = method_name
self.args = args
class Boolean(Node):
def __init__(self, value):
self.value = value
class ForLoop(Node):
def __init__(self, var_name, iterable, body):
self.var_name = var_name
self.iterable = iterable
self.body = body
class RangeExpression(Node):
def __init__(self, start, end):
self.start = start
self.end = end
class Break(Node):
pass
class Function:
def __init__(self, params, body):
self.params = params
self.body = body
class ExecutionContext:
def __init__(self, parent=None):
self.variables = {}
self.functions = {} if parent is None else parent.functions
self.parent = parent
self.return_value = None
def get_variable(self, name):
if name in self.variables:
return self.variables[name]
elif self.parent:
return self.parent.get_variable(name)
else:
raise NameError(f"Undefined variable '{name}'")
def set_variable(self, name, value):
if name in self.variables or self.parent is None:
self.variables[name] = value
else:
self.parent.set_variable(name, value)
def define_function(self, name, function):
self.functions[name] = function
def get_function(self, name):
if name in self.functions:
return self.functions[name]
elif self.parent:
return self.parent.get_function(name)
else:
raise NameError(f"Undefined function '{name}'")
class BuiltInFunction(Function):
def __init__(self, func):
self.func = func
class ReturnException(Exception):
def __init__(self, value):
self.value = value
# Precedence to handle unary minus
precedence = (
('left', 'OR'),
('left', 'AND'),
('nonassoc', 'EQ', 'NEQ'),
('nonassoc', 'LT', 'LE', 'GT', 'GE'),
('left', 'PLUS', 'MINUS'),
('left', 'TIMES', 'DIVIDE', 'MOD'),
('right', 'NOT', 'UMINUS'),
)
# ---------------- GRAMMAR -----------------
def p_program(p):
'''program : statement_list'''
p[0] = Program(p[1])
def p_statement_list(p):
'''statement_list : statement_list statement
| statement'''
p[0] = p[1] + [p[2]] if len(p) == 3 else [p[1]]
def p_statement(p):
'''statement : assignment
| print_statement
| if_statement
| while_statement
| function_def
| for_loop
| return_statement
| wait_statement
| block
| expression_statement
| import_statement
| BREAK'''
p[0] = Break() if p.slice[1].type == 'BREAK' else p[1]
def p_block(p):
'''block : LBRACE statement_list RBRACE
| LBRACE RBRACE'''
p[0] = Block(p[2]) if len(p) == 4 else Block([])
def p_expression_statement(p):
'''expression_statement : expression'''
p[0] = p[1]
def p_assignment(p):
'''assignment : IDENTIFIER EQUALS expression'''
p[0] = Assignment(p[1], p[3])
def p_print_statement(p):
'''print_statement : PRINT LPAREN expression RPAREN'''
p[0] = Print(p[3])
def p_if_statement(p):
'''if_statement : IF expression block
| IF expression block ELSE block'''
p[0] = If(p[2], p[3]) if len(p) == 4 else If(p[2], p[3], p[5])
def p_for_loop(p):
'''for_loop : FOR IDENTIFIER IN iterable block'''
p[0] = ForLoop(p[2], p[4], p[5])
def p_iterable(p):
'''iterable : expression
| RANGE LPAREN expression COMMA expression RPAREN'''
p[0] = p[1] if len(p) == 2 else RangeExpression(p[3], p[5])
def p_while_statement(p):
'''while_statement : WHILE expression block'''
p[0] = While(p[2], p[3])
def p_function_def(p):
'''function_def : DEFINE IDENTIFIER LPAREN RPAREN block
| DEFINE IDENTIFIER LPAREN param_list RPAREN block'''
if len(p) == 6:
p[0] = FunctionDef(p[2], [], p[5])
else:
p[0] = FunctionDef(p[2], p[4], p[6])
def p_param_list(p):
'''param_list : IDENTIFIER
| param_list COMMA IDENTIFIER
| empty'''
if len(p) == 2 and p[1] is not None:
p[0] = [p[1]]
elif len(p) == 4:
p[0] = p[1] + [p[3]]
else:
p[0] = []
def p_import_statement(p):
'''import_statement : IMPORT IDENTIFIER'''
p[0] = Import(p[2])
def p_return_statement(p):
'''return_statement : RESULT expression'''
p[0] = Return(p[2])
def p_wait_statement(p):
'''wait_statement : WAIT expression'''
p[0] = Wait(p[2])
def p_expression(p):
'''expression : logic_or_expr'''
p[0] = p[1]
def p_logic_or_expr(p):
'''logic_or_expr : logic_or_expr OR logic_and_expr
| logic_and_expr'''
p[0] = BinaryOp('or', p[1], p[3]) if len(p) == 4 else p[1]
def p_logic_and_expr(p):
'''logic_and_expr : logic_and_expr AND equality_expr
| equality_expr'''
p[0] = BinaryOp('and', p[1], p[3]) if len(p) == 4 else p[1]
def p_equality_expr(p):
'''equality_expr : relational_expr
| equality_expr EQ relational_expr
| equality_expr NEQ relational_expr'''
p[0] = p[1] if len(p) == 2 else BinaryOp(p[2], p[1], p[3])
def p_relational_expr(p):
'''relational_expr : additive_expr
| relational_expr LT additive_expr
| relational_expr GT additive_expr
| relational_expr LE additive_expr
| relational_expr GE additive_expr'''
p[0] = p[1] if len(p) == 2 else BinaryOp(p[2], p[1], p[3])
def p_additive_expr(p):
'''additive_expr : additive_expr PLUS term
| additive_expr MINUS term
| term'''
p[0] = BinaryOp(p[2], p[1], p[3]) if len(p) == 4 else p[1]
def p_term(p):
'''term : term TIMES factor
| term DIVIDE factor
| term MOD factor
| factor'''
p[0] = BinaryOp(p[2], p[1], p[3]) if len(p) == 4 else p[1]
def p_factor(p):
'''factor : PLUS factor
| MINUS factor %prec UMINUS
| NOT factor
| primary'''
p[0] = UnaryOp(p[1], p[2]) if len(p) == 3 else p[1]
def p_primary(p):
'''primary : atom
| primary DOT IDENTIFIER
| primary DOT IDENTIFIER LPAREN arg_list RPAREN
| primary DOT IDENTIFIER LPAREN RPAREN
| primary LPAREN arg_list RPAREN
| primary LPAREN RPAREN'''
if len(p) == 2:
# atom
p[0] = p[1]
elif len(p) == 4 and p[2] == '.':
# primary DOT IDENTIFIER
p[0] = MemberAccess(p[1], p[3])
elif len(p) == 6 and p[3] != '(':
# primary DOT IDENTIFIER LPAREN RPAREN
# means primary.member()
p[0] = MethodCall(p[1], p[3], [])
elif len(p) == 7:
# primary DOT IDENTIFIER LPAREN arg_list RPAREN
p[0] = MethodCall(p[1], p[3], p[5])
elif len(p) == 5 and p[2] == '(':
# primary LPAREN arg_list RPAREN
p[0] = FunctionCall(p[1], p[3])
elif len(p) == 4 and p[2] == '(':
# primary LPAREN RPAREN
p[0] = FunctionCall(p[1], [])
def p_arg_list(p):
'''arg_list : expression
| arg_list COMMA expression
| empty'''
if len(p) == 2 and p[1] is not None:
p[0] = [p[1]]
elif len(p) == 4:
p[0] = p[1] + [p[3]]
else:
p[0] = []
def p_atom(p):
'''atom : IDENTIFIER
| NUMBER
| STRING
| TRUE
| FALSE
| LPAREN expression RPAREN'''
if len(p) == 2:
t = p.slice[1].type
if t == 'IDENTIFIER':
p[0] = Variable(p[1])
elif t == 'NUMBER':
p[0] = Number(p[1])
elif t == 'STRING':
p[0] = String(p[1])
elif t == 'TRUE':
p[0] = Boolean(True)
elif t == 'FALSE':
p[0] = Boolean(False)
else:
p[0] = p[2]
def p_expression_increment(p):
'''expression : expression INCREMENT
| expression DECREMENT'''
if p[2] == '++':
p[0] = UnaryOp('increment', p[1])
else:
p[0] = UnaryOp('decrement', p[1])
def p_expression_compound_assignment(p):
'''expression : IDENTIFIER PLUS_EQUALS expression
| IDENTIFIER MINUS_EQUALS expression'''
if p[2] == '+=':
p[0] = CompoundAssignment(p[1], '+', p[3])
else:
p[0] = CompoundAssignment(p[1], '-', p[3])
def p_empty(p):
'''empty :'''
p[0] = None
def p_error(p):
if p:
token_value = str(p.value)
suggestions = difflib.get_close_matches(token_value, list(reserved.keys()) + ['(', ')', '{', '}', '+', '-', '*', '/', '==', '!=', '<', '>', '<=', '>='], n=1, cutoff=0.8)
error_message = f"[ERROR] Syntax error at '{token_value}' on line {p.lineno}"
if suggestions:
error_message += f". Did you mean '{suggestions[0]}'?"
print(Fore.RED + error_message)
else:
print(f"{Fore.RED}[ERROR] Syntax error at EOF")
if not args.about:
# build parser, i think
try:
if args.init:
print("\033[36m[INFO] Initializing parser...\033[0m")
class ColorStream:
def __init__(self, stream, debug=False):
self.stream = stream
self.debug_mode = debug
self.printed_messages = set()
def write(self, data):
if str(data).startswith("WARNING:"):
#remove the warning prefix, replacing it with our own [WARNING]
data = str(data).replace("WARNING:", "[WARNING]")
self.stream.write(Fore.YELLOW + data + "\033[0m\n")
else:
self.stream.write("\033[93m" + data + "\033[0m")
def flush(self):
self.stream.flush()
def info(self, message, *args):
if not self.debug_mode:
if not hasattr(self, 'printed_messages'):
self.printed_messages = set()
if message not in self.printed_messages and message != "":
self.write("\033[36m[INFO] " + message + "\033[0m\n")
self.printed_messages.add(message)
else:
self.write("\033[36m[INFO] " + message + "\033[0m\n")
def success(self, message, *args):
self.write("\033[32m[SUCCESS] " + message + "\033[0m\n")
def fatal(self, message, *args):
self.write(f"{Fore.LIGHTRED_EX}[FATAL] {message}" + "\n")
def warning(self, message, *args):
self.write(f"{Fore.YELLOW}[WARNING] {message}" + "\n")
def debug(self, message, *args):
if self.debug_mode:
self.write("\033[35m[DEBUG] " + message + "\033[0m\n")
parser = yacc.yacc(start='program', debug=True, debuglog=ColorStream(sys.stdout, debug=args.debug), write_tables=True, optimize=True)
if args.init:
print("\033[32m[SUCCESS] Parser initialized.\033[0m")
except Exception as e:
print(Fore.LIGHTRED_EX + f"[FATAL] {e}")
exit(1)
if args.init:
print("\033[32m[SUCCESS] Interpreter initialization complete!\033[0m")
exit(0)
# ---------------- EXECUTION -----------------
class ReturnException(Exception):
def __init__(self, value):
self.value = value
from colorama import Fore
import math, time, random, requests
class ReturnException(Exception):
def __init__(self, value):
self.value = value
def execute(node, context):
if node is None:
return None
if handler := NODE_HANDLERS.get(type(node)):
return handler(node, context)
else:
raise TypeError(f"Unknown node type '{type(node).__name__}'")
def handle_program(node, context):
for stmt in node.statements:
val = execute(stmt, context)
# If a break is encountered at top-level, it just stops executing further statements
if val == 'break':
break
return None
def handle_import(node, context):
module_name = node.module_name
try:
module = __import__(module_name)
context.set_variable(module_name, module)
except ImportError:
print(f"{Fore.RED}[ERROR] Module '{module_name}' not found")
def handle_block(node, context):
for stmt in node.statements:
val = execute(stmt, context)
if val == 'break':
return 'break'
return None
def handle_number(node, context):
return node.value
def handle_string(node, context):
return node.value
def handle_variable(node, context):
return context.get_variable(node.name)
def handle_assignment(node, context):
value = execute(node.value, context)
context.set_variable(node.name, value)
def handle_print(node, context):
value = execute(node.expression, context)
print(value)
def handle_wait(node, context):
duration = execute(node.duration, context)
time.sleep(duration)
def handle_boolean(node, context):
return node.value
def handle_if(node, context):
if condition := execute(node.condition, context):
return execute(node.then_branch, context)
elif node.else_branch:
return execute(node.else_branch, context)
return None
def handle_function_def(node, context):
func = Function(node.params, node.body)
context.define_function(node.name, func)
def handle_function_call(node, context):
func_name = node.name.name if hasattr(node.name, 'name') else node.name