-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathel.py
More file actions
304 lines (263 loc) · 9.88 KB
/
el.py
File metadata and controls
304 lines (263 loc) · 9.88 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
import sys
import argparse
from easy_lang import run_file, lexer, Parser, Interpreter
def repl():
print("EasyLang REPL (Type 'exit' or 'quit' to leave)")
interpreter = Interpreter()
while True:
line = input(">>> ")
if line.strip() in ("exit", "quit"):
break
try:
tokens = list(lexer(line))
parser = Parser(tokens)
ast = parser.parse()
interpreter.interpret(ast)
except Exception as e:
print("Error:", e)
def print_tokens(path):
with open(path, encoding='utf-8') as f:
source = f.read()
tokens = list(lexer(source))
for t in tokens:
print(t)
def print_ast(path):
with open(path, encoding='utf-8') as f:
source = f.read()
tokens = list(lexer(source))
parser = Parser(tokens)
ast = parser.parse()
print(ast)
def analyze_program(ast):
warnings = []
defined_funcs = {}
called_funcs = set()
for node in ast:
if isinstance(node, tuple) and node[0] == 'func':
_, name, params, body, line, col = node
defined_funcs[name] = (params, body, line)
for node in ast:
find_called_funcs(node, called_funcs)
for func in defined_funcs:
if func not in called_funcs and func != "main":
warnings.append(f"Function '{func}' is defined but never used")
for node in ast:
if isinstance(node, tuple) and node[0] == 'func':
_, name, params, body, line, col = node
warnings.extend(analyze_function(name, params, body, line))
return warnings
def find_called_funcs(node, called_funcs):
if not isinstance(node, tuple):
return
if node[0] == 'call':
called_funcs.add(node[1])
for child in node[2:]:
if isinstance(child, list):
for item in child:
find_called_funcs(item, called_funcs)
elif isinstance(child, tuple):
find_called_funcs(child, called_funcs)
var_types = {}
def analyze_function(name, params, body, func_line):
warnings = []
assigned, used = set(), set()
params_set = set(params)
local_types = {}
collect_vars_from_statements(body, assigned, used, name, warnings, local_types)
unused = (assigned - used) - params_set
for var in sorted(unused):
warnings.append(f"{name}(): variable '{var}' assigned but never used")
for var in assigned:
if var in params_set:
warnings.append(f"{name}(): variable '{var}' shadows parameter")
for stmt in body:
if isinstance(stmt, tuple) and stmt[0] == 'for':
block = stmt[4]
seen_break = False
for inner in block:
if not isinstance(inner, tuple):
continue
if inner[0] == 'break':
seen_break = True
elif seen_break:
line = inner[-2]
warnings.append(f"{name}(): unreachable code after break at line {line}")
break
if not function_has_return(body):
warnings.append(f"{name}(): function has no return statement")
return warnings
def function_has_return(body):
for stmt in body:
if not isinstance(stmt, tuple):
continue
t = stmt[0]
if t == 'return':
return True
elif t in ('if', 'while', 'for'):
if t == 'if':
_, cond, then_branch, else_branch, line, col = stmt
if function_has_return(then_branch):
return True
if else_branch and function_has_return(else_branch):
return True
elif t == 'while':
_, cond, block, line, col = stmt
if function_has_return(block):
return True
elif t == 'for':
_, loop_var, start_expr, end_expr, block, line, col = stmt
if function_has_return(block):
return True
return False
def collect_vars_from_statements(stmts, assigned, used, fname, warnings, local_types):
for node in stmts:
if not isinstance(node, tuple):
continue
t = node[0]
if t == 'read':
_, var, type_name, line, col = node
assigned.add(var)
local_types[var] = type_name
if t == 'assign':
_, var, expr, line, col = node
assigned.add(var)
collect_vars_from_expr(expr, used)
if var in local_types:
expected = local_types[var]
actual_kind = expr[0]
if expected == "int" and actual_kind == "string":
warnings.append(
f"{fname}(): Type mismatch -> '{var}' expected int, got string at line {line}"
)
elif expected == "string" and actual_kind == "number":
warnings.append(
f"{fname}(): Type mismatch -> '{var}' expected string, got number at line {line}"
)
elif t == 'for':
_, loop_var, start_expr, end_expr, block, line, col = node
assigned.add(loop_var)
collect_vars_from_expr(start_expr, used)
collect_vars_from_expr(end_expr, used)
collect_vars_from_statements(block, assigned, used, fname, warnings, local_types)
elif t == 'if':
_, condition, then_branch, else_branch, line, col = node
collect_vars_from_expr(condition, used)
collect_vars_from_statements(then_branch, assigned, used, fname, warnings, local_types)
if else_branch:
collect_vars_from_statements(else_branch, assigned, used, fname, warnings, local_types)
elif t == 'while':
_, condition, block, line, col = node
collect_vars_from_expr(condition, used)
collect_vars_from_statements(block, assigned, used, fname, warnings, local_types)
elif t in ('print','expr','return'):
_, expr, line, col = node
collect_vars_from_expr(expr, used)
def collect_vars_from_expr(expr, used):
if not isinstance(expr, tuple):
return
t = expr[0]
if t == 'var':
_, name, line, col = expr
used.add(name)
elif t in ('number','string','boolean'):
return
elif t in ('neg','logicnot'):
_, subexpr, line, col = expr
collect_vars_from_expr(subexpr, used)
elif t in ('binop','compare','logicop'):
_, op, left, right, line, col = expr
collect_vars_from_expr(left, used)
collect_vars_from_expr(right, used)
elif t == 'call':
_, fname, args, kwargs, line, col = expr
for a in args:
collect_vars_from_expr(a, used)
for v in kwargs.values():
collect_vars_from_expr(v, used)
elif t == 'list':
_, items, line, col = expr
for item in items:
collect_vars_from_expr(item, used)
elif t == 'dict':
_, pairs, line, col = expr
for key, val_expr in pairs:
collect_vars_from_expr(val_expr, used)
elif t == 'index':
_, container_expr, idx_expr, line, col = expr
collect_vars_from_expr(container_expr, used)
collect_vars_from_expr(idx_expr, used)
elif t == 'method':
_, obj_expr, meth, args, kwargs, line, col = expr
collect_vars_from_expr(obj_expr, used)
for a in args:
collect_vars_from_expr(a, used)
for v in kwargs.values():
collect_vars_from_expr(v, used)
def lint_file(path):
print(f"Linting {path}...\n")
try:
with open(path) as f: src = f.read()
tokens = list(lexer(src))
ast = Parser(tokens).parse()
except Exception as e:
print(f"Syntax error: {e}"); return
warnings = analyze_program(ast)
if warnings:
print("\n⚠ Lint warnings:")
for w in warnings: print(" -", w)
else:
print("✔ No lint issues found")
VERSION = '0.1.2'
AUTHOR = 'GreenBugX(0xNA)'
DESCRIPTION = (
'EasyLang is a compact educational scripting language whose syntax reads like English.\n'
'It is optimized for clarity and teaching: you can write programs using short English phrases instead of dense punctuation.'
)
def print_about():
print(f"""
=== EasyLang ===
{DESCRIPTION}
Version: {VERSION}
Author: {AUTHOR}
License: MIT
Website: https://easylang.dedyn.io
Contact: greenbugx@proton.me
""")
def main():
parser = argparse.ArgumentParser(
prog="el",
description=DESCRIPTION,
epilog=f"Author: {AUTHOR}\nVersion: {VERSION}"
)
parser.add_argument('file', nargs='?', help="Path to .elang file to execute")
parser.add_argument('--version', action='store_true', help="Show interpreter version and exit")
parser.add_argument('--about', action='store_true', help="Show full interpreter/about info and exit")
parser.add_argument('--repl', action='store_true', help="Start interactive EasyLang shell")
parser.add_argument('--lint', metavar="FILE", help="Check for syntax/style issues")
parser.add_argument('--tokens', metavar="FILE", help="Print all tokens from file")
parser.add_argument('--ast', metavar="FILE", help="Print AST from file")
args = parser.parse_args()
if args.version:
print(f"EasyLang version {VERSION} by {AUTHOR}")
sys.exit(0)
if args.about:
print_about()
sys.exit(0)
if args.repl:
repl()
sys.exit(0)
if args.tokens:
print_tokens(args.tokens)
sys.exit(0)
if args.ast:
print_ast(args.ast)
sys.exit(0)
if args.lint:
lint_file(args.lint)
sys.exit(0)
if not args.file:
print(f"\n=== EasyLang CLI ===\n{DESCRIPTION}\nAuthor: {AUTHOR}\nVersion: {VERSION}\nUsage: el <filename.elang>\nUse --help for more options.\n")
sys.exit(0)
run_file(args.file)
if __name__ == "__main__":
main()