commit 243b52e2cb819f0b09a4b6b69a7d7634a55f24e7 Author: Adam Eehan Date: Sun Aug 30 12:48:17 2026 +0530 feat: Initial release of AiraLang (v1.2.0 Next-Gen Engine) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f24c547 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +__pycache__/ +*.py[cod] +*$py.class +.DS_Store +*.tmp +*.log diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..8dd978c --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Adam Eehan (Aira Group of Technology) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..68bb38d --- /dev/null +++ b/README.md @@ -0,0 +1,113 @@ +# ๐ŸŒŸ AiraLang (v1.2.0 Next-Gen Engine) +> **The High-Performance, Lightweight & Expressive Programming Language for Creators & Developers** +> **Author & Creator:** Adam Eehan (Founder & CEO, Aira Group of Technology) ๐Ÿ‘‘ + +--- + +## โšก Introduction +`AiraLang` is an open-source, dynamic, and expressive scripting language engineered from scratch with a focus on simplicity, developer freedom, high speed, and native systems/cybersecurity capabilities. + +--- + +## ๐Ÿš€ Quick Start in Termux / Linux + +### 1. Interactive REPL Shell +Launch the live interactive REPL anytime by typing: +```bash +airalang +``` + +### 2. Run an AiraLang Script +```bash +airalang script.aira +``` + +--- + +## ๐Ÿ’ป Syntax & Features Guide + +### 1. Variables & Output +```aira +say "Hello, World!"; +let name = "Adam Boss"; +let power = 100; +say "Creator: " + name; +``` + +### 2. For..In Loops & Range +```aira +let tools = ["Termux", "AiraLang", "CyberGuard"]; +for tool in tools { + say "Tool: " + tool; +} + +# Looping using range(start, end) +for i in range(1, 6) { + if (i == 3) { + continue; # skip 3 + } + say "Count: " + i; +} +``` + +### 3. Object-Oriented Programming (OOP) +```aira +class Agent { + fn init(name, role) { + this.name = name; + this.role = role; + } + + fn introduce() { + return "Agent: " + this.name + " (" + this.role + ")"; + } +} + +let adam = new Agent("Adam Eehan", "CEO"); +say adam.introduce(); +``` + +### 4. Exception Handling (Try / Catch / Throw) +```aira +try { + throw "Security Access Denied"; +} catch (err) { + say "Caught Exception: " + err; +} +``` + +### 5. Native String & List Methods +```aira +let text = " aira technology "; +say text.trim().upper(); # "AIRA TECHNOLOGY" + +let langs = ["C++", "Python"]; +langs.push("AiraLang"); +say langs.join(" -> "); # "C++ -> Python -> AiraLang" +``` + +### 6. Standard Library Modules +```aira +# Network / HTTP +import "http"; +let res = http.get("https://httpbin.org/get"); + +# Cryptography & Hashing +import "crypto"; +let hash = crypto.sha256("admin123"); +let b64 = crypto.b64encode("secret"); + +# System & OS +import "os"; +let out = os.cmd("uname -a"); + +# Math & Time & JSON +import "math"; +import "time"; +import "json"; +``` + +--- + +## ๐Ÿ“œ License +MIT Open Source License ยฉ 2026 Adam Eehan (Aira Group of Technology). diff --git a/bin/airalang b/bin/airalang new file mode 100755 index 0000000..b894f52 --- /dev/null +++ b/bin/airalang @@ -0,0 +1,9 @@ +#!/data/data/com.termux/files/usr/bin/python3 +import sys +import os + +sys.path.insert(0, "/data/data/com.termux/files/home/airalang/src") +import cli + +if __name__ == "__main__": + cli.main() diff --git a/examples/hello.aira b/examples/hello.aira new file mode 100644 index 0000000..0725e40 --- /dev/null +++ b/examples/hello.aira @@ -0,0 +1,35 @@ +# =================================================== +# ๐ŸŒŸ AiraLang Hello World & Feature Test +# ๐Ÿ‘‘ Creator: Adam Eehan (Aira Group of Technology) +# =================================================== + +say "๐Ÿš€ Hello, World from AiraLang Engine!"; +say "======================================"; + +let creator = "Adam Boss"; +let role = "Founder & CEO, Aira Group of Technology"; +let version = 1.0; + +say "๐Ÿ‘‘ Author: " + creator; +say "๐Ÿ’ผ Role: " + role; +say "โšก Version: " + version; + +# Math Operations +let a = 50; +let b = 25; +let sum = a + b; +say "๐Ÿ”ข Math Check (50 + 25): " + sum; + +# Conditional Logic +if (sum >= 75) { + say "โœ… Status: AiraLang Core Engine is 100% Online & Functional!"; +} else { + say "โŒ Status: Error"; +} + +# Function Definition & Execution +fn greet(name) { + return "๐Ÿ”ฅ Welcome to your own programming language, " + name + "! ๐Ÿ‘‘"; +} + +say greet(creator); diff --git a/examples/test_advanced_features.aira b/examples/test_advanced_features.aira new file mode 100644 index 0000000..fc3178e --- /dev/null +++ b/examples/test_advanced_features.aira @@ -0,0 +1,101 @@ +# ========================================================== +# ๐ŸŒŸ AiraLang v1.2.0 Advanced Engine Feature Test +# ๐Ÿ‘‘ Creator: Adam Eehan (Aira Group of Technology) +# ========================================================== + +say "๐Ÿ”ฅ AiraLang v1.2.0 Next-Gen Features Test Starting..."; +say "======================================================"; + +# 1. Testing for..in loops with break and continue +say "[1] Testing For..In Loops & Range:"; +let fruits = ["Apple", "Mango", "Banana", "Orange"]; +for f in fruits { + say " ๐Ÿ‘‰ Fruit: " + f; +} + +say " Looping through range(1, 5):"; +for i in range(1, 6) { + if (i == 3) { + say " โšก Skipping 3 (continue)"; + continue; + } + say " ๐Ÿ”ข Number: " + i; +} + +# 2. Testing String & List Methods +say "------------------------------------------------------"; +say "[2] Testing Native String & List Methods:"; +let greeting = " aira technology group "; +say " Original : '" + greeting + "'"; +say " Trimmed : '" + greeting.trim() + "'"; +say " Upper : " + greeting.trim().upper(); +say " Length : " + greeting.trim().length; + +let langs = ["C++", "Python"]; +langs.push("AiraLang"); +say " Updated List: " + langs.join(" -> "); +say " Contains Python? " + langs.contains("Python"); + +# 3. Testing Try..Catch & Throw +say "------------------------------------------------------"; +say "[3] Testing Exception Handling (Try / Catch / Throw):"; +try { + say " Trying risky operation..."; + throw "Fatal Memory Overflow Exception (Simulated)"; + say " This line should never print!"; +} catch (err) { + say " ๐Ÿ›ก๏ธ Caught Exception Successfully: " + err; +} + +# 4. Testing Object-Oriented Programming (OOP - Classes & Instances) +say "------------------------------------------------------"; +say "[4] Testing OOP (Classes, Instances, This, Methods):"; +class Agent { + fn init(name, rank, power) { + this.name = name; + this.rank = rank; + this.power = power; + } + + fn introduce() { + return "๐Ÿ‘‘ Agent " + this.name + " | Rank: " + this.rank + " | Power: " + this.power; + } + + fn boost(amount) { + this.power = this.power + amount; + say " โšก Power boosted! New power: " + this.power; + } +} + +let boss = new Agent("Adam Eehan", "CEO & AI Architect", 100); +say " " + boss.introduce(); +boss.boost(50); +say " " + boss.introduce(); + +# 5. Testing Crypto / Hash Module +say "------------------------------------------------------"; +say "[5] Testing Built-in Crypto Module:"; +import "crypto"; +let secret = "AdamBoss_AiraTech_2026"; +let hash_val = crypto.sha256(secret); +let b64_val = crypto.b64encode(secret); +say " Secret String : " + secret; +say " SHA-256 Hash : " + hash_val; +say " Base64 Encode : " + b64_val; +say " Base64 Decode : " + crypto.b64decode(b64_val); + +# 6. Testing HTTP Module (Status check) +say "------------------------------------------------------"; +say "[6] Testing HTTP Module:"; +import "http"; +let test_url = "https://httpbin.org/get"; +try { + say " Connecting to " + test_url + "..."; + let status_code = http.status(test_url); + say " HTTP Response Status: " + status_code; +} catch (net_err) { + say " Network offline or error handled: " + net_err; +} + +say "======================================================"; +say "โœ… ALL ADVANCED FEATURES TESTED & 100% OPERATIONAL! ๐Ÿš€"; diff --git a/examples/test_modules.aira b/examples/test_modules.aira new file mode 100644 index 0000000..025b3ba --- /dev/null +++ b/examples/test_modules.aira @@ -0,0 +1,60 @@ +# =================================================== +# [*] AiraLang v1.1.0 Standard Library & Modules Test +# [*] Author: Adam Eehan (Aira Group of Technology) +# =================================================== + +say "[*] Testing Built-in Standard Library Modules..."; +say "-----------------------------------------------"; + +# 1. Math Module Test +import "math"; +let sq = math.sqrt(64); +let rnd = math.random(1, 100); +say "[+] Math Sqrt(64) : " + sq; +say "[+] Math Random(1-100) : " + rnd; +say "[+] Math PI : " + math.pi; + +# 2. Time Module Test +import "time"; +let current_time = time.now(); +say "[+] Current Timestamp : " + current_time; + +# 3. OS Module Test (Terminal commands) +import "os"; +let kernel = os.cmd("uname -o"); +let user_dir = os.cwd(); +say "[+] OS Kernel : " + kernel; +say "[+] Current Directory : " + user_dir; + +# 4. File Module Test +import "file"; +let test_file = "aira_temp.txt"; +file.write(test_file, "AiraLang File I/O Engine Working!"); +let read_back = file.read(test_file); +say "[+] File Read Result : " + read_back; +file.delete(test_file); +say "[+] Temporary File Cleaned Up!"; + +# 5. Data Structures (Lists & Dictionaries) +let profile = { + "name": "Adam Boss", + "role": "Founder & CEO", + "power": 100 +}; +say "[+] Profile Name : " + profile["name"]; +say "[+] Profile Role : " + profile["role"]; + +let tools = ["AiraLang", "Termux", "CyberSecurity"]; +say "[+] First Tool : " + tools[0]; +append(tools, "NeuralEngine"); +say "[+] Updated Tools List : " + tools; + +# 6. JSON Module Test +import "json"; +let raw_json = '{"project": "AiraLang", "version": "1.1.0", "status": "Ready"}'; +let parsed = json.parse(raw_json); +say "[+] JSON Parsed Project : " + parsed["project"]; +say "[+] JSON Parsed Version : " + parsed["version"]; + +say "-----------------------------------------------"; +say "[+] ALL BASIC MODULES TESTED & 100% OPERATIONAL!"; diff --git a/install.sh b/install.sh new file mode 100755 index 0000000..596539e --- /dev/null +++ b/install.sh @@ -0,0 +1,59 @@ +#!/bin/bash +# ============================================================= +# ๐ŸŒŸ AiraLang Global Installer for Termux & Linux +# ๐Ÿ‘‘ Creator: Adam Eehan (Aira Group of Technology) +# ============================================================= + +set -e + +echo -e "\033[1;36m" +echo " ___ _ __ " +echo " / | (_)________ _/ / ____ _____ ____ _" +echo " / /| | / / ___/ __ \`/ / / __ \`/ __ \/ __ \`/" +echo " / ___ |/ / / / /_/ / /___/ /_/ / / / / /_/ / " +echo "/_/ |_/_/_/ \\__,_/_____/\\__,_/_/ /_/\\__, / " +echo " /____/ " +echo -e "\033[0m" +echo -e "\033[1;32m[*] Installing AiraLang (v1.2.0 Next-Gen Engine)...\033[0m" + +# Target installation directory +INSTALL_DIR="$HOME/.airalang" +BIN_DIR="" + +if [ -d "/data/data/com.termux/files/usr/bin" ]; then + BIN_DIR="/data/data/com.termux/files/usr/bin" +elif [ -d "$HOME/.local/bin" ]; then + BIN_DIR="$HOME/.local/bin" +elif [ -d "/usr/local/bin" ] && [ -w "/usr/local/bin" ]; then + BIN_DIR="/usr/local/bin" +else + BIN_DIR="$HOME/bin" + mkdir -p "$BIN_DIR" +fi + +echo -e "\033[1;34m[*] Target Binary Path: $BIN_DIR/airalang\033[0m" + +# Create symlink / launcher +cat << 'EOF' > "$BIN_DIR/airalang" +#!/data/data/com.termux/files/usr/bin/python3 +import sys +import os + +INSTALL_PATH = os.path.expanduser("~/.airalang/src") +LOCAL_PATH = "/data/data/com.termux/files/home/airalang/src" + +if os.path.exists(LOCAL_PATH): + sys.path.insert(0, LOCAL_PATH) +elif os.path.exists(INSTALL_PATH): + sys.path.insert(0, INSTALL_PATH) + +import cli + +if __name__ == "__main__": + cli.main() +EOF + +chmod +x "$BIN_DIR/airalang" + +echo -e "\033[1;32m[+] AiraLang Successfully Installed! ๐Ÿš€\033[0m" +echo -e "\033[1;37m[*] Run \033[1;33mairalang\033[0m to start the REPL, or \033[1;33mairalang \033[0m to run a file.\033[0m" diff --git a/src/ast_nodes.py b/src/ast_nodes.py new file mode 100644 index 0000000..881526e --- /dev/null +++ b/src/ast_nodes.py @@ -0,0 +1,170 @@ +class ASTNode: + pass + +class ProgramNode(ASTNode): + def __init__(self, statements): + self.statements = statements + +class ImportStatementNode(ASTNode): + def __init__(self, module_name, line): + self.module_name = module_name + self.line = line + +class SayStatementNode(ASTNode): + def __init__(self, expressions, line): + self.expressions = expressions + self.line = line + +class LetStatementNode(ASTNode): + def __init__(self, name, expression, line): + self.name = name + self.expression = expression + self.line = line + +class AssignStatementNode(ASTNode): + def __init__(self, name, expression, line): + self.name = name + self.expression = expression + self.line = line + +class IndexAssignStatementNode(ASTNode): + def __init__(self, target, index, expression, line): + self.target = target + self.index = index + self.expression = expression + self.line = line + +class MemberAssignStatementNode(ASTNode): + def __init__(self, target, member, expression, line): + self.target = target + self.member = member + self.expression = expression + self.line = line + +class IfStatementNode(ASTNode): + def __init__(self, condition, then_branch, else_branch, line): + self.condition = condition + self.then_branch = then_branch + self.else_branch = else_branch + self.line = line + +class WhileStatementNode(ASTNode): + def __init__(self, condition, body, line): + self.condition = condition + self.body = body + self.line = line + +class ForInStatementNode(ASTNode): + def __init__(self, var_name, iterable, body, line): + self.var_name = var_name + self.iterable = iterable + self.body = body + self.line = line + +class TryCatchStatementNode(ASTNode): + def __init__(self, try_body, error_var, catch_body, line): + self.try_body = try_body + self.error_var = error_var + self.catch_body = catch_body + self.line = line + +class ThrowStatementNode(ASTNode): + def __init__(self, expression, line): + self.expression = expression + self.line = line + +class BreakStatementNode(ASTNode): + def __init__(self, line): + self.line = line + +class ContinueStatementNode(ASTNode): + def __init__(self, line): + self.line = line + +class ClassDefNode(ASTNode): + def __init__(self, name, methods, line): + self.name = name + self.methods = methods + self.line = line + +class BlockNode(ASTNode): + def __init__(self, statements): + self.statements = statements + +class FunctionDefNode(ASTNode): + def __init__(self, name, params, body, line): + self.name = name + self.params = params + self.body = body + self.line = line + +class ReturnStatementNode(ASTNode): + def __init__(self, expression, line): + self.expression = expression + self.line = line + +class ExpressionStatementNode(ASTNode): + def __init__(self, expression): + self.expression = expression + +class BinaryOpNode(ASTNode): + def __init__(self, left, op, right, line): + self.left = left + self.op = op + self.right = right + self.line = line + +class UnaryOpNode(ASTNode): + def __init__(self, op, right, line): + self.op = op + self.right = right + self.line = line + +class LiteralNode(ASTNode): + def __init__(self, value, type_, line): + self.value = value + self.type = type_ + self.line = line + +class IdentifierNode(ASTNode): + def __init__(self, name, line): + self.name = name + self.line = line + +class ThisNode(ASTNode): + def __init__(self, line): + self.line = line + +class NewInstanceNode(ASTNode): + def __init__(self, class_name, arguments, line): + self.class_name = class_name + self.arguments = arguments + self.line = line + +class FunctionCallNode(ASTNode): + def __init__(self, callee, arguments, line): + self.callee = callee + self.arguments = arguments + self.line = line + +class MemberAccessNode(ASTNode): + def __init__(self, target, member, line): + self.target = target + self.member = member + self.line = line + +class IndexAccessNode(ASTNode): + def __init__(self, target, index, line): + self.target = target + self.index = index + self.line = line + +class ListNode(ASTNode): + def __init__(self, elements, line): + self.elements = elements + self.line = line + +class DictNode(ASTNode): + def __init__(self, pairs, line): + self.pairs = pairs + self.line = line diff --git a/src/cli.py b/src/cli.py new file mode 100755 index 0000000..604749a --- /dev/null +++ b/src/cli.py @@ -0,0 +1,161 @@ +#!/data/data/com.termux/files/usr/bin/python3 +import sys +import os + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from lexer import Lexer +from parser import Parser +from evaluator import Evaluator + +VERSION = "1.2.0 (Next-Gen Engine)" +AUTHOR = "Adam Eehan (Aira Group of Technology)" + +ASCII_BANNER = f"""\033[1;36m + ___ _ __ + / | (_)________ _/ / ____ _____ ____ _ + / /| | / / ___/ __ `/ / / __ `/ __ \\/ __ `/ + / ___ |/ / / / /_/ / /___/ /_/ / / / / /_/ / +/_/ |_/_/_/ \\__,_/_____/\\__,_/_/ /_/\\__, / + /____/ +\033[0m\033[1;30m---------------------------------------------------\033[0m + \033[1;32m[+]\033[0m \033[1;37mEngine:\033[0m AiraLang v{VERSION} + \033[1;34m[*]\033[0m \033[1;37mCreator:\033[0m {AUTHOR} + \033[1;33m[!]\033[0m Multiline support: open \033[1;32m{{\033[0m will continue on next line. + \033[1;33m[!]\033[0m Type \033[1;31m'exit'\033[0m or \033[1;31m'quit'\033[0m to close REPL. +\033[1;30m---------------------------------------------------\033[0m +""" + +def is_balanced(code): + # Check if { }, ( ), [ ] are balanced + in_single_quote = False + in_double_quote = False + in_comment = False + + braces = 0 + parens = 0 + brackets = 0 + + i = 0 + while i < len(code): + c = code[i] + + if in_comment: + if c == '\n': + in_comment = False + i += 1 + continue + + if c == '#' and not in_single_quote and not in_double_quote: + in_comment = True + i += 1 + continue + + if c == '"' and not in_single_quote: + if i > 0 and code[i-1] == '\\': + pass + else: + in_double_quote = not in_double_quote + i += 1 + continue + + if c == "'" and not in_double_quote: + if i > 0 and code[i-1] == '\\': + pass + else: + in_single_quote = not in_single_quote + i += 1 + continue + + if not in_single_quote and not in_double_quote: + if c == '{': braces += 1 + elif c == '}': braces -= 1 + elif c == '(': parens += 1 + elif c == ')': parens -= 1 + elif c == '[': brackets += 1 + elif c == ']': brackets -= 1 + + i += 1 + + return (braces <= 0 and parens <= 0 and brackets <= 0 and not in_single_quote and not in_double_quote) + +def run_code(source_code, evaluator=None): + if evaluator is None: + evaluator = Evaluator() + try: + lexer = Lexer(source_code) + tokens = lexer.tokenize() + parser = Parser(tokens) + ast = parser.parse() + return evaluator.eval(ast) + except SyntaxError as e: + print(f"\033[1;31m[!] SyntaxError:\033[0m {e}") + except NameError as e: + print(f"\033[1;31m[!] NameError:\033[0m {e}") + except TypeError as e: + print(f"\033[1;31m[!] TypeError:\033[0m {e}") + except Exception as e: + print(f"\033[1;31m[!] Error:\033[0m {e}") + +def run_file(filepath): + if not os.path.exists(filepath): + print(f"\033[1;31m[!] Error: File '{filepath}' not found.\033[0m") + sys.exit(1) + with open(filepath, "r", encoding="utf-8") as f: + code = f.read() + run_code(code) + +def start_repl(): + print(ASCII_BANNER) + evaluator = Evaluator() + buffer = [] + + while True: + try: + if not buffer: + prompt = "\033[1;35m[aira]\033[0m \033[1;32mโฏโฏ\033[0m " + else: + prompt = "\033[1;33m[....]\033[0m \033[1;32mยทยท\033[0m " + + line = input(prompt) + + if not buffer and line.strip() in ("exit", "quit"): + print("\033[1;33m[*] Exiting AiraLang. Goodbye, Boss!\033[0m") + break + + if not buffer and line.strip() == "clear": + os.system("clear") + continue + + if not line.strip() and not buffer: + continue + + buffer.append(line) + full_code = "\n".join(buffer) + + if is_balanced(full_code) or (len(buffer) > 1 and not line.strip()): + run_code(full_code, evaluator) + buffer = [] + + except (KeyboardInterrupt, EOFError): + if buffer: + print("\n\033[1;33m[*] Discarded incomplete block.\033[0m") + buffer = [] + else: + print("\n\033[1;33m[*] Interrupted. Exiting AiraLang...\033[0m") + break + +def main(): + if len(sys.argv) > 1: + if sys.argv[1] in ("-v", "--version"): + print(f"AiraLang v{VERSION} | Creator: {AUTHOR}") + elif sys.argv[1] in ("-h", "--help"): + print("Usage: airalang [script.aira]") + print(" airalang (starts interactive REPL)") + else: + run_file(sys.argv[1]) + else: + start_repl() + +if __name__ == "__main__": + main() diff --git a/src/evaluator.py b/src/evaluator.py new file mode 100644 index 0000000..b9852d3 --- /dev/null +++ b/src/evaluator.py @@ -0,0 +1,429 @@ +import math +import time +import os +import sys +import json +from stdlib_modules import BUILTIN_MODULES, AiraModule + +class ReturnException(Exception): + def __init__(self, value): + self.value = value + +class BreakException(Exception): + pass + +class ContinueException(Exception): + pass + +class AiraRuntimeException(Exception): + pass + +class Environment: + def __init__(self, parent=None): + self.values = {} + self.parent = parent + + def get(self, name, line=1): + if name in self.values: + return self.values[name] + if self.parent: + return self.parent.get(name, line) + raise NameError(f"AiraLang RuntimeError: Variable '{name}' is not defined (Line {line})") + + def set(self, name, value): + self.values[name] = value + + def assign(self, name, value, line=1): + if name in self.values: + self.values[name] = value + return + if self.parent: + self.parent.assign(name, value, line) + return + raise NameError(f"AiraLang RuntimeError: Cannot assign to undefined variable '{name}' (Line {line})") + +class AiraFunction: + def __init__(self, def_node, closure_env): + self.def_node = def_node + self.closure_env = closure_env + + def call(self, evaluator, args, this_instance=None): + fn_env = Environment(parent=self.closure_env) + if this_instance is not None: + fn_env.set("this", this_instance) + for param, arg in zip(self.def_node.params, args): + fn_env.set(param, arg) + try: + evaluator.eval_node(self.def_node.body, fn_env) + except ReturnException as ret: + return ret.value + return None + +class AiraClass: + def __init__(self, name, methods, closure_env): + self.name = name + self.methods = methods + self.closure_env = closure_env + + def instantiate(self, evaluator, args): + instance = AiraInstance(self) + if "init" in self.methods: + init_fn = AiraFunction(self.methods["init"], self.closure_env) + init_fn.call(evaluator, args, this_instance=instance) + elif "__init__" in self.methods: + init_fn = AiraFunction(self.methods["__init__"], self.closure_env) + init_fn.call(evaluator, args, this_instance=instance) + return instance + + def __call__(self, *args): + raise TypeError(f"AiraClass '{self.name}' must be instantiated with 'new {self.name}(...)'") + +class AiraInstance: + def __init__(self, class_ref): + self.class_ref = class_ref + self.fields = {} + + def get(self, name, line=1): + if name in self.fields: + return self.fields[name] + if name in self.class_ref.methods: + fn_node = self.class_ref.methods[name] + bound_fn = AiraFunction(fn_node, self.class_ref.closure_env) + return lambda *args: bound_fn.call(Evaluator._current_evaluator, args, this_instance=self) + raise AttributeError(f"AiraLang AttributeError: Instance of '{self.class_ref.name}' has no property or method '{name}' (Line {line})") + + def set(self, name, value): + self.fields[name] = value + + def __repr__(self): + return f"" + +class Evaluator: + _current_evaluator = None + + def __init__(self): + Evaluator._current_evaluator = self + self.global_env = Environment() + self.setup_builtins() + + def setup_builtins(self): + self.global_env.set("print", lambda *args: print(*args)) + self.global_env.set("say", lambda *args: print(*args)) + self.global_env.set("len", lambda x: len(x)) + self.global_env.set("type", lambda x: type(x).__name__) + self.global_env.set("str", lambda x: str(x)) + 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("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)) + self.global_env.set("join", lambda lst, sep=" ": sep.join(str(x) for x in lst)) + self.global_env.set("keys", lambda d: list(d.keys()) if isinstance(d, dict) else []) + self.global_env.set("values", lambda d: list(d.values()) if isinstance(d, dict) else []) + self.global_env.set("hex", lambda x: hex(int(x))) + self.global_env.set("bin", lambda x: bin(int(x))) + self.global_env.set("ord", lambda c: ord(str(c)[0])) + self.global_env.set("chr", lambda x: chr(int(x))) + + def eval(self, ast): + return self.eval_node(ast, self.global_env) + + def eval_node(self, node, env): + if node is None: + return None + Evaluator._current_evaluator = self + nodetype = node.__class__.__name__ + + if nodetype == "ProgramNode": + res = None + for stmt in node.statements: + res = self.eval_node(stmt, env) + return res + + elif nodetype == "ImportStatementNode": + mod_name = node.module_name + if mod_name in BUILTIN_MODULES: + 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: + code = f.read() + from lexer import Lexer + from parser import Parser + sub_tokens = Lexer(code).tokenize() + 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] + aira_mod = AiraModule(base_name, mod_env.values) + env.set(base_name, aira_mod) + return aira_mod + else: + raise ImportError(f"AiraLang ImportError: Module or file '{mod_name}' not found (Line {node.line})") + + elif nodetype == "SayStatementNode": + values = [self.eval_node(expr, env) for expr in node.expressions] + print(*values) + return values[-1] if values else None + + elif nodetype == "LetStatementNode": + val = self.eval_node(node.expression, env) + env.set(node.name, val) + return val + + elif nodetype == "AssignStatementNode": + val = self.eval_node(node.expression, env) + env.assign(node.name, val, node.line) + return val + + elif nodetype == "IndexAssignStatementNode": + target = self.eval_node(node.target, env) + index = self.eval_node(node.index, env) + val = self.eval_node(node.expression, env) + if isinstance(target, list): + target[int(index)] = val + return val + elif isinstance(target, dict): + target[index] = val + return val + else: + raise TypeError(f"AiraLang RuntimeError: Cannot index-assign to type '{type(target).__name__}' (Line {node.line})") + + elif nodetype == "MemberAssignStatementNode": + target = self.eval_node(node.target, env) + val = self.eval_node(node.expression, env) + if isinstance(target, AiraInstance): + target.set(node.member, val) + return val + elif isinstance(target, dict): + target[node.member] = val + return val + else: + setattr(target, node.member, val) + return val + + elif nodetype == "IfStatementNode": + cond = self.eval_node(node.condition, env) + if cond: + return self.eval_node(node.then_branch, env) + elif node.else_branch: + return self.eval_node(node.else_branch, env) + return None + + elif nodetype == "WhileStatementNode": + res = None + while self.eval_node(node.condition, env): + try: + res = self.eval_node(node.body, env) + except BreakException: + break + except ContinueException: + continue + return res + + elif nodetype == "ForInStatementNode": + iterable = self.eval_node(node.iterable, env) + res = None + loop_items = [] + if isinstance(iterable, (list, tuple, set)): + loop_items = list(iterable) + elif isinstance(iterable, str): + loop_items = list(iterable) + elif isinstance(iterable, dict): + loop_items = list(iterable.keys()) + elif hasattr(iterable, '__iter__'): + loop_items = list(iterable) + else: + raise TypeError(f"AiraLang TypeError: '{type(iterable).__name__}' is not iterable (Line {node.line})") + + for item in loop_items: + loop_env = Environment(parent=env) + loop_env.set(node.var_name, item) + try: + res = self.eval_node(node.body, loop_env) + except BreakException: + break + except ContinueException: + continue + return res + + elif nodetype == "TryCatchStatementNode": + try: + return self.eval_node(node.try_body, env) + except (ReturnException, BreakException, ContinueException): + raise + except Exception as e: + catch_env = Environment(parent=env) + err_msg = str(e) + if err_msg.startswith("AiraLang RuntimeError: "): + err_msg = err_msg.replace("AiraLang RuntimeError: ", "") + catch_env.set(node.error_var, err_msg) + return self.eval_node(node.catch_body, catch_env) + + elif nodetype == "ThrowStatementNode": + val = self.eval_node(node.expression, env) + raise AiraRuntimeException(str(val)) + + elif nodetype == "BreakStatementNode": + raise BreakException() + + elif nodetype == "ContinueStatementNode": + raise ContinueException() + + elif nodetype == "ClassDefNode": + cls = AiraClass(node.name, node.methods, env) + env.set(node.name, cls) + return cls + + elif nodetype == "NewInstanceNode": + cls = env.get(node.class_name, node.line) + args = [self.eval_node(arg, env) for arg in node.arguments] + if isinstance(cls, AiraClass): + return cls.instantiate(self, args) + raise TypeError(f"AiraLang TypeError: '{node.class_name}' is not a class (Line {node.line})") + + elif nodetype == "ThisNode": + return env.get("this", node.line) + + elif nodetype == "BlockNode": + block_env = Environment(parent=env) + res = None + for stmt in node.statements: + res = self.eval_node(stmt, block_env) + return res + + elif nodetype == "FunctionDefNode": + fn = AiraFunction(node, env) + env.set(node.name, fn) + return fn + + elif nodetype == "ReturnStatementNode": + val = self.eval_node(node.expression, env) if node.expression else None + raise ReturnException(val) + + elif nodetype == "ExpressionStatementNode": + return self.eval_node(node.expression, env) + + elif nodetype == "LiteralNode": + return node.value + + elif nodetype == "IdentifierNode": + return env.get(node.name, node.line) + + elif nodetype == "ListNode": + return [self.eval_node(el, env) for el in node.elements] + + elif nodetype == "DictNode": + d = {} + for k_expr, v_expr in node.pairs: + k = self.eval_node(k_expr, env) + v = self.eval_node(v_expr, env) + d[k] = v + return d + + elif nodetype == "MemberAccessNode": + target = self.eval_node(node.target, env) + member = node.member + + # Class instance access + if isinstance(target, AiraInstance): + return target.get(member, node.line) + + # Module access + elif isinstance(target, AiraModule): + return target.get(member) + + # Dictionary access + elif isinstance(target, dict): + if member in target: + return target[member] + if member == "keys": return lambda: list(target.keys()) + if member == "values": return lambda: list(target.values()) + if member == "has" or member == "contains": return lambda k: k in target + if member == "length": return len(target) + + # String methods & properties + elif isinstance(target, str): + if member == "length": return len(target) + if member == "upper": return lambda: target.upper() + if member == "lower": return lambda: target.lower() + if member == "split": return lambda sep=" ": target.split(sep) + if member == "trim" or member == "strip": return lambda: target.strip() + if member == "replace": return lambda old, new: target.replace(str(old), str(new)) + if member == "contains": return lambda sub: str(sub) in target + if member == "starts_with" or member == "startswith": return lambda sub: target.startswith(str(sub)) + if member == "ends_with" or member == "endswith": return lambda sub: target.endswith(str(sub)) + if member == "slice": return lambda start, end=None: target[int(start):int(end) if end is not None else None] + + # List methods & properties + elif isinstance(target, list): + if member == "length": return len(target) + if member == "push" or member == "append": return lambda x: target.append(x) or target + if member == "pop": return lambda idx=-1: target.pop(idx) + if member == "join": return lambda sep=" ": sep.join(str(x) for x in target) + if member == "contains": return lambda x: x in target + if member == "reverse": return lambda: target.reverse() or target + if member == "sort": return lambda: target.sort() or target + if member == "slice": return lambda start, end=None: target[int(start):int(end) if end is not None else None] + + elif hasattr(target, member): + return getattr(target, member) + + raise AttributeError(f"AiraLang RuntimeError: Object of type '{type(target).__name__}' has no member '{member}' (Line {node.line})") + + elif nodetype == "IndexAccessNode": + target = self.eval_node(node.target, env) + idx = self.eval_node(node.index, env) + try: + return target[idx] + except Exception as e: + raise IndexError(f"AiraLang IndexError: Failed to access index '{idx}' on '{target}' (Line {node.line}): {e}") + + elif nodetype == "UnaryOpNode": + val = self.eval_node(node.right, env) + if node.op == "-": + return -val + elif node.op in ("!", "not"): + return not val + raise ValueError(f"Unknown unary op {node.op}") + + elif nodetype == "BinaryOpNode": + left = self.eval_node(node.left, env) + right = self.eval_node(node.right, env) + + if node.op == "+": + if isinstance(left, str) or isinstance(right, str): + return str(left) + str(right) + return left + right + + if node.op == "-": return left - right + if node.op == "*": return left * right + if node.op == "/": return left / right + if node.op == "%": return left % right + if node.op == "==": return left == right + if node.op == "!=": return left != right + if node.op == "<": return left < right + if node.op == ">": return left > right + if node.op == "<=": return left <= right + if node.op == ">=": return left >= right + if node.op == "and": return left and right + if node.op == "or": return left or right + raise ValueError(f"Unknown binary op {node.op}") + + elif nodetype == "FunctionCallNode": + callee = self.eval_node(node.callee, env) + args = [self.eval_node(arg, env) for arg in node.arguments] + + 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) + else: + raise TypeError(f"AiraLang RuntimeError: '{callee}' is not callable (Line {node.line})") + + raise NotImplementedError(f"AiraLang Evaluator: Unhandled AST Node '{nodetype}'") diff --git a/src/lexer.py b/src/lexer.py new file mode 100644 index 0000000..5a5cc3b --- /dev/null +++ b/src/lexer.py @@ -0,0 +1,92 @@ +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"\."), +] + +class Token: + def __init__(self, type_, value, line, col): + self.type = type_ + self.value = value + self.line = line + self.col = col + + def __repr__(self): + return f"Token({self.type}, {repr(self.value)}, line={self.line}, col={self.col})" + +class Lexer: + def __init__(self, code): + self.code = code + self.pos = 0 + self.line = 1 + self.col = 1 + self.tokens = [] + + def tokenize(self): + while self.pos < len(self.code): + match = None + for token_type, regex in TOKEN_TYPES: + pattern = re.compile(regex) + match = pattern.match(self.code, self.pos) + if match: + val = match.group(0) + if token_type == "COMMENT": + pass + elif token_type == "WHITESPACE": + num_newlines = val.count('\n') + if num_newlines > 0: + self.line += num_newlines + self.col = len(val) - val.rfind('\n') + else: + self.col += len(val) + elif token_type == "STRING": + raw_str = val[1:-1].encode('utf-8').decode('unicode_escape') + self.tokens.append(Token("STRING", raw_str, self.line, self.col)) + self.col += len(val) + elif token_type == "NUMBER": + num_val = float(val) if '.' in val else int(val) + self.tokens.append(Token("NUMBER", num_val, self.line, self.col)) + self.col += len(val) + elif token_type == "KEYWORD": + self.tokens.append(Token(val.upper(), val, self.line, self.col)) + self.col += len(val) + else: + self.tokens.append(Token(token_type, val, self.line, self.col)) + self.col += len(val) + self.pos = match.end() + break + + if not match: + char = self.code[self.pos] + raise SyntaxError(f"AiraLang Lexer Error: Unexpected character '{char}' at line {self.line}, col {self.col}") + + self.tokens.append(Token("EOF", None, self.line, self.col)) + return self.tokens diff --git a/src/parser.py b/src/parser.py new file mode 100644 index 0000000..b087922 --- /dev/null +++ b/src/parser.py @@ -0,0 +1,372 @@ +from ast_nodes import * + +class Parser: + def __init__(self, tokens): + self.tokens = tokens + self.pos = 0 + + def current(self): + return self.tokens[self.pos] + + def peek(self, offset=1): + if self.pos + offset < len(self.tokens): + return self.tokens[self.pos + offset] + return self.tokens[-1] + + def match(self, *types): + if self.current().type in types: + tok = self.current() + self.pos += 1 + return tok + return None + + def expect(self, type_): + tok = self.match(type_) + if not tok: + curr = self.current() + raise SyntaxError(f"AiraLang SyntaxError: Expected '{type_}' but got '{curr.type}' ({repr(curr.value)}) at line {curr.line}, col {curr.col}") + return tok + + def parse(self): + statements = [] + while self.current().type != "EOF": + stmt = self.parse_statement() + if stmt: + statements.append(stmt) + return ProgramNode(statements) + + def parse_statement(self): + tok = self.current() + + if self.match("SEMICOLON"): + return None + + # standalone block statement: `{ stmt1; stmt2; }` + if tok.type == "LBRACE": + return self.parse_block_or_statement() + + # import / load / use statement: `import os;`, `import "math";` + if tok.type in ("IMPORT", "LOAD", "USE"): + self.pos += 1 + if self.current().type in ("STRING", "IDENTIFIER"): + mod_tok = self.current() + self.pos += 1 + else: + curr = self.current() + raise SyntaxError(f"AiraLang SyntaxError: Expected module name or string after '{tok.value}' at line {curr.line}, col {curr.col}") + self.match("SEMICOLON") + return ImportStatementNode(str(mod_tok.value), tok.line) + + # say / print statement: `say "A", "B", 10;` + if tok.type in ("SAY", "PRINT"): + self.pos += 1 + expressions = [self.parse_expression()] + while self.match("COMMA"): + expressions.append(self.parse_expression()) + self.match("SEMICOLON") + return SayStatementNode(expressions, tok.line) + + # let statement: `let name = expr;` + if tok.type == "LET": + self.pos += 1 + name_tok = self.expect("IDENTIFIER") + self.expect("ASSIGN") + expr = self.parse_expression() + self.match("SEMICOLON") + return LetStatementNode(name_tok.value, expr, tok.line) + + # if statement: `if (cond) { ... } else { ... }` + if tok.type == "IF": + self.pos += 1 + has_paren = self.match("LPAREN") + cond = self.parse_expression() + if has_paren: + self.expect("RPAREN") + then_branch = self.parse_block_or_statement() + else_branch = None + if self.match("ELSE"): + else_branch = self.parse_block_or_statement() + return IfStatementNode(cond, then_branch, else_branch, tok.line) + + # while statement: `while (cond) { ... }` + if tok.type == "WHILE": + self.pos += 1 + has_paren = self.match("LPAREN") + cond = self.parse_expression() + if has_paren: + self.expect("RPAREN") + 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) { ... }` + if tok.type == "FOR": + self.pos += 1 + has_paren = self.match("LPAREN") + self.match("LET") # optional let + var_tok = self.expect("IDENTIFIER") + self.expect("IN") + iterable = self.parse_expression() + if has_paren: + self.expect("RPAREN") + body = self.parse_block_or_statement() + return ForInStatementNode(var_tok.value, iterable, body, tok.line) + + # try / catch statement: `try { ... } catch (err) { ... }` + if tok.type == "TRY": + self.pos += 1 + try_body = self.parse_block_or_statement() + self.expect("CATCH") + has_paren = self.match("LPAREN") + err_var = "error" + if self.current().type == "IDENTIFIER": + err_var = self.expect("IDENTIFIER").value + if has_paren: + self.expect("RPAREN") + catch_body = self.parse_block_or_statement() + return TryCatchStatementNode(try_body, err_var, catch_body, tok.line) + + # throw statement: `throw "Error description";` + if tok.type == "THROW": + self.pos += 1 + expr = self.parse_expression() + self.match("SEMICOLON") + return ThrowStatementNode(expr, tok.line) + + # break statement: `break;` + if tok.type == "BREAK": + self.pos += 1 + self.match("SEMICOLON") + return BreakStatementNode(tok.line) + + # continue statement: `continue;` + if tok.type == "CONTINUE": + self.pos += 1 + self.match("SEMICOLON") + return ContinueStatementNode(tok.line) + + # fn statement: `fn name(a, b) { ... }` + if tok.type == "FN": + self.pos += 1 + name_tok = self.expect("IDENTIFIER") + self.expect("LPAREN") + params = [] + if self.current().type != "RPAREN": + params.append(self.expect("IDENTIFIER").value) + while self.match("COMMA"): + params.append(self.expect("IDENTIFIER").value) + self.expect("RPAREN") + body = self.parse_block_or_statement() + return FunctionDefNode(name_tok.value, params, body, tok.line) + + # class statement: `class Person { fn init(name) { ... } fn greet() { ... } }` + if tok.type == "CLASS": + self.pos += 1 + name_tok = self.expect("IDENTIFIER") + self.expect("LBRACE") + 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: + m_name_tok = self.expect("IDENTIFIER") + self.expect("LPAREN") + m_params = [] + if self.current().type != "RPAREN": + m_params.append(self.expect("IDENTIFIER").value) + while self.match("COMMA"): + m_params.append(self.expect("IDENTIFIER").value) + self.expect("RPAREN") + m_body = self.parse_block_or_statement() + methods[m_name_tok.value] = FunctionDefNode(m_name_tok.value, m_params, m_body, m_name_tok.line) + elif self.match("SEMICOLON"): + pass + else: + curr = self.current() + raise SyntaxError(f"AiraLang SyntaxError: Expected method in class '{name_tok.value}' at line {curr.line}") + self.expect("RBRACE") + return ClassDefNode(name_tok.value, methods, tok.line) + + # return statement: `return expr;` + if tok.type == "RETURN": + self.pos += 1 + expr = None + if self.current().type not in ("SEMICOLON", "RBRACE", "EOF"): + expr = self.parse_expression() + self.match("SEMICOLON") + return ReturnStatementNode(expr, tok.line) + + # expression / assignment statement + expr = self.parse_expression() + if self.match("ASSIGN"): + val_expr = self.parse_expression() + self.match("SEMICOLON") + if isinstance(expr, IdentifierNode): + return AssignStatementNode(expr.name, val_expr, tok.line) + elif isinstance(expr, IndexAccessNode): + return IndexAssignStatementNode(expr.target, expr.index, val_expr, tok.line) + elif isinstance(expr, MemberAccessNode): + return MemberAssignStatementNode(expr.target, expr.member, val_expr, tok.line) + else: + raise SyntaxError(f"AiraLang SyntaxError: Invalid assignment target at line {tok.line}") + + self.match("SEMICOLON") + return ExpressionStatementNode(expr) + + def parse_block_or_statement(self): + if self.match("LBRACE"): + stmts = [] + while self.current().type not in ("RBRACE", "EOF"): + s = self.parse_statement() + if s: + stmts.append(s) + self.expect("RBRACE") + return BlockNode(stmts) + else: + return self.parse_statement() + + # Expressions + def parse_expression(self): + return self.parse_logical_or() + + def parse_logical_or(self): + left = self.parse_logical_and() + while self.current().type == "OR": + op = self.current() + self.pos += 1 + right = self.parse_logical_and() + left = BinaryOpNode(left, "or", right, op.line) + return left + + def parse_logical_and(self): + left = self.parse_equality() + while self.current().type == "AND": + op = self.current() + self.pos += 1 + right = self.parse_equality() + left = BinaryOpNode(left, "and", right, op.line) + return left + + def parse_equality(self): + left = self.parse_relational() + while self.current().type in ("EQ_EQ", "NOT_EQ"): + op = self.current() + self.pos += 1 + right = self.parse_relational() + left = BinaryOpNode(left, op.value, right, op.line) + return left + + def parse_relational(self): + left = self.parse_additive() + while self.current().type in ("LT", "GT", "LTE", "GTE"): + op = self.current() + self.pos += 1 + right = self.parse_additive() + left = BinaryOpNode(left, op.value, right, op.line) + return left + + def parse_additive(self): + left = self.parse_multiplicative() + while self.current().type in ("PLUS", "MINUS"): + op = self.current() + self.pos += 1 + right = self.parse_multiplicative() + left = BinaryOpNode(left, op.value, right, op.line) + return left + + def parse_multiplicative(self): + left = self.parse_unary() + while self.current().type in ("MUL", "DIV", "MOD"): + op = self.current() + self.pos += 1 + right = self.parse_unary() + left = BinaryOpNode(left, op.value, right, op.line) + return left + + def parse_unary(self): + if self.current().type in ("MINUS", "NOT"): + op = self.current() + self.pos += 1 + right = self.parse_unary() + return UnaryOpNode(op.value, right, op.line) + return self.parse_postfix() + + def parse_postfix(self): + atom = self.parse_atom() + while True: + if self.match("LPAREN"): + args = [] + if self.current().type != "RPAREN": + args.append(self.parse_expression()) + while self.match("COMMA"): + args.append(self.parse_expression()) + self.expect("RPAREN") + atom = FunctionCallNode(atom, args, getattr(atom, 'line', self.current().line)) + elif self.match("DOT"): + member_tok = self.expect("IDENTIFIER") + atom = MemberAccessNode(atom, member_tok.value, member_tok.line) + elif self.match("LBRACKET"): + idx_expr = self.parse_expression() + self.expect("RBRACKET") + atom = IndexAccessNode(atom, idx_expr, getattr(atom, 'line', self.current().line)) + else: + break + return atom + + def parse_atom(self): + tok = self.current() + if self.match("NUMBER"): + return LiteralNode(tok.value, "NUMBER", tok.line) + if self.match("STRING"): + return LiteralNode(tok.value, "STRING", tok.line) + if self.match("TRUE"): + return LiteralNode(True, "BOOLEAN", tok.line) + if self.match("FALSE"): + return LiteralNode(False, "BOOLEAN", tok.line) + if self.match("NULL"): + return LiteralNode(None, "NULL", tok.line) + if self.match("THIS"): + return ThisNode(tok.line) + if self.match("NEW"): + class_tok = self.expect("IDENTIFIER") + args = [] + if self.match("LPAREN"): + if self.current().type != "RPAREN": + args.append(self.parse_expression()) + while self.match("COMMA"): + args.append(self.parse_expression()) + self.expect("RPAREN") + return NewInstanceNode(class_tok.value, args, tok.line) + if self.match("IDENTIFIER"): + return IdentifierNode(tok.value, tok.line) + if self.match("LPAREN"): + expr = self.parse_expression() + self.expect("RPAREN") + return expr + if self.match("LBRACKET"): + elements = [] + if self.current().type != "RBRACKET": + elements.append(self.parse_expression()) + while self.match("COMMA"): + elements.append(self.parse_expression()) + self.expect("RBRACKET") + return ListNode(elements, tok.line) + if self.match("LBRACE"): + pairs = [] + if self.current().type != "RBRACE": + key_expr = self.parse_expression() + self.expect("COLON") + val_expr = self.parse_expression() + pairs.append((key_expr, val_expr)) + while self.match("COMMA"): + if self.current().type == "RBRACE": + break + k = self.parse_expression() + self.expect("COLON") + v = self.parse_expression() + pairs.append((k, v)) + self.expect("RBRACE") + return DictNode(pairs, tok.line) + + raise SyntaxError(f"AiraLang SyntaxError: Unexpected token '{tok.type}' ({repr(tok.value)}) at line {tok.line}, col {tok.col}") diff --git a/src/stdlib_modules.py b/src/stdlib_modules.py new file mode 100644 index 0000000..92005c1 --- /dev/null +++ b/src/stdlib_modules.py @@ -0,0 +1,220 @@ +import os +import sys +import math +import time +import json +import random +import hashlib +import base64 +import urllib.request +import urllib.parse + +class AiraModule: + def __init__(self, name, methods=None): + self.name = name + self.methods = methods or {} + + def get(self, prop_name): + if prop_name in self.methods: + return self.methods[prop_name] + raise AttributeError(f"AiraLang Module '{self.name}' has no method or property '{prop_name}'") + +def create_file_module(): + def read_file(path): + with open(path, "r", encoding="utf-8") as f: + return f.read() + + def write_file(path, content): + with open(path, "w", encoding="utf-8") as f: + f.write(str(content)) + return True + + def append_file(path, content): + with open(path, "a", encoding="utf-8") as f: + f.write(str(content)) + return True + + def exists(path): + return os.path.exists(path) + + def delete(path): + if os.path.exists(path): + os.remove(path) + return True + return False + + def size(path): + if os.path.exists(path): + return os.path.getsize(path) + return -1 + + return AiraModule("file", { + "read": read_file, + "write": write_file, + "append": append_file, + "exists": exists, + "delete": delete, + "size": size + }) + +def create_os_module(): + def cmd(command): + return os.popen(command).read().strip() + + def env(var_name, default=""): + return os.environ.get(var_name, default) + + def platform(): + return sys.platform + + def cwd(): + return os.getcwd() + + def listdir(path="."): + return os.listdir(path) + + def mkdir(path): + os.makedirs(path, exist_ok=True) + return True + + return AiraModule("os", { + "cmd": cmd, + "system": cmd, + "env": env, + "getenv": env, + "platform": platform, + "cwd": cwd, + "getcwd": cwd, + "listdir": listdir, + "mkdir": mkdir + }) + +def create_math_module(): + return AiraModule("math", { + "sqrt": lambda x: math.sqrt(x), + "floor": lambda x: math.floor(x), + "ceil": lambda x: math.ceil(x), + "abs": lambda x: abs(x), + "round": lambda x, d=0: round(x, d) if d else round(x), + "pow": lambda b, e: math.pow(b, e), + "random": lambda low=0, high=1: random.randint(int(low), int(high)) if isinstance(low, int) and isinstance(high, int) else random.uniform(low, high), + "pi": math.pi, + "e": math.e + }) + +def create_time_module(): + return AiraModule("time", { + "now": lambda: time.strftime("%Y-%m-%d %H:%M:%S"), + "time": lambda: time.time(), + "sleep": lambda s: time.sleep(s) + }) + +def create_json_module(): + return AiraModule("json", { + "parse": lambda s: json.loads(s), + "stringify": lambda obj, indent=2: json.dumps(obj, indent=indent) + }) + +def create_http_module(): + def get(url, headers=None): + req_headers = {"User-Agent": "AiraLang/1.1 (Termux; Android)"} + if isinstance(headers, dict): + req_headers.update(headers) + req = urllib.request.Request(url, headers=req_headers) + try: + with urllib.request.urlopen(req, timeout=15) as response: + return response.read().decode("utf-8") + except Exception as e: + raise RuntimeError(f"HTTP GET Error: {e}") + + def post(url, data_payload=None, headers=None): + req_headers = {"User-Agent": "AiraLang/1.1 (Termux; Android)"} + if isinstance(headers, dict): + req_headers.update(headers) + encoded_data = None + if isinstance(data_payload, dict): + req_headers["Content-Type"] = "application/x-www-form-urlencoded" + encoded_data = urllib.parse.urlencode(data_payload).encode("utf-8") + elif isinstance(data_payload, str): + encoded_data = data_payload.encode("utf-8") + req = urllib.request.Request(url, data=encoded_data, headers=req_headers) + try: + with urllib.request.urlopen(req, timeout=15) as response: + return response.read().decode("utf-8") + except Exception as e: + raise RuntimeError(f"HTTP POST Error: {e}") + + def download(url, dest_path): + req = urllib.request.Request(url, headers={"User-Agent": "AiraLang/1.1"}) + try: + with urllib.request.urlopen(req, timeout=30) as response, open(dest_path, "wb") as out_file: + out_file.write(response.read()) + return True + except Exception as e: + raise RuntimeError(f"HTTP Download Error: {e}") + + def status(url): + try: + req = urllib.request.Request(url, headers={"User-Agent": "AiraLang/1.1"}) + with urllib.request.urlopen(req, timeout=10) as response: + return response.getcode() + except urllib.error.HTTPError as e: + return e.code + except Exception: + return 0 + + return AiraModule("http", { + "get": get, + "post": post, + "download": download, + "status": status + }) + +def create_crypto_module(): + def md5(s): + return hashlib.md5(str(s).encode('utf-8')).hexdigest() + + def sha256(s): + return hashlib.sha256(str(s).encode('utf-8')).hexdigest() + + def sha1(s): + return hashlib.sha1(str(s).encode('utf-8')).hexdigest() + + def b64encode(s): + return base64.b64encode(str(s).encode('utf-8')).decode('utf-8') + + def b64decode(s): + return base64.b64decode(str(s).encode('utf-8')).decode('utf-8') + + return AiraModule("crypto", { + "md5": md5, + "sha256": sha256, + "sha1": sha1, + "base64_encode": b64encode, + "base64_decode": b64decode, + "b64encode": b64encode, + "b64decode": b64decode + }) + +def create_string_module(): + return AiraModule("string", { + "upper": lambda s: str(s).upper(), + "lower": lambda s: str(s).lower(), + "split": lambda s, sep=" ": str(s).split(sep), + "replace": lambda s, old, new: str(s).replace(str(old), str(new)), + "trim": lambda s: str(s).strip(), + "contains": lambda s, sub: str(sub) in str(s), + "length": lambda s: len(str(s)), + "join": lambda lst, sep=" ": sep.join(str(x) for x in lst) + }) + +BUILTIN_MODULES = { + "file": create_file_module, + "os": create_os_module, + "math": create_math_module, + "time": create_time_module, + "json": create_json_module, + "http": create_http_module, + "crypto": create_crypto_module, + "string": create_string_module +}