-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
950 lines (804 loc) · 34 KB
/
script.js
File metadata and controls
950 lines (804 loc) · 34 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
// Simplified SPL interpreter code - more concise and readable
const splInterpreterCode = `
import math, random, string
class SPLError(Exception): pass
class Token:
def __init__(self, type, value, line=1, col=1):
self.type, self.value, self.line, self.col = type, value, line, col
def __repr__(self): return f"Token({self.type}, {self.value})"
class Lexer:
OPERATORS = {
'+': 'PLUS', '-': 'MINUS', '*': 'MULTIPLY', '/': 'DIVIDE',
'(': 'LPAREN', ')': 'RPAREN', '[': 'LBRACKET', ']': 'RBRACKET',
'{': 'LBRACE', '}': 'RBRACE', ';': 'SEMICOLON', ',': 'COMMA', '.': 'DOT'
}
KEYWORDS = {
'if': 'IF', 'else': 'ELSE', 'while': 'WHILE', 'print': 'PRINT',
'break': 'BREAK', 'True': 'TRUE', 'False': 'FALSE',
'for': 'FOR', 'in': 'IN', 'range': 'RANGE',
'String': 'STRING_CLASS', 'List':'LIST_CLASS',
'Math': 'MATH_CLASS', 'Number': 'NUMBER_CLASS'
}
def __init__(self, text):
self.text = text
self.pos = 0
self.line = 1
self.col = 1
def tokenize(self):
tokens = []
while self.pos < len(self.text):
char = self.current_char()
if not char: break
if char.isspace():
if char == '\\n':
tokens.append(Token('NEWLINE', '\\n', self.line, self.col))
self.line += 1
self.col = 1
self.advance()
elif char == '#':
self.skip_comment()
elif char.isdigit():
tokens.append(self.make_number())
elif char.isalpha() or char == '_':
tokens.append(self.make_identifier())
elif char == '"':
tokens.append(self.make_string())
elif char in self.OPERATORS:
tokens.append(Token(self.OPERATORS[char], char, self.line, self.col))
self.advance()
elif char in '=><!' and self.peek() == '=':
op_map = {'==': 'EQ', '>=': 'GTE', '<=': 'LTE', '!=': 'NEQ'}
op = char + self.peek()
tokens.append(Token(op_map[op], op, self.line, self.col))
self.advance(2)
elif char == '=':
tokens.append(Token('ASSIGN', '=', self.line, self.col))
self.advance()
elif char in '><':
op_map = {'>': 'GT', '<': 'LT'}
tokens.append(Token(op_map[char], char, self.line, self.col))
self.advance()
else:
raise SPLError(f"Unexpected character: {char}")
tokens.append(Token('EOF', None, self.line, self.col))
return tokens
def current_char(self):
return None if self.pos >= len(self.text) else self.text[self.pos]
def peek(self):
next_pos = self.pos + 1
return None if next_pos >= len(self.text) else self.text[next_pos]
def advance(self, count=1):
for _ in range(count):
if self.pos < len(self.text):
self.pos += 1
self.col += 1
def skip_comment(self):
while self.current_char() and self.current_char() != '\\n':
self.advance()
def make_number(self):
start_col = self.col
num_str = ''
while self.current_char() and (self.current_char().isdigit() or self.current_char() == '.'):
num_str += self.current_char()
self.advance()
return Token('NUMBER', float(num_str), self.line, start_col)
def make_identifier(self):
start_col = self.col
id_str = ''
while self.current_char() and (self.current_char().isalnum() or self.current_char() == '_'):
id_str += self.current_char()
self.advance()
token_type = self.KEYWORDS.get(id_str, 'IDENTIFIER')
return Token(token_type, id_str, self.line, start_col)
def make_string(self):
start_col = self.col
self.advance() # Skip opening quote
string_val = ''
while self.current_char() and self.current_char() != '"':
string_val += self.current_char()
self.advance()
if self.current_char() == '"':
self.advance() # Skip closing quote
else:
raise SPLError("Unterminated string")
return Token('STRING', string_val, self.line, start_col)
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.pos = 0
def current_token(self):
return self.tokens[self.pos] if self.pos < len(self.tokens) else None
def advance(self): self.pos += 1
def parse(self):
statements = []
while self.current_token() and self.current_token().type != 'EOF':
if self.current_token().type == 'NEWLINE':
self.advance()
continue
stmt = self.parse_statement()
if stmt:
statements.append(stmt)
self._handle_statement_separator()
return {'type': 'Program', 'statements': statements}
def _handle_statement_separator(self):
"""Handle semicolons and newlines after statements"""
if self.current_token() and self.current_token().type == 'SEMICOLON':
self.advance()
elif self.current_token() and self.current_token().type == 'NEWLINE':
while self.current_token() and self.current_token().type == 'NEWLINE':
self.advance()
if (self.current_token() and
self.current_token().type not in ['EOF', 'RBRACE', 'ELSE', 'IF', 'WHILE', 'FOR', 'PRINT']):
self.expect('SEMICOLON')
elif not self.current_token() or self.current_token().type == 'EOF':
pass
else:
if (self.current_token() and
self.current_token().type not in ['RBRACE', 'ELSE', 'EOF']):
self.expect('SEMICOLON')
def parse_statement(self):
if not self.current_token(): return None
token_type = self.current_token().type
parsers = {
'PRINT': self.parse_print,
'IF': self.parse_if,
'WHILE': self.parse_while,
'FOR': self.parse_for,
'BREAK': self.parse_break,
'IDENTIFIER': self.parse_assignment
}
if token_type in parsers:
return parsers[token_type]()
else:
raise SPLError(f"Unexpected token: {token_type}")
def parse_break(self):
self.advance()
return {'type': 'Break'}
def parse_print(self):
self.advance() # consume 'print'
self.expect('LPAREN')
args = []
if self.current_token() and self.current_token().type != 'RPAREN':
args.append(self.parse_expression())
while self.current_token() and self.current_token().type == 'COMMA':
self.advance() # consume comma
args.append(self.parse_expression())
self.expect('RPAREN')
return {'type': 'Print', 'args': args}
def parse_assignment(self):
# Look ahead to see if this is an assignment or expression statement
if (self.pos + 1 < len(self.tokens) and
self.tokens[self.pos + 1].type == 'ASSIGN'):
# This is an assignment
name = self.current_token().value
self.advance() # consume identifier
self.expect('ASSIGN')
value = self.parse_expression()
return {'type': 'Assign', 'name': name, 'value': value}
else:
# This is an expression statement
expr = self.parse_expression()
return {'type': 'ExpressionStatement', 'expression': expr}
def parse_if(self):
self.advance() # consume 'if'
condition = self.parse_expression()
self._skip_newlines()
then_branch = self.parse_block()
else_branch = []
if self.current_token() and self.current_token().type == 'ELSE':
self.advance() # consume 'else'
self._skip_newlines()
else_branch = self.parse_block()
return {'type': 'If', 'condition': condition, 'then_branch': then_branch, 'else_branch': else_branch}
def parse_for(self):
self.advance()
if not self.current_token() or self.current_token().type != 'IDENTIFIER':
raise SPLError("Expected variable name after 'for'")
var_name = self.current_token().value
self.advance()
self.expect('IN')
iterable = self.parse_expression()
self._skip_newlines()
body = self.parse_block()
return {'type': 'For', 'var_name': var_name, 'iterable': iterable, 'body': body}
def parse_static_method(self, class_name):
self.advance()
method_name = self.current_token().value
self.advance()
self.expect('LPAREN')
args = []
if self.current_token() and self.current_token().type != 'RPAREN':
args.append(self.parse_expression())
while self.current_token() and self.current_token().type == "COMMA":
self.advance()
args.append(self.parse_expression())
self.expect('RPAREN')
return {
'type': 'StaticMethodCall',
'class': class_name,
'method': method_name,
'args': args
}
def parse_while(self):
self.advance() # consume 'while'
condition = self.parse_expression()
self._skip_newlines()
body = self.parse_block()
return {'type': 'While', 'condition': condition, 'body': body}
def _skip_newlines(self):
"""Helper to skip newline tokens"""
while self.current_token() and self.current_token().type == 'NEWLINE':
self.advance()
def parse_block(self):
statements = []
self.expect('LBRACE')
while self.current_token() and self.current_token().type != 'RBRACE':
if self.current_token().type == 'NEWLINE':
self.advance()
continue
stmt = self.parse_statement()
if stmt:
statements.append(stmt)
if self.current_token() and self.current_token().type == 'SEMICOLON':
self.advance()
else:
next_pos = self.pos
while next_pos < len(self.tokens) and self.tokens[next_pos].type == 'NEWLINE':
next_pos += 1
if next_pos < len(self.tokens) and self.tokens[next_pos].type != 'RBRACE':
self.expect('SEMICOLON')
self.expect('RBRACE')
return statements
def parse_expression(self): return self.parse_comparison()
def parse_comparison(self):
left = self.parse_term()
while self.current_token() and self.current_token().type in ['GT', 'LT', 'GTE', 'LTE', 'EQ', 'NEQ']:
op = self.current_token().value
self.advance()
right = self.parse_term()
left = {'type': 'BinOp', 'left': left, 'op': op, 'right': right}
return left
def parse_term(self):
left = self.parse_factor()
while self.current_token() and self.current_token().type in ['PLUS', 'MINUS']:
op = self.current_token().value
self.advance()
right = self.parse_factor()
left = {'type': 'BinOp', 'left': left, 'op': op, 'right': right}
return left
def parse_factor(self):
left = self.parse_primary()
while self.current_token() and self.current_token().type in ['MULTIPLY', 'DIVIDE']:
op = self.current_token().value
self.advance()
right = self.parse_primary()
left = {'type': 'BinOp', 'left': left, 'op': op, 'right': right}
return left
def parse_primary(self):
token = self.current_token()
simple_types = {
'NUMBER': lambda: {'type': 'Number', 'value': token.value},
'STRING': lambda: {'type': 'String', 'value': token.value},
'TRUE': lambda: {'type': 'Boolean', 'value': True},
'FALSE': lambda: {'type': 'Boolean', 'value': False}
}
if token.type in simple_types:
self.advance()
return simple_types[token.type]()
elif token.type in ['STRING_CLASS', 'LIST_CLASS', 'MATH_CLASS', 'NUMBER_CLASS']:
class_name = token.value
self.advance()
if self.current_token() and self.current_token().type == 'DOT':
return self.parse_static_method(class_name)
else:
raise SPLError(f"Unexpected class reference: {class_name}")
elif token.type == 'IDENTIFIER':
name = token.value
self.advance()
result = None
if self.current_token() and self.current_token().type == 'LBRACKET':
self.advance()
index = self.parse_expression()
self.expect('RBRACKET')
result = {'type': 'Index', 'object': {'type': 'Variable', 'name': name}, 'index': index}
else:
result = {'type': 'Variable', 'name': name}
while self.current_token() and self.current_token().type == 'DOT':
self.advance()
method_name = self.current_token().value
self.advance()
self.expect('LPAREN')
args = []
if self.current_token() and self.current_token().type != 'RPAREN':
args.append(self.parse_expression())
while self.current_token() and self.current_token().type == 'COMMA':
self.advance()
args.append(self.parse_expression())
self.expect('RPAREN')
result = {
'type': 'MethodCall',
'object': result,
'method': method_name,
'args': args
}
return result
elif token.type == 'LPAREN':
self.advance()
expr = self.parse_expression()
self.expect('RPAREN')
return expr
elif token.type == 'MINUS':
self.advance()
operand = self.parse_primary()
return {'type': 'UnaryOp', 'op': '-', 'operand': operand}
elif token.type == 'LBRACKET':
self.advance()
elements = []
if self.current_token() and self.current_token().type != 'RBRACKET':
elements.append(self.parse_expression())
while self.current_token() and self.current_token().type == 'COMMA':
self.advance()
elements.append(self.parse_expression())
self.expect('RBRACKET')
return {'type': 'List', 'elements': elements}
elif token.type == 'RANGE':
self.advance()
self.expect('LPAREN')
args = []
if self.current_token() and self.current_token().type != 'RPAREN':
args.append(self.parse_expression())
while self.current_token() and self.current_token().type == 'COMMA':
self.advance()
args.append(self.parse_expression())
self.expect('RPAREN')
return {'type': 'Range', 'args': args}
else:
raise SPLError(f"Unexpected token: {token.type}")
def expect(self, token_type):
if self.current_token() and self.current_token().type == token_type:
self.advance()
else:
current = self.current_token().type if self.current_token() else 'EOF'
raise SPLError(f"Expected {token_type}, got {current}")
class Interpreter:
def __init__(self):
self.variables = {}
self.output = []
def interpret(self, node):
method_name = f'visit_{node["type"]}'
method = getattr(self, method_name, self.generic_visit)
return method(node)
def generic_visit(self, node):
raise SPLError(f"No visit method for {node['type']}")
def visit_Program(self, node):
result = None
for stmt in node['statements']:
result = self.interpret(stmt)
return result
def visit_Number(self, node): return node['value']
def visit_Boolean(self, node): return node['value']
def visit_String(self, node): return node['value']
def visit_Break(self, node): raise BreakException()
def visit_Variable(self, node):
name = node['name']
if name in self.variables:
return self.variables[name]
else:
raise SPLError(f"Variable '{name}' is not defined")
def visit_BinOp(self, node):
left = self.interpret(node['left'])
right = self.interpret(node['right'])
op = node['op']
if op == '/' and right == 0:
raise SPLError("Division by zero")
ops = {
'+': lambda l, r: l + r,
'-': lambda l, r: l - r,
'*': lambda l, r: l * r,
'/': lambda l, r: l / r,
'>': lambda l, r: l > r,
'<': lambda l, r: l < r,
'>=': lambda l, r: l >= r,
'<=': lambda l, r: l <= r,
'==': lambda l, r: l == r,
'!=': lambda l, r: l != r
}
if op in ops:
return ops[op](left, right)
else:
raise SPLError(f"Unknown operator: {op}")
def visit_UnaryOp(self, node):
operand = self.interpret(node['operand'])
if node['op'] == '-':
return -operand
else:
raise SPLError(f"Unknown unary operator: {node['op']}")
def visit_Assign(self, node):
value = self.interpret(node['value'])
self.variables[node['name']] = value
return value
def visit_ExpressionStatement(self, node):
# Evaluate expression but don't return the value (for statements)
self.interpret(node['expression'])
return None
def visit_Print(self, node):
values = [str(self.interpret(arg)) for arg in node['args']]
output_text = ' '.join(values)
self.output.append(output_text)
return None
def visit_If(self, node):
condition = self.interpret(node['condition'])
if condition:
return self._execute_statements(node['then_branch'])
elif node['else_branch']:
return self._execute_statements(node['else_branch'])
return None
def visit_For(self, node):
iterable_value = self.interpret(node['iterable'])
result = None
try:
if isinstance(iterable_value, list):
for item in iterable_value:
self.variables[node['var_name']] = item
result = self._execute_statements(node['body'])
elif isinstance(iterable_value, dict) and iterable_value.get('type') == 'range':
start = int(iterable_value.get('start', 0))
end = int(iterable_value.get('end', 0))
step = int(iterable_value.get('step', 1))
for i in range(start, end, step):
self.variables[node['var_name']] = i
result = self._execute_statements(node['body'])
else:
raise SPLError(f"Object is not iterable: {type(iterable_value)}")
except BreakException:
pass
return result
def visit_Range(self, node):
args = [self.interpret(arg) for arg in node['args']]
if len(args) == 1:
return {'type': 'range', 'start': 0, 'end': int(args[0]), 'step': 1}
elif len(args) == 2:
return {'type': 'range', 'start': int(args[0]), 'end': int(args[1]), 'step': 1}
elif len(args) == 3:
return {'type': 'range', 'start': int(args[0]), 'end': int(args[1]), 'step': int(args[2])}
else:
raise SPLError('range() takes 1 to 3 arguments')
def visit_While(self, node):
result = None
try:
while self.interpret(node['condition']):
result = self._execute_statements(node['body'])
except BreakException:
pass
return result
def visit_List(self, node):
return [self.interpret(element) for element in node['elements']]
def visit_Index(self, node):
obj = self.interpret(node['object'])
index = int(self.interpret(node['index']))
if isinstance(obj, list):
if 0 <= index < len(obj):
return obj[index]
else:
raise SPLError(f"List index out of range: {index}")
else:
raise SPLError(f"Object is not indexable: {type(obj)}")
def visit_MethodCall(self, node):
obj = self.interpret(node['object'])
method_name = node['method']
args = [self.interpret(arg) for arg in node['args']]
if isinstance(obj, str):
return self._call_string_method(obj, method_name, args)
elif isinstance(obj, list):
return self._call_list_method(obj, method_name, args)
elif isinstance(obj, (int, float)):
return self._call_number_method(obj, method_name, args)
elif isinstance(obj, bool):
return self._call_boolean_method(obj, method_name, args)
else:
raise SPLError(f"Object of type {type(obj)} has no methods")
def visit_StaticMethodCall(self, node):
class_name = node['class']
method_name = node['method']
args = [self.interpret(arg) for arg in node['args']]
if class_name == 'String':
return self._call_string_static_method(method_name, args)
elif class_name == 'List':
return self._call_list_static_method(method_name, args)
elif class_name == 'Math':
return self._call_math_static_method(method_name, args)
else:
raise SPLError(f"Unknown class: {class_name}")
def _call_string_static_method(self, method_name, args):
methods = {
'fromcode': lambda code: chr(int(code)),
'join': lambda items, sep='': sep.join(str(x) for x in items),
'repeat': lambda text, count: str(text) * int(count),
'ascii_letters': lambda: string.ascii_letters,
'digits': lambda: string.digits
}
if method_name not in methods:
raise SPLError(f"String class has no static method '{method_name}'")
return methods[method_name](*args)
def _call_string_method(self, string_obj, method_name, args):
methods = {
'length': lambda: len(string_obj),
'upper': lambda: string_obj.upper(),
'lower': lambda: string_obj.lower(),
'slice': lambda start, end=None: string_obj[start:end] if end else string_obj[start:],
'replace': lambda old, new: string_obj.replace(old, new),
'split': lambda sep=' ': string_obj.split(sep),
'strip': lambda: string_obj.strip(),
'startswith': lambda prefix: string_obj.startswith(prefix),
'endswith': lambda suffix: string_obj.endswith(suffix),
'find': lambda substring: string_obj.find(substring),
'contains': lambda substring: substring in string_obj
}
if method_name not in methods:
raise SPLError(f"String has no method '{method_name}'")
try:
return methods[method_name](*args)
except TypeError:
raise SPLError(f"Wrong number of arguments for string.{method_name}")
def _call_list_static_method(self, method_name, args):
methods = {
'range': lambda start, end=None, step=1: list(range(start, end or start, step)),
'fill': lambda count, value: [value] * int(count),
'empty': lambda: [],
'from_string': lambda text: list(text)
}
if method_name not in methods:
raise SPLError(f"List class has no static method '{method_name}'")
return methods[method_name](*args)
def _call_math_static_method(self, method_name, args):
methods = {
'pi': lambda: math.pi,
'e': lambda: math.e,
'random': lambda: random.random(),
'max': lambda items: max(items),
'min': lambda items: min(items),
'sum': lambda items: sum(items),
'average': lambda items: sum(items) / len(items),
'sin': lambda x: math.sin(x),
'cos': lambda x: math.cos(x),
'tan': lambda x: math.tan(x),
'log': lambda x: math.log(x)
}
if method_name not in methods:
raise SPLError(f"Math class has no static method '{method_name}'")
return methods[method_name](*args)
def _call_list_method(self, list_obj, method_name, args):
methods = {
'length': lambda: len(list_obj),
'append': lambda item: list_obj.append(item) or list_obj,
'prepend': lambda item: list_obj.insert(0, item) or list_obj,
'pop': lambda index=-1: list_obj.pop(index),
'remove': lambda item: list_obj.remove(item) or list_obj,
'reverse': lambda: list_obj.reverse() or list_obj,
'sort': lambda: list_obj.sort() or list_obj,
'contains': lambda item: item in list_obj,
'index': lambda item: list_obj.index(item) if item in list_obj else -1,
'slice': lambda start, end=None: list_obj[start:end] if end else list_obj[start:],
'join': lambda separator=',': separator.join(str(x) for x in list_obj),
'clear': lambda: list_obj.clear() or list_obj,
'copy': lambda: list_obj.copy()
}
if method_name not in methods:
raise SPLError(f"List has no method '{method_name}'")
try:
return methods[method_name](*args)
except (TypeError, ValueError) as e:
raise SPLError(f"Error in list.{method_name}: {str(e)}")
def _call_number_method(self, number_obj, method_name, args):
methods = {
'abs': lambda: abs(number_obj),
'round': lambda digits=0: round(number_obj, int(digits)),
'floor': lambda: math.floor(number_obj),
'ceil': lambda: math.ceil(number_obj),
'sqrt': lambda: math.sqrt(number_obj),
'pow': lambda exponent: number_obj ** exponent,
'tostring': lambda: str(number_obj),
'sign': lambda: 1 if number_obj > 0 else (-1 if number_obj < 0 else 0)
}
if method_name not in methods:
raise SPLError(f"Number has no method '{method_name}'")
try:
return methods[method_name](*args)
except (TypeError, ValueError) as e:
raise SPLError(f"Error in number.{method_name}: {str(e)}")
def _call_boolean_method(self, bool_obj, method_name, args):
methods = {
'tostring': lambda: str(bool_obj).lower(),
'tonumber': lambda: 1 if bool_obj else 0,
'not': lambda: not bool_obj
}
if method_name not in methods:
raise SPLError(f"Boolean has no method '{method_name}'")
try:
return methods[method_name](*args)
except TypeError:
raise SPLError(f"Wrong number of arguments for boolean.{method_name}")
def _execute_statements(self, statements):
result = None
for stmt in statements:
result = self.interpret(stmt)
return result
class BreakException(Exception): pass
# Global interpreter instance
global_interpreter = Interpreter()
def execute_spl_code(code):
global global_interpreter
try:
global_interpreter.output = [] # Clear previous output
lexer = Lexer(code)
tokens = lexer.tokenize()
parser = Parser(tokens)
ast = parser.parse()
result = global_interpreter.interpret(ast)
return {
'success': True,
'output': global_interpreter.output,
'result': result,
'error': None
}
except Exception as e:
return {
'success': False,
'output': global_interpreter.output,
'result': None,
'error': str(e)
}
print("SPL Interpreter loaded successfully!")
`;
// Global variables
let pyodide, codeEditor;
// Sample code examples - more concise examples
const examples = [
`x = 5;\nprint("Hello, World!");\nprint("x =", x);`,
`# Basic arithmetic\nx = 5; y = 10;\nresult = x + y * 2;\nprint("Result:", result);\n\nname = "World";\nprint("Hello", name);`,
`# Conditionals\nx = 15;\nif x > 10 {\n print("x is greater than 10");\n} else {\n print("x is not greater than 10");\n}`,
`# Loops\ncounter = 1;\nwhile counter <= 5 {\n print("Count:", counter);\n counter = counter + 1;\n}`,
`# Lists and for loops\nnumbers = [1, 2, 3, 4, 5];\nfor num in numbers {\n print("Number:", num);\n}\n\nfor i in range(3) {\n print("Range:", i);\n}`
];
// Initialize Pyodide and SPL interpreter
async function initializePyodide() {
try {
console.log("Loading Pyodide...");
pyodide = await loadPyodide();
console.log("Pyodide loaded, loading SPL interpreter...");
await pyodide.runPythonAsync(splInterpreterCode);
console.log("SPL interpreter loaded successfully");
return true;
} catch (error) {
console.error("Failed to initialize:", error);
return false;
}
}
// Initialize CodeMirror editor
function initializeEditor() {
codeEditor = CodeMirror.fromTextArea(document.getElementById('code-editor'), {
mode: 'python',
theme: 'monokai',
lineNumbers: true,
autoCloseBrackets: true,
matchBrackets: true,
indentUnit: 4,
tabSize: 4,
lineWrapping: true,
viewportMargin: Infinity
});
codeEditor.setValue(examples[0]);
}
// Execute SPL code with improved error handling
async function runCode() {
const runBtn = document.getElementById('run-btn');
const code = codeEditor.getValue().trim();
if (!code) {
addOutput("No code to execute!", "error");
return;
}
try {
// Update UI
runBtn.disabled = true;
runBtn.innerHTML = '<span class="btn-icon">⏳</span>Running...';
// Clear output and show running message
clearOutput(false);
addOutput(`> Running code...`, "info");
// Execute code via Pyodide
pyodide.globals.set('user_code', code);
const resultStr = pyodide.runPython(`
import json
result = execute_spl_code(user_code)
json.dumps(result)
`);
const result = JSON.parse(resultStr);
// Display results
if (result.error) {
addOutput(`Error: ${result.error}`, "error");
} else {
if (result.output?.length > 0) {
result.output.forEach(line => addOutput(line, "print"));
} else {
addOutput("✓ Code executed successfully (no output)", "info");
}
}
} catch (error) {
console.error("JavaScript error:", error);
addOutput(`JavaScript Error: ${error.message}`, "error");
} finally {
runBtn.disabled = false;
runBtn.innerHTML = '<span class="btn-icon">▶</span>Run Code';
}
}
// Utility functions for output management
function addOutput(text, type = "output") {
const output = document.getElementById('output');
const div = document.createElement('div');
const classMap = {
"error": "error-line",
"print": "print-line",
"info": "output-line",
"output": "output-line"
};
div.className = classMap[type] || "output-line";
div.textContent = text;
output.appendChild(div);
output.scrollTop = output.scrollHeight;
}
function clearOutput(clearWelcome = true) {
const output = document.getElementById('output');
if (clearWelcome) {
output.innerHTML = '';
} else {
// Keep welcome message, remove everything else
Array.from(output.children).forEach(child => {
if (!child.classList.contains('welcome-output')) {
child.remove();
}
});
}
}
function loadExample() {
const randomExample = examples[Math.floor(Math.random() * examples.length)];
codeEditor.setValue(randomExample);
addOutput("Example code loaded!", "info");
}
// Main initialization
async function main() {
const status = document.getElementById('status');
try {
status.textContent = "Loading Pyodide...";
const pyodideLoaded = await initializePyodide();
if (!pyodideLoaded) {
throw new Error("Failed to load Pyodide");
}
status.textContent = "Ready! Write your code and click Run.";
status.style.color = "#00ff00";
document.getElementById('run-btn').disabled = false;
console.log("SPL IDE ready!");
} catch (error) {
console.error("Initialization failed:", error);
status.innerHTML = `
<div style="color: #ff4444;">Error: ${error.message}</div>
<div style="color: #ffaa00; font-size: 12px; margin-top: 5px;">
Check browser console for details.
</div>
`;
}
}
// Event listeners setup
document.addEventListener('DOMContentLoaded', function() {
initializeEditor();
// Button events
document.getElementById('run-btn').addEventListener('click', runCode);
document.getElementById('clear-btn').addEventListener('click', () => clearOutput(true));
document.getElementById('example-btn').addEventListener('click', loadExample);
// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
e.preventDefault();
runCode();
}
});
main();
});