feat(v1.3.0): add else-if, shorthand operators, sqlite & net modules, builtins, and custom imports
This commit is contained in:
1 parent
243b52e2cb
commit
8a1ac0b814
8 files changed
+396
-65
No files matched your search
+1
-2
@@ -8,7 +8,7 @@ from lexer import Lexer
|
||||
from parser import Parser
|
||||
from evaluator import Evaluator
|
||||
|
||||
VERSION = "1.2.0 (Next-Gen Engine)"
|
||||
VERSION = "1.3.0 (Pro Edition)"
|
||||
AUTHOR = "Adam Eehan (Aira Group of Technology)"
|
||||
|
||||
ASCII_BANNER = f"""\033[1;36m
|
||||
@@ -27,7 +27,6 @@ ASCII_BANNER = f"""\033[1;36m
|
||||
"""
|
||||
|
||||
def is_balanced(code):
|
||||
# Check if { }, ( ), [ ] are balanced
|
||||
in_single_quote = False
|
||||
in_double_quote = False
|
||||
in_comment = False
|
||||
|
||||
+13
-4
@@ -115,6 +115,10 @@ class Evaluator:
|
||||
self.global_env.set("num", lambda x: float(x) if '.' in str(x) else int(x))
|
||||
self.global_env.set("input", lambda prompt="": input(prompt))
|
||||
self.global_env.set("range", lambda start, stop=None, step=1: list(range(int(start), int(stop), int(step))) if stop is not None else list(range(int(start))))
|
||||
self.global_env.set("min", lambda *args: min(args[0]) if len(args) == 1 and isinstance(args[0], (list, tuple)) else min(*args))
|
||||
self.global_env.set("max", lambda *args: max(args[0]) if len(args) == 1 and isinstance(args[0], (list, tuple)) else max(*args))
|
||||
self.global_env.set("abs", lambda x: abs(x))
|
||||
self.global_env.set("sum", lambda lst: sum(lst) if isinstance(lst, (list, tuple)) else lst)
|
||||
self.global_env.set("append", lambda lst, item: lst.append(item) or lst)
|
||||
self.global_env.set("pop", lambda lst, idx=-1: lst.pop(idx))
|
||||
self.global_env.set("split", lambda s, sep=" ": str(s).split(sep))
|
||||
@@ -147,8 +151,14 @@ class Evaluator:
|
||||
module_instance = BUILTIN_MODULES[mod_name]()
|
||||
env.set(mod_name, module_instance)
|
||||
return module_instance
|
||||
elif os.path.exists(mod_name):
|
||||
with open(mod_name, "r", encoding="utf-8") as f:
|
||||
|
||||
# File import check (.aira or .py)
|
||||
target_path = mod_name
|
||||
if not os.path.exists(target_path) and not target_path.endswith(".aira"):
|
||||
target_path = mod_name + ".aira"
|
||||
|
||||
if os.path.exists(target_path):
|
||||
with open(target_path, "r", encoding="utf-8") as f:
|
||||
code = f.read()
|
||||
from lexer import Lexer
|
||||
from parser import Parser
|
||||
@@ -156,7 +166,7 @@ class Evaluator:
|
||||
sub_ast = Parser(sub_tokens).parse()
|
||||
mod_env = Environment(parent=self.global_env)
|
||||
self.eval_node(sub_ast, mod_env)
|
||||
base_name = os.path.splitext(os.path.basename(mod_name))[0]
|
||||
base_name = os.path.splitext(os.path.basename(target_path))[0]
|
||||
aira_mod = AiraModule(base_name, mod_env.values)
|
||||
env.set(base_name, aira_mod)
|
||||
return aira_mod
|
||||
@@ -419,7 +429,6 @@ class Evaluator:
|
||||
if isinstance(callee, AiraFunction):
|
||||
return callee.call(self, args)
|
||||
elif isinstance(callee, AiraClass):
|
||||
# allow calling class directly as constructor ClassName(args)
|
||||
return callee.instantiate(self, args)
|
||||
elif callable(callee):
|
||||
return callee(*args)
|
||||
|
||||
+34
-29
@@ -1,35 +1,40 @@
|
||||
import re
|
||||
|
||||
TOKEN_TYPES = [
|
||||
("COMMENT", r"#.*"),
|
||||
("WHITESPACE", r"[ \t\r\n]+"),
|
||||
("NUMBER", r"\d+(\.\d+)?"),
|
||||
("STRING", r'("([^"\\]|\\.)*"|\'([^\'\\]|\\.)*\')'),
|
||||
("KEYWORD", r"\b(let|say|print|if|else|while|for|in|fn|return|import|load|use|true|false|null|and|or|not|try|catch|throw|class|new|this|break|continue)\b"),
|
||||
("IDENTIFIER", r"[a-zA-Z_][a-zA-Z0-9_]*"),
|
||||
("EQ_EQ", r"=="),
|
||||
("NOT_EQ", r"!="),
|
||||
("LTE", r"<="),
|
||||
("GTE", r">="),
|
||||
("ASSIGN", r"="),
|
||||
("PLUS", r"\+"),
|
||||
("MINUS", r"-"),
|
||||
("MUL", r"\*"),
|
||||
("DIV", r"/"),
|
||||
("MOD", r"%"),
|
||||
("LT", r"<"),
|
||||
("GT", r">"),
|
||||
("NOT", r"!"),
|
||||
("LPAREN", r"\("),
|
||||
("RPAREN", r"\)"),
|
||||
("LBRACE", r"\{"),
|
||||
("RBRACE", r"\}"),
|
||||
("LBRACKET", r"\["),
|
||||
("RBRACKET", r"\]"),
|
||||
("COLON", r":"),
|
||||
("SEMICOLON", r";"),
|
||||
("COMMA", r","),
|
||||
("DOT", r"\."),
|
||||
("COMMENT", r"#.*"),
|
||||
("WHITESPACE", r"[ \t\r\n]+"),
|
||||
("NUMBER", r"\d+(\.\d+)?"),
|
||||
("STRING", r'("([^"\\]|\\.)*"|\'([^\'\\]|\\.)*\')'),
|
||||
("KEYWORD", r"\b(let|say|print|if|else|while|for|in|fn|return|import|load|use|true|false|null|and|or|not|try|catch|throw|class|new|this|break|continue)\b"),
|
||||
("IDENTIFIER", r"[a-zA-Z_][a-zA-Z0-9_]*"),
|
||||
("PLUS_ASSIGN", r"\+="),
|
||||
("MINUS_ASSIGN", r"-="),
|
||||
("MUL_ASSIGN", r"\*="),
|
||||
("DIV_ASSIGN", r"/="),
|
||||
("MOD_ASSIGN", r"%="),
|
||||
("EQ_EQ", r"=="),
|
||||
("NOT_EQ", r"!="),
|
||||
("LTE", r"<="),
|
||||
("GTE", r">="),
|
||||
("ASSIGN", r"="),
|
||||
("PLUS", r"\+"),
|
||||
("MINUS", r"-"),
|
||||
("MUL", r"\*"),
|
||||
("DIV", r"/"),
|
||||
("MOD", r"%"),
|
||||
("LT", r"<"),
|
||||
("GT", r">"),
|
||||
("NOT", r"!"),
|
||||
("LPAREN", r"\("),
|
||||
("RPAREN", r"\)"),
|
||||
("LBRACE", r"\{"),
|
||||
("RBRACE", r"\}"),
|
||||
("LBRACKET", r"\["),
|
||||
("RBRACKET", r"\]"),
|
||||
("COLON", r":"),
|
||||
("SEMICOLON", r";"),
|
||||
("COMMA", r","),
|
||||
("DOT", r"\."),
|
||||
]
|
||||
|
||||
class Token:
|
||||
|
||||
+22
-8
@@ -41,11 +41,11 @@ class Parser:
|
||||
if self.match("SEMICOLON"):
|
||||
return None
|
||||
|
||||
# standalone block statement: `{ stmt1; stmt2; }`
|
||||
# Standalone block statement: `{ stmt1; stmt2; }`
|
||||
if tok.type == "LBRACE":
|
||||
return self.parse_block_or_statement()
|
||||
|
||||
# import / load / use statement: `import os;`, `import "math";`
|
||||
# import / load / use statement: `import os;`, `import "math";`, `import "helper.aira";`
|
||||
if tok.type in ("IMPORT", "LOAD", "USE"):
|
||||
self.pos += 1
|
||||
if self.current().type in ("STRING", "IDENTIFIER"):
|
||||
@@ -75,7 +75,7 @@ class Parser:
|
||||
self.match("SEMICOLON")
|
||||
return LetStatementNode(name_tok.value, expr, tok.line)
|
||||
|
||||
# if statement: `if (cond) { ... } else { ... }`
|
||||
# if statement: `if (cond) { ... } else if (cond2) { ... } else { ... }`
|
||||
if tok.type == "IF":
|
||||
self.pos += 1
|
||||
has_paren = self.match("LPAREN")
|
||||
@@ -85,7 +85,10 @@ class Parser:
|
||||
then_branch = self.parse_block_or_statement()
|
||||
else_branch = None
|
||||
if self.match("ELSE"):
|
||||
else_branch = self.parse_block_or_statement()
|
||||
if self.current().type == "IF":
|
||||
else_branch = self.parse_statement()
|
||||
else:
|
||||
else_branch = self.parse_block_or_statement()
|
||||
return IfStatementNode(cond, then_branch, else_branch, tok.line)
|
||||
|
||||
# while statement: `while (cond) { ... }`
|
||||
@@ -98,7 +101,7 @@ class Parser:
|
||||
body = self.parse_block_or_statement()
|
||||
return WhileStatementNode(cond, body, tok.line)
|
||||
|
||||
# for statement: `for item in items { ... }` or `for (item in items) { ... }` or `for (let item in items) { ... }`
|
||||
# for statement: `for item in items { ... }`
|
||||
if tok.type == "FOR":
|
||||
self.pos += 1
|
||||
has_paren = self.match("LPAREN")
|
||||
@@ -166,7 +169,6 @@ class Parser:
|
||||
methods = {}
|
||||
while self.current().type != "RBRACE" and self.current().type != "EOF":
|
||||
if self.match("FN") or self.current().type == "IDENTIFIER":
|
||||
# allow either `fn name()` or `name()`
|
||||
if self.tokens[self.pos - 1].type != "FN":
|
||||
m_name_tok = self.expect("IDENTIFIER")
|
||||
else:
|
||||
@@ -197,11 +199,23 @@ class Parser:
|
||||
self.match("SEMICOLON")
|
||||
return ReturnStatementNode(expr, tok.line)
|
||||
|
||||
# expression / assignment statement
|
||||
# expression / assignment / shorthand assignment statement
|
||||
expr = self.parse_expression()
|
||||
if self.match("ASSIGN"):
|
||||
assign_op = self.match("ASSIGN", "PLUS_ASSIGN", "MINUS_ASSIGN", "MUL_ASSIGN", "DIV_ASSIGN", "MOD_ASSIGN")
|
||||
if assign_op:
|
||||
val_expr = self.parse_expression()
|
||||
self.match("SEMICOLON")
|
||||
|
||||
if assign_op.type != "ASSIGN":
|
||||
bin_op_symbol = {
|
||||
"PLUS_ASSIGN": "+",
|
||||
"MINUS_ASSIGN": "-",
|
||||
"MUL_ASSIGN": "*",
|
||||
"DIV_ASSIGN": "/",
|
||||
"MOD_ASSIGN": "%"
|
||||
}[assign_op.type]
|
||||
val_expr = BinaryOpNode(expr, bin_op_symbol, val_expr, assign_op.line)
|
||||
|
||||
if isinstance(expr, IdentifierNode):
|
||||
return AssignStatementNode(expr.name, val_expr, tok.line)
|
||||
elif isinstance(expr, IndexAccessNode):
|
||||
|
||||
+122
-5
@@ -6,6 +6,8 @@ import json
|
||||
import random
|
||||
import hashlib
|
||||
import base64
|
||||
import socket
|
||||
import sqlite3
|
||||
import urllib.request
|
||||
import urllib.parse
|
||||
|
||||
@@ -19,6 +21,119 @@ class AiraModule:
|
||||
return self.methods[prop_name]
|
||||
raise AttributeError(f"AiraLang Module '{self.name}' has no method or property '{prop_name}'")
|
||||
|
||||
class AiraSQLiteDB:
|
||||
def __init__(self, db_path):
|
||||
self.db_path = db_path
|
||||
self.conn = sqlite3.connect(db_path)
|
||||
self.conn.row_factory = sqlite3.Row
|
||||
|
||||
def execute(self, sql, params=None):
|
||||
cursor = self.conn.cursor()
|
||||
if params:
|
||||
cursor.execute(sql, tuple(params) if isinstance(params, list) else (params,))
|
||||
else:
|
||||
cursor.execute(sql)
|
||||
self.conn.commit()
|
||||
return cursor.rowcount
|
||||
|
||||
def query(self, sql, params=None):
|
||||
cursor = self.conn.cursor()
|
||||
if params:
|
||||
cursor.execute(sql, tuple(params) if isinstance(params, list) else (params,))
|
||||
else:
|
||||
cursor.execute(sql)
|
||||
rows = cursor.fetchall()
|
||||
result = []
|
||||
for r in rows:
|
||||
result.append({k: r[k] for k in r.keys()})
|
||||
return result
|
||||
|
||||
def insert(self, table, data_dict):
|
||||
if not isinstance(data_dict, dict):
|
||||
raise TypeError("sqlite.insert requires a dictionary of column: value")
|
||||
columns = ", ".join(data_dict.keys())
|
||||
placeholders = ", ".join(["?"] * len(data_dict))
|
||||
sql = f"INSERT INTO {table} ({columns}) VALUES ({placeholders})"
|
||||
return self.execute(sql, list(data_dict.values()))
|
||||
|
||||
def close(self):
|
||||
self.conn.close()
|
||||
return True
|
||||
|
||||
def get(self, prop_name):
|
||||
if hasattr(self, prop_name):
|
||||
return getattr(self, prop_name)
|
||||
raise AttributeError(f"SQLite DB object has no property '{prop_name}'")
|
||||
|
||||
def create_sqlite_module():
|
||||
def open_db(path):
|
||||
db = AiraSQLiteDB(path)
|
||||
return AiraModule("sqlite_conn", {
|
||||
"execute": db.execute,
|
||||
"query": db.query,
|
||||
"insert": db.insert,
|
||||
"close": db.close
|
||||
})
|
||||
|
||||
return AiraModule("sqlite", {
|
||||
"open": open_db,
|
||||
"connect": open_db
|
||||
})
|
||||
|
||||
def create_net_module():
|
||||
def scan_port(host, port, timeout=2.0):
|
||||
try:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.settimeout(float(timeout))
|
||||
result = s.connect_ex((str(host), int(port)))
|
||||
s.close()
|
||||
return result == 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def scan_ports(host, start_port, end_port, timeout=1.0):
|
||||
open_ports = []
|
||||
for p in range(int(start_port), int(end_port) + 1):
|
||||
if scan_port(host, p, timeout):
|
||||
open_ports.append(p)
|
||||
return open_ports
|
||||
|
||||
def resolve(domain):
|
||||
try:
|
||||
return socket.gethostbyname(str(domain))
|
||||
except Exception as e:
|
||||
return f"Error: {e}"
|
||||
|
||||
def local_ip():
|
||||
try:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
s.connect(("8.8.8.8", 80))
|
||||
ip = s.getsockname()[0]
|
||||
s.close()
|
||||
return ip
|
||||
except Exception:
|
||||
return "127.0.0.1"
|
||||
|
||||
def tcp_send(host, port, message, timeout=5.0):
|
||||
try:
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
s.settimeout(float(timeout))
|
||||
s.connect((str(host), int(port)))
|
||||
s.sendall(str(message).encode('utf-8'))
|
||||
data = s.recv(4096)
|
||||
s.close()
|
||||
return data.decode('utf-8', errors='ignore')
|
||||
except Exception as e:
|
||||
return f"Socket Error: {e}"
|
||||
|
||||
return AiraModule("net", {
|
||||
"scan_port": scan_port,
|
||||
"scan_ports": scan_ports,
|
||||
"resolve": resolve,
|
||||
"local_ip": local_ip,
|
||||
"tcp_send": tcp_send
|
||||
})
|
||||
|
||||
def create_file_module():
|
||||
def read_file(path):
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
@@ -117,7 +232,7 @@ def create_json_module():
|
||||
|
||||
def create_http_module():
|
||||
def get(url, headers=None):
|
||||
req_headers = {"User-Agent": "AiraLang/1.1 (Termux; Android)"}
|
||||
req_headers = {"User-Agent": "AiraLang/1.3 (Termux; Android)"}
|
||||
if isinstance(headers, dict):
|
||||
req_headers.update(headers)
|
||||
req = urllib.request.Request(url, headers=req_headers)
|
||||
@@ -128,7 +243,7 @@ def create_http_module():
|
||||
raise RuntimeError(f"HTTP GET Error: {e}")
|
||||
|
||||
def post(url, data_payload=None, headers=None):
|
||||
req_headers = {"User-Agent": "AiraLang/1.1 (Termux; Android)"}
|
||||
req_headers = {"User-Agent": "AiraLang/1.3 (Termux; Android)"}
|
||||
if isinstance(headers, dict):
|
||||
req_headers.update(headers)
|
||||
encoded_data = None
|
||||
@@ -145,7 +260,7 @@ def create_http_module():
|
||||
raise RuntimeError(f"HTTP POST Error: {e}")
|
||||
|
||||
def download(url, dest_path):
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "AiraLang/1.1"})
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "AiraLang/1.3"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as response, open(dest_path, "wb") as out_file:
|
||||
out_file.write(response.read())
|
||||
@@ -155,7 +270,7 @@ def create_http_module():
|
||||
|
||||
def status(url):
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "AiraLang/1.1"})
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "AiraLang/1.3"})
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
return response.getcode()
|
||||
except urllib.error.HTTPError as e:
|
||||
@@ -216,5 +331,7 @@ BUILTIN_MODULES = {
|
||||
"json": create_json_module,
|
||||
"http": create_http_module,
|
||||
"crypto": create_crypto_module,
|
||||
"string": create_string_module
|
||||
"string": create_string_module,
|
||||
"sqlite": create_sqlite_module,
|
||||
"net": create_net_module
|
||||
}
|
||||
Reference in new issue
Block a user