From 739439874fd976f53d9b3f5eba572092fd64302d Mon Sep 17 00:00:00 2001 From: Adam Eehan Date: Thu, 12 Nov 2026 22:47:26 +0530 Subject: [PATCH] =?UTF-8?q?chore(clean):=20100%=20Pure=20.aira=20=E2=80=94?= =?UTF-8?q?=20Purged=20all=20legacy=20Python=20and=20C=20files?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitattributes | 16 +- bin/airalang | Bin 81112 -> 0 bytes bin/airalang.bat | 2 - bin/airalang.cmd | 2 - bin/airalang.ps1 | 1 - install.bat | 18 - install.sh | 45 - modules/README.md | 45 - modules/ai.md | 110 - modules/android.md | 98 - modules/bot.md | 27 - modules/crypto.md | 21 - modules/env.md | 30 - modules/file.md | 24 - modules/http.md | 21 - modules/json.md | 19 - modules/math.md | 24 - modules/net.md | 21 - modules/os.md | 23 - modules/proposal.md | 27 - modules/sec.md | 27 - modules/serve.md | 43 - modules/sqlite.md | 25 - modules/string.md | 26 - modules/system.md | 93 - modules/term.md | 50 - modules/thread.md | 25 - modules/time.md | 21 - modules/webhook.md | 29 - modules/youtube.md | 46 - s1duo/Makefile | 31 - s1duo/include/ast.h | 189 -- s1duo/include/common.h | 58 - s1duo/include/elf_emitter.h | 34 - s1duo/include/env.h | 20 - s1duo/include/evaluator.h | 32 - s1duo/include/lexer.h | 18 - s1duo/include/modules.h | 13 - s1duo/include/parser.h | 19 - s1duo/include/token.h | 92 - s1duo/include/value.h | 106 - s1duo/src/ast.c | 396 ---- s1duo/src/common.c | 133 -- s1duo/src/elf_emitter.c | 334 --- s1duo/src/env.c | 67 - s1duo/src/evaluator.c | 462 ----- s1duo/src/lexer.c | 361 ---- s1duo/src/main.c | 174 -- s1duo/src/modules.c | 621 ------ s1duo/src/parser.c | 552 ----- s1duo/src/value.c | 369 ---- s1duo/tests/test_basic.aira | 61 - s1duo/tests/test_benchmark.aira | 8 - s1duo/tests/test_raw_elf.aira | 3 - s1duo/tests/test_security_bounds.aira | 3 - s1duo/tests/test_security_recursion.aira | 10 - setup.nsi | 119 -- src/ast_nodes.py | 197 -- src/cli.py | 570 ------ src/evaluator.py | 636 ------ src/lexer.py | 103 - src/parser.py | 580 ------ src/stdlib_modules.py | 2381 ---------------------- 63 files changed, 1 insertion(+), 9710 deletions(-) delete mode 100755 bin/airalang delete mode 100644 bin/airalang.bat delete mode 100644 bin/airalang.cmd delete mode 100644 bin/airalang.ps1 delete mode 100644 install.bat delete mode 100755 install.sh delete mode 100644 modules/README.md delete mode 100644 modules/ai.md delete mode 100644 modules/android.md delete mode 100644 modules/bot.md delete mode 100644 modules/crypto.md delete mode 100644 modules/env.md delete mode 100644 modules/file.md delete mode 100644 modules/http.md delete mode 100644 modules/json.md delete mode 100644 modules/math.md delete mode 100644 modules/net.md delete mode 100644 modules/os.md delete mode 100644 modules/proposal.md delete mode 100644 modules/sec.md delete mode 100644 modules/serve.md delete mode 100644 modules/sqlite.md delete mode 100644 modules/string.md delete mode 100644 modules/system.md delete mode 100644 modules/term.md delete mode 100644 modules/thread.md delete mode 100644 modules/time.md delete mode 100644 modules/webhook.md delete mode 100644 modules/youtube.md delete mode 100644 s1duo/Makefile delete mode 100644 s1duo/include/ast.h delete mode 100644 s1duo/include/common.h delete mode 100644 s1duo/include/elf_emitter.h delete mode 100644 s1duo/include/env.h delete mode 100644 s1duo/include/evaluator.h delete mode 100644 s1duo/include/lexer.h delete mode 100644 s1duo/include/modules.h delete mode 100644 s1duo/include/parser.h delete mode 100644 s1duo/include/token.h delete mode 100644 s1duo/include/value.h delete mode 100644 s1duo/src/ast.c delete mode 100644 s1duo/src/common.c delete mode 100644 s1duo/src/elf_emitter.c delete mode 100644 s1duo/src/env.c delete mode 100644 s1duo/src/evaluator.c delete mode 100644 s1duo/src/lexer.c delete mode 100644 s1duo/src/main.c delete mode 100644 s1duo/src/modules.c delete mode 100644 s1duo/src/parser.c delete mode 100644 s1duo/src/value.c delete mode 100644 s1duo/tests/test_basic.aira delete mode 100644 s1duo/tests/test_benchmark.aira delete mode 100644 s1duo/tests/test_raw_elf.aira delete mode 100644 s1duo/tests/test_security_bounds.aira delete mode 100644 s1duo/tests/test_security_recursion.aira delete mode 100644 setup.nsi delete mode 100644 src/ast_nodes.py delete mode 100755 src/cli.py delete mode 100644 src/evaluator.py delete mode 100644 src/lexer.py delete mode 100644 src/parser.py delete mode 100644 src/stdlib_modules.py diff --git a/.gitattributes b/.gitattributes index b83a0a8..2453ccb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,18 +1,4 @@ # AIRA Sovereign Language Identity +# 100% Pure .aira Codebase *.aira linguist-language=Aira *.aira linguist-detectable=true - -# Exclude compiler internals, VM, and runtime engines from GitHub language stats -# Ensures GitHub repo remains 100% pure AIRA -src/** linguist-vendored=true -s1duo/** linguist-vendored=true -bin/** linguist-vendored=true -modules/** linguist-documentation=true -*.py linguist-vendored=true -*.c linguist-vendored=true -*.h linguist-vendored=true -*.o linguist-generated=true -Makefile linguist-vendored=true -*.sh linguist-vendored=true -*.bat linguist-vendored=true -*.nsi linguist-vendored=true diff --git a/bin/airalang b/bin/airalang deleted file mode 100755 index ab86bb8c9bffc95d599b1c82cce3fc3ce2c44df6..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 81112 zcmb@P3w%`7@%Ybf0&GHr00{}tYmzhVo&`l}%Qweisw6|HTx2E;aqZ9!3qg86^v+sWxnVBF@XxN7Q8Xv#52nr zVTixN9!42m@6DbD{+nAP%N-{Fjb>@plhX^eS8tF}R%z*F!FzQjqL+*1(lCI{=0utUycS-?&xxdNzf{-_Qut&udORxIc{lr<+zIS$`z$G z6SD8!uF2mc2&R1RFi(KGKUEt*|@M;(MdKdU67x*?8_=7I+ zM_k}dF7ThYz@K%2zXaT=zg~60|C0;;J1+R|xxhbkfq&)#|H1{{4TE;FhXfaRKNonq z3p~RGKGp@E?E;_d0-x>zzs3cAoeO+{3;b&?@In{(au;}|3;gRY@Nc-l?{$GI<^2!; z#awhf4_-P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9pTjc7sD2<_13gr@2%fO%Gr)En&mIX_frP@dOf**pTqXG|5|>A z1+5>XZ`%Kj%%IBI|)9dl|doBl}uhk$R|sNN88s>6AVWCbJ_k}w%@@1Yksr+ zW_%z_`+o?BdC+qxS-rDO5oU5uuA3#S!#=P7(DrFvk?}G6Ps5%@|MmLZATC*<$INf0 z_kf2u&GDq|A0bB!k8)MnA$ULjO(II}g*Z@&o>`;hOYTddwATLX{PQ+29d^a3ew%WY d{ZEV_%-Vkqe+)xU_U{<2I0sVUYIw}{{|{QLC7u8P diff --git a/bin/airalang.bat b/bin/airalang.bat deleted file mode 100644 index 08cbd24..0000000 --- a/bin/airalang.bat +++ /dev/null @@ -1,2 +0,0 @@ -@echo off -python "%~dp0..\src\cli.py" %* diff --git a/bin/airalang.cmd b/bin/airalang.cmd deleted file mode 100644 index 08cbd24..0000000 --- a/bin/airalang.cmd +++ /dev/null @@ -1,2 +0,0 @@ -@echo off -python "%~dp0..\src\cli.py" %* diff --git a/bin/airalang.ps1 b/bin/airalang.ps1 deleted file mode 100644 index 6a935eb..0000000 --- a/bin/airalang.ps1 +++ /dev/null @@ -1 +0,0 @@ -& python "$PSScriptRoot\..\src\cli.py" $args diff --git a/install.bat b/install.bat deleted file mode 100644 index 5e7fbc0..0000000 --- a/install.bat +++ /dev/null @@ -1,18 +0,0 @@ -@echo off -setlocal -echo =================================================== -echo AiraLang Windows Installer -echo Creator: Adam Eehan (Aira Group of Technology) -echo =================================================== -echo. - -set "BIN_DIR=%~dp0bin" - -echo [+] Adding %BIN_DIR% to User PATH... -powershell -Command "$p = [Environment]::GetEnvironmentVariable('Path', 'User'); if ($p -notlike '*%BIN_DIR%*') { [Environment]::SetEnvironmentVariable('Path', $p + ';%BIN_DIR%', 'User'); Write-Host '[+] Successfully added to User PATH!' } else { Write-Host '[*] Already in PATH.' }" - -echo. -echo [+] Installation complete! Open a new command prompt and run: -echo airalang --version -echo =================================================== -pause diff --git a/install.sh b/install.sh deleted file mode 100755 index 4154f69..0000000 --- a/install.sh +++ /dev/null @@ -1,45 +0,0 @@ -#!/bin/bash -# ============================================================= -# 🌟 AiraLang Global Native Installer for Linux & Termux -# πŸ‘‘ Creator: Adam Eehan (Founder & CEO, Aira Group of Technology) -# ⚑ Engine: AiraLang S1 Duo Native Systems Flagship -# ============================================================= - -set -e - -echo -e "\033[1;36m" -echo " ___ _ __ _____ __ ____ " -echo " / | (_)________ _/ / ____ _____ ____ _ / ___// / / __ \__ ______ " -echo " / /| |/ / ___/ __ \`/ / / __ \`/ __ \/ __ \`// __// / / / / / / / / __ \ " -echo " / ___ / / / / /_/ / /___/ /_/ / / / / /_/ /___/ / /__/ /_/ / /_/ / /_/ / " -echo " /_/ |/_/_/ \\__,_/_____/\\__,_/_/ /_/\\__, //____/____/_____/\\__,_/\\____/ " -echo " /____/ " -echo -e "\033[0m" -echo -e "\033[1;32m[*] Compiling & Installing AiraLang S1 Duo Native Engine...\033[0m" - -REPO_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -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[*] Building native engine with clang...\033[0m" -cd "$REPO_DIR/s1duo" -make clean -make - -cp bin/airalang "$BIN_DIR/airalang" -cp bin/airalang "$BIN_DIR/airalang3" -chmod 755 "$BIN_DIR/airalang" "$BIN_DIR/airalang3" - -echo -e "\033[1;32m[+] AiraLang S1 Duo Successfully Installed to $BIN_DIR/airalang! πŸš€\033[0m" -echo -e "\033[1;37m[*] Run \033[1;33mairalang\033[0m to start the REPL, or \033[1;33mairalang \033[0m to execute.\033[0m" -echo -e "\033[1;35m[*] Standalone ELF binary compiler: \033[1;33mairalang -b -o \033[0m" diff --git a/modules/README.md b/modules/README.md deleted file mode 100644 index 8ae33ac..0000000 --- a/modules/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# πŸ“¦ AiraLang Standard Library Modules Directory -> **Official Module Catalog for AiraLang (v1.5.0 Full-Stack Web & Cyber OSINT Edition)** -> **Author & Creator:** Er. Adam Eehan (Founder & CEO, Aira Group of Technology) πŸ‘‘ - ---- - -## 🌟 Overview -AiraLang features 22 built-in standard library modules engineered natively for full-stack web serving, AI capabilities, cyber security recon, system operations, and terminal aesthetics. - -All modules are loaded natively via the `import` statement: -```aira -import ""; -``` - ---- - -## πŸ“‹ Complete Modules Catalog - -| # | Module | Category | Primary Purpose | Key Methods | -|---|---|---|---|---| -| 1 | [`serve`](./serve.md) / `server` | Web Backend | Native Micro Web Server for building REST APIs | `route()`, `get()`, `post()`, `start()` | -| 2 | [`term`](./term.md) / `ui` | Terminal Aesthetics | ANSI colors, stylized boxes, ASCII data tables, braille spinners | `color()`, `rainbow()`, `box()`, `table()`, `spinner()`, `clear()` | -| 3 | [`webhook`](./webhook.md) | Event Automation | Instant JSON webhook dispatcher and background listener | `send()`, `listen()` | -| 4 | [`bot`](./bot.md) / `telegram` | Messaging Bots | Telegram Bot API and Discord webhook notifications | `telegram_send()`, `discord_send()` | -| 5 | [`env`](./env.md) / `dotenv` | Secrets & Config | `.env` file loader and environment variable manager | `load()`, `get()`, `set()`, `all()` | -| 6 | [`ai`](./ai.md) | Artificial Intelligence | Universal LLM engine (OpenAI, DeepSeek, Claude, Gemini, Groq, Ollama, OpenRouter, etc.) | `ask()`, `set_provider()`, `set_endpoint()`, `set_key()`, `providers()` | -| 7 | [`sec`](./sec.md) | Cybersecurity | Port scanning, header auditing, subdomain recon, SSL inspection, DNS lookup | `scan_ports()`, `audit_headers()`, `subdomains()`, `ssl_check()`, `dns_lookup()`, `crack_md5()` | -| 8 | [`crypto`](./crypto.md) | Security | Cryptographic hashes, JWT signing/verifying, UUIDs, Base64 | `jwt_sign()`, `jwt_verify()`, `uuid()`, `hmac()`, `sha256()`, `md5()`, `base64_encode()` | -| 9 | [`system`](./system.md) / `hardware` | PC & Hardware Telemetry | Cross-platform GPU, CPU, RAM, battery, and OS hardware telemetry | `info()`, `gpu()`, `battery()`, `ram()`, `cpu()` | -| 10 | [`android`](./android.md) / `droidsec` | Mobile Security & Recon | Android device integrity audit, root detection, and static APK security analyzer | `device_info()`, `audit_device()`, `audit_apk()`, `audit_package()`, `check_root()` | -| 11 | [`proposal`](./proposal.md) | Fun & Cyber-Prank | Automated HTTP 500 love timeout & AI sentiment checker | `ask()`, `set_key()`, `set_system()`, `wish()`, `set_wish()` | -| 12 | [`http`](./http.md) | Networking | Web requests, REST APIs, and file downloads | `get()`, `post()`, `download()`, `status()` | -| 13 | [`file`](./file.md) | System I/O | Read, write, append, and inspect local files | `read()`, `write()`, `append()`, `exists()`, `delete()` | -| 14 | [`os`](./os.md) | System | Shell commands, environment variables, CLI args, directories | `cmd()`, `env()`, `cwd()`, `listdir()`, `mkdir()`, `args()`, `is_windows()` | -| 15 | [`math`](./math.md) | Mathematics | Math functions, trigonometry, and constants | `sqrt()`, `pow()`, `abs()`, `random()`, `round()`, `pi`, `e` | -| 16 | [`time`](./time.md) | System | Epoch time, timestamps, and execution delays | `now()`, `time()`, `sleep()` | -| 17 | [`json`](./json.md) | Data | Parsing and serialization of JSON payloads | `parse()`, `stringify()`, `mkstring()` | -| 18 | [`string`](./string.md) | Utilities | Advanced text manipulation and transformation | `split()`, `replace()`, `upper()`, `lower()`, `trim()`, `join()` | -| 19 | [`sqlite`](./sqlite.md) | Database | Lightweight embedded SQL relational database | `open()`, `query()`, `execute()`, `close()` | -| 20 | [`net`](./net.md) | Networking | Host pings, TCP port checks, and IP discovery | `ping()`, `port_open()`, `local_ip()`, `fetch()` | -| 21 | [`thread`](./thread.md) | Concurrency | Thread spawning, worker pools, and parallel execution | `spawn()`, `join()`, `pool()`, `sleep()` | -| 22 | [`youtube`](./youtube.md) / `yt` | Media & Video | YouTube video/audio download engine via APM | `get()`, `stream()`, `download()`, `title`, `duration` | - ---- -*Maintained by the AiraLang Core Engineering Team. Created by Er. Adam Eehan.* diff --git a/modules/ai.md b/modules/ai.md deleted file mode 100644 index 23fad10..0000000 --- a/modules/ai.md +++ /dev/null @@ -1,110 +0,0 @@ -# πŸ€– AiraLang `ai` Module -> **Universal World AI & LLM Integration Engine** -> Native multi-provider AI supporting Google Gemini, Groq, OpenAI, DeepSeek, OpenRouter, Anthropic Claude, Mistral AI, Ollama (Local/Offline), Together AI, Perplexity, Cerebras, and custom OpenAI-compatible endpoints. - -## Import -```aira -import "ai"; -``` - -## Supported World AI Providers -| Provider Key | Provider Name | Default Model | Key Prefix / Notes | -|---|---|---|---| -| `gemini` | Google Gemini | `gemini-1.5-flash` | Starts with `AIza` | -| `groq` | Groq Cloud | `openai/gpt-oss-120b` | Starts with `gsk_` | -| `openai` | OpenAI | `gpt-4o-mini` | Starts with `sk-` | -| `deepseek` | DeepSeek AI | `deepseek-chat` | Starts with `sk-` | -| `openrouter` | OpenRouter (300+ Models) | `meta-llama/llama-3.3-70b-instruct` | Starts with `sk-or-` | -| `anthropic` | Anthropic Claude | `claude-3-5-sonnet-20241022` | Starts with `sk-ant-` | -| `mistral` | Mistral AI | `mistral-small-latest` | Mistral API key | -| `ollama` | Ollama (Local / Offline) | `llama3.2` | `http://localhost:11434` (No key required) | -| `together` | Together AI | `meta-llama/Llama-3.3-70B-Instruct-Turbo` | Together API key | -| `perplexity` | Perplexity AI | `sonar` | Starts with `pplx-` | -| `cerebras` | Cerebras Fast Inference | `llama3.3-70b` | Starts with `csk-` | -| `custom` | Any Self-Hosted Server | Custom | vLLM, LM Studio, TGI, Localhost | - -## Methods -- `ai.ask(prompt, [model], [key], [system], [provider])`: Unified multi-provider prompt execution. -- `ai.set_key(api_key, [provider], [model])`: Configure API key with intelligent key prefix auto-detection. -- `ai.set_provider(provider_name, [key], [model])`: Switch the active AI provider. -- `ai.set_endpoint(url, [key], [model])`: Point to ANY custom OpenAI-compatible server (vLLM, LM Studio, Ollama). -- `ai.set_model(model_name)`: Override default model. -- `ai.set_system(prompt)`: Customize the AI engine system prompt/persona (default: official Aira persona). -- `ai.providers()`: Returns a dictionary of all registered world providers. -- `ai.chat(messages, [model], [key], [provider])`: Multi-turn conversational chat. -- `ai.summarize(text, [max_words], [provider])`: Summarize text within specified word count. - -### Direct Provider Shortcuts -- `ai.gemini(prompt, [model], [key])` -- `ai.groq(prompt, [model], [key])` -- `ai.openai(prompt, [model], [key])` -- `ai.deepseek(prompt, [model], [key])` -- `ai.openrouter(prompt, [model], [key])` -- `ai.anthropic(prompt, [model], [key])` -- `ai.mistral(prompt, [model], [key])` -- `ai.ollama(prompt, [model])` -- `ai.together(prompt, [model], [key])` -- `ai.perplexity(prompt, [model], [key])` -- `ai.cerebras(prompt, [model], [key])` - -## Examples - -### example -```aira -import "ai"; - -ai.set_key("YOUR_API_KEY"); -ai.set_provider("PROVIDER","MODEL"); - -while true{ - let user_input = input("Ask to AI : "); - - //EXIT CONTION - if user_input == "exit" { - say "Goood bye take care"; - break; - } - - //ai call - let replay = ai.ask(user_input); - say "Aira : " + replay; -} -``` - - - -### 1. Smart Auto-Routing -```aira -import "ai"; - -# OpenRouter key automatically routes to OpenRouter -ai.set_key("sk-or-v1-YOUR_KEY"); -say ai.ask("Explain quantum encryption"); -``` - - -### 2. DeepSeek AI -```aira -import "ai"; - -ai.set_provider("deepseek", "sk-YOUR_DEEPSEEK_KEY"); -say ai.ask("Write an optimized sorting algorithm in AiraLang"); -``` - -### 3. Local Offline AI with Ollama (Termux / PC) -```aira -import "ai"; - -# 100% offline, zero internet needed -ai.set_provider("ollama", model="llama3.2"); -say ai.ask("What is cybersecurity?"); -``` - -### 4. Custom Enterprise Server (vLLM / LM Studio) -```aira -import "ai"; - -ai.set_endpoint("http://192.168.1.50:8000/v1/chat/completions", "token", "my-custom-model"); -say ai.ask("Analyze log files"); -``` - diff --git a/modules/android.md b/modules/android.md deleted file mode 100644 index 368dc0f..0000000 --- a/modules/android.md +++ /dev/null @@ -1,98 +0,0 @@ -# πŸ“± `android` Module (AiraLang Native Android Security) - -Native Android security inspection, APK static analysis, and device hardening module engineered specifically for mobile application penetration testing and security auditing directly inside Termux and Linux environments. - -Can be imported as either: -```aira -import "android"; -# or -import "droidsec"; -``` - ---- - -## πŸ› οΈ Functions & Capabilities - -### 1. `android.device_info()` -Returns comprehensive hardware and operating system profile details: -- `brand`: Device brand (e.g. Redmi, Samsung, Google) -- `model`: Device hardware model code -- `manufacturer`: Hardware manufacturer -- `android_version`: Android OS release version (e.g. "16") -- `sdk_version`: Android API level integer (e.g. 36) -- `arch`: CPU architecture (e.g. arm64-v8a) -- `build_type`: OS build variant (e.g. "user", "userdebug") - -```aira -import "android"; -let dev = android.device_info(); -say "Device: " + dev.brand + " " + dev.model; -say "Android Version: " + dev.android_version + " (API " + dev.sdk_version + ")"; -``` - ---- - -### 2. `android.audit_device()` -Performs complete security posture and integrity audit on the host device: -- `is_rooted`: Boolean checking SU binaries (`/system/bin/su`, `/data/local/su`, Magisk paths). -- `bootloader_locked`: Boolean evaluating `ro.boot.flash.locked`. -- `verified_boot`: Android Verified Boot (AVB) state (e.g. "green", "yellow", "orange"). -- `is_debuggable_os`: Boolean checking if OS runs with `ro.debuggable=1`. -- `security_score`: Calculated integer security health score (0 - 100). -- `posture`: Overall rating: `"SECURE"`, `"MODERATE_RISK"`, or `"HIGH_RISK"`. -- `findings`: List of security risks discovered. -- `recommendations`: Hardening recommendations. - -```aira -import "android"; -let audit = android.audit_device(); -say "Device Posture: " + audit.posture; -say "Security Score: " + audit.security_score + "/100"; -say "Root Detected: " + audit.is_rooted; -say "Findings: " + audit.findings; -``` - ---- - -### 3. `android.audit_apk(apk_path)` -High-speed zero-dependency static APK security auditor: -- **Binary AXML String Extractor:** Decodes permissions and configuration flags from compiled `AndroidManifest.xml`. -- **Dangerous Permissions Identifier:** Flags high-risk permissions (SMS, Camera, Location, Audio, Contacts). -- **Security Misconfigurations:** Checks `debuggable`, `allowBackup`, and `usesCleartextTraffic`. -- **DEX Bytecode Key Scanner:** Scans compiled `.dex` files for exposed cloud keys (Google API `AIza...`, AWS `AKIA...`, plaintext HTTP URLs). -- **Signature Audit:** Checks for META-INF signatures and flags insecure Android Debug Keystores. - -```aira -import "android"; -let report = android.audit_apk("/sdcard/Download/target.apk"); -say "Package Name: " + report.package_name; -say "Risk Level: " + report.risk_level; -say "Dangerous Permissions: " + report.dangerous_permissions; -say "Exposed Keys: " + report.hardcoded_secrets; -say "Findings: " + report.findings; -``` - ---- - -### 4. `android.audit_package(package_name)` -Attempts to locate and audit an installed package by name. - -```aira -import "android"; -let report = android.audit_package("com.whatsapp"); -say report; -``` - ---- - -### 5. `android.check_root()` / `android.is_rooted()` -Quick boolean helper returning `true` if root / su binary is detected. - ---- - -### 6. `android.get_prop(prop_name)` -Queries any Android system property via `/system/bin/getprop`: -```aira -import "android"; -say "CPU ABI: " + android.get_prop("ro.product.cpu.abi"); -``` diff --git a/modules/bot.md b/modules/bot.md deleted file mode 100644 index 9942898..0000000 --- a/modules/bot.md +++ /dev/null @@ -1,27 +0,0 @@ -# πŸ€– AiraLang Module: `bot` - -The `bot` module provides 1-line notification and messaging integrations for Telegram and Discord bots. - ---- - -## πŸ“Œ Functions - -### 1. `bot.telegram_send(bot_token, chat_id, message, parse_mode="HTML")` -Sends a message via the official Telegram Bot API. -```airalang -import "bot"; - -let token = "123456:ABC-DEF..."; -let chat = "987654321"; -bot.telegram_send(token, chat, "AiraLang Alert: Port scan finished!"); -``` - -### 2. `bot.discord_send(webhook_url, content, username="Aira Bot", avatar_url=null)` -Dispatches an alert to a Discord channel via incoming webhook. -```airalang -bot.discord_send( - "https://discord.com/api/webhooks/...", - "Deployment completed on Vercel! πŸš€", - username="Aira CI/CD" -); -``` diff --git a/modules/crypto.md b/modules/crypto.md deleted file mode 100644 index 6e5a113..0000000 --- a/modules/crypto.md +++ /dev/null @@ -1,21 +0,0 @@ -# πŸ” AiraLang `crypto` Module -> **Cryptographic Hashing & Encoding** - -## Import -```aira -import "crypto"; -``` - -## Methods -- `crypto.md5(text)`: Generate MD5 hex digest. -- `crypto.sha256(text)`: Generate SHA-256 hex digest. -- `crypto.sha1(text)`: Generate SHA-1 hex digest. -- `crypto.base64_encode(text)`: Base64 encoding. -- `crypto.base64_decode(encoded)`: Base64 decoding. - -## Example -```aira -import "crypto"; - -say "Hash: " + crypto.sha256("admin123"); -``` diff --git a/modules/env.md b/modules/env.md deleted file mode 100644 index 15f04b0..0000000 --- a/modules/env.md +++ /dev/null @@ -1,30 +0,0 @@ -# πŸ›‘οΈ AiraLang Module: `env` - -The `env` module provides seamless `.env` file loading and secure environment variable access. - ---- - -## πŸ“Œ Functions - -### 1. `env.load(filepath=".env")` -Loads key-value pairs from a `.env` file into the environment. Returns `true` if loaded, `false` if file does not exist. -```airalang -import "env"; - -env.load(".env"); -``` - -### 2. `env.get(key, default=null)` -Retrieves an environment variable. -```airalang -let key = env.get("GEMINI_API_KEY", "default_key"); -``` - -### 3. `env.set(key, value)` -Sets an environment variable in the current process. -```airalang -env.set("APP_MODE", "development"); -``` - -### 4. `env.all()` -Returns a dictionary of all current environment variables. diff --git a/modules/file.md b/modules/file.md deleted file mode 100644 index 4606024..0000000 --- a/modules/file.md +++ /dev/null @@ -1,24 +0,0 @@ -# πŸ“ AiraLang `file` Module -> **Local File System I/O Operations** - -## Import -```aira -import "file"; -``` - -## Methods -- `file.read(path)`: Read entire text file. -- `file.write(path, content)`: Overwrite file with content. -- `file.append(path, content)`: Append content to file. -- `file.exists(path)`: Check if file exists. -- `file.delete(path)`: Remove file. -- `file.size(path)`: Get file size in bytes. - -## Example -```aira -import "file"; - -file.write("test.txt", "AiraLang v1.4.1"); -let text = file.read("test.txt"); -say text; -``` diff --git a/modules/http.md b/modules/http.md deleted file mode 100644 index 8d0b569..0000000 --- a/modules/http.md +++ /dev/null @@ -1,21 +0,0 @@ -# 🌐 AiraLang `http` Module -> **HTTP Networking & Web Request Client** - -## Import -```aira -import "http"; -``` - -## Methods -- `http.get(url, [headers])`: Perform HTTP GET request. -- `http.post(url, data_payload, [headers])`: Perform HTTP POST request. -- `http.download(url, destination_path)`: Download remote file to local disk. -- `http.status(url)`: Get HTTP response status code. - -## Example -```aira -import "http"; - -let html = http.get("https://httpbin.org/get"); -say html; -``` diff --git a/modules/json.md b/modules/json.md deleted file mode 100644 index 97d35c4..0000000 --- a/modules/json.md +++ /dev/null @@ -1,19 +0,0 @@ -# πŸ“‹ AiraLang `json` Module -> **JSON Parsing & Serialization** - -## Import -```aira -import "json"; -``` - -## Methods -- `json.parse(json_string)`: Parse JSON string into AiraLang dictionary or list. -- `json.stringify(obj, [indent=2])` / `json.mkstring()`: Serialize data structure to JSON. - -## Example -```aira -import "json"; - -let obj = json.parse("{"status": "ok", "code": 200}"); -say obj["status"]; -``` diff --git a/modules/math.md b/modules/math.md deleted file mode 100644 index 22ead9d..0000000 --- a/modules/math.md +++ /dev/null @@ -1,24 +0,0 @@ -# πŸ“ AiraLang `math` Module -> **Mathematical Functions & Constants** - -## Import -```aira -import "math"; -``` - -## Methods & Constants -- `math.sqrt(x)`: Square root. -- `math.floor(x)`, `math.ceil(x)`: Rounding down and up. -- `math.abs(x)`: Absolute value. -- `math.round(x, [decimals])`: Rounding. -- `math.pow(base, exp)`: Exponentiation. -- `math.random(low, high)`: Generate random integer or float. -- `math.pi`: $\pi$ constant (~3.14159265). -- `math.e`: Euler constant (~2.7182818). - -## Example -```aira -import "math"; - -say "Hypotenuse: " + math.sqrt(math.pow(3, 2) + math.pow(4, 2)); # 5.0 -``` diff --git a/modules/net.md b/modules/net.md deleted file mode 100644 index ee74b1c..0000000 --- a/modules/net.md +++ /dev/null @@ -1,21 +0,0 @@ -# πŸ“‘ AiraLang `net` Module -> **Low-Level Network Diagnostics & Sockets** - -## Import -```aira -import "net"; -``` - -## Methods -- `net.ping(host, [timeout=2])`: Check ICMP reachability. -- `net.port_open(host, port, [timeout=2])`: Test TCP socket connectivity. -- `net.local_ip()`: Retrieve current local network IP address. -- `net.fetch(url)`: Quick HTTP GET shortcut. - -## Example -```aira -import "net"; - -say "Local IP: " + net.local_ip(); -say "Gateway reachable: " + net.ping("1.1.1.1"); -``` diff --git a/modules/os.md b/modules/os.md deleted file mode 100644 index a5fd5bd..0000000 --- a/modules/os.md +++ /dev/null @@ -1,23 +0,0 @@ -# πŸ’» AiraLang `os` Module -> **Operating System Interaction & Shell Commands** - -## Import -```aira -import "os"; -``` - -## Methods -- `os.cmd(command)` / `os.system(command)`: Execute shell command and return stdout. -- `os.env(name, [default])`: Read environment variable. -- `os.platform()`: Return host OS platform (linux, darwin, win32). -- `os.cwd()`: Current working directory. -- `os.listdir([path])`: List files and directories. -- `os.mkdir(path)`: Create directory recursively. - -## Example -```aira -import "os"; - -say "OS: " + os.platform(); -say "Files: ", os.listdir("."); -``` diff --git a/modules/proposal.md b/modules/proposal.md deleted file mode 100644 index 91b1e25..0000000 --- a/modules/proposal.md +++ /dev/null @@ -1,27 +0,0 @@ -# πŸ’– AiraLang `proposal` Module -> **Cyber-Romance & Proposal Prank Engine** -> Features an automated HTTP 500 Server Love Timeout loop and an intelligent Lover Accept Checker AI with celebratory wishes. - -## Import -```aira -import "proposal"; -import "ai"; # Optional, for shared API key configuration -``` - -## Methods -- `proposal.ask(prompt="Do You Love Me : ", [api_key], [wish_enabled=True])`: Runs proposal prompt. Automatically enters an inescapable simulated HTTP 500 error loop until target answers affirmatively. -- `proposal.set_key(api_key)`: Sets Groq or Gemini API key for Lover Accept Checker AI sentiment analysis. -- `proposal.set_system(system_prompt)`: Customizes Lover Accept Checker AI persona. -- `proposal.set_wish(custom_wish)`: Sets a custom congratulatory message. -- `proposal.wish([custom_message])`: Triggers Aira celebratory wish immediately. - -## Example -```aira -import "proposal"; -import "ai"; - -ai.set_key("gsk_YOUR_GROQ_KEY"); - -proposal.ask("Do You Love Me : "); -say "mee too 🩷"; -``` diff --git a/modules/sec.md b/modules/sec.md deleted file mode 100644 index cc2d78d..0000000 --- a/modules/sec.md +++ /dev/null @@ -1,27 +0,0 @@ -# πŸ›‘οΈ AiraLang `sec` Module -> **Cybersecurity & Ethical Reconnaissance Engine** -> Built natively for security researchers, penetration testers, and cyber defenders. - -## Import -```aira -import "sec"; -``` - -## Methods -- `sec.scan_ports(host, ports, [timeout])`: Multi-threaded TCP port scanner. -- `sec.scan_port(host, port, [timeout])`: Single port check. -- `sec.banner(host, port, [timeout])`: Grab service banner. -- `sec.audit_headers(url)`: Security header audit (CSP, HSTS, X-Frame-Options) with grading. -- `sec.subdomains(domain)`: Discover subdomains via Certificate Transparency. -- `sec.hash_identify(hash_string)`: Identify hash algorithms (MD5, SHA1, SHA256, Bcrypt, etc.). -- `sec.crack_md5(hash, wordlist)`: Dictionary-based MD5 cracker. -- `sec.resolve(hostname)`: DNS host-to-IP resolution. -- `sec.reverse_dns(ip)`: Reverse DNS lookup. - -## Example -```aira -import "sec"; - -let open_ports = sec.scan_ports("google.com", [80, 443, 8080]); -say "Open Ports: ", open_ports; -``` diff --git a/modules/serve.md b/modules/serve.md deleted file mode 100644 index f8e336b..0000000 --- a/modules/serve.md +++ /dev/null @@ -1,43 +0,0 @@ -# 🌐 AiraLang Module: `serve` - -The `serve` module provides a native, zero-dependency micro web server engine directly inside AiraLang. Build REST APIs, microservices, and webhook endpoints with minimal code. - ---- - -## πŸ“Œ Functions - -### 1. `serve.route(path, handler_fn, method="GET")` -Registers a route endpoint. `handler_fn` receives a request dictionary containing `path`, `method`, `query`, `body`, and `headers`. -```airalang -import "serve"; - -serve.route("/api/hello", fn(req) { - return { - "status": "ok", - "message": "Hello from AiraLang Web Engine!", - "client_path": req["path"] - }; -}); -``` - -### 2. `serve.get(path, handler_fn)` -Shortcut to register a `GET` route. -```airalang -serve.get("/api/status", fn(req) { - return {"status": "online", "uptime": "100%"}; -}); -``` - -### 3. `serve.post(path, handler_fn)` -Shortcut to register a `POST` route. -```airalang -serve.post("/api/echo", fn(req) { - return {"received": req["body"]}; -}); -``` - -### 4. `serve.start(port=8080, host="0.0.0.0", background=false)` -Starts the HTTP server. If `background=true`, the server runs in a daemon thread so the script can continue executing. -```airalang -serve.start(port=8080); -``` diff --git a/modules/sqlite.md b/modules/sqlite.md deleted file mode 100644 index b8f83ee..0000000 --- a/modules/sqlite.md +++ /dev/null @@ -1,25 +0,0 @@ -# πŸ—„οΈ AiraLang `sqlite` Module -> **Embedded Relational SQL Database** - -## Import -```aira -import "sqlite"; -``` - -## Methods -- `sqlite.open(path)`: Open or create database file. -- `sqlite.execute(db, sql, [params])`: Execute DDL/DML statements (INSERT, UPDATE, DELETE). -- `sqlite.query(db, sql, [params])`: Execute SELECT and return rows as dictionary list. -- `sqlite.close(db)`: Close database connection. - -## Example -```aira -import "sqlite"; - -let db = sqlite.open("test.db"); -sqlite.execute(db, "CREATE TABLE IF NOT EXISTS logs (msg TEXT);"); -sqlite.execute(db, "INSERT INTO logs VALUES (?);", ["System Booted"]); -let rows = sqlite.query(db, "SELECT * FROM logs;"); -say rows; -sqlite.close(db); -``` diff --git a/modules/string.md b/modules/string.md deleted file mode 100644 index bb5ad6a..0000000 --- a/modules/string.md +++ /dev/null @@ -1,26 +0,0 @@ -# πŸ”€ AiraLang `string` Module -> **Advanced Text & String Utilities** - -## Import -```aira -import "string"; -``` - -## Methods -- `string.split(text, [delimiter])`: Split text into array. -- `string.replace(text, old, new)`: Replace occurrences. -- `string.upper(text)`: Convert to uppercase. -- `string.lower(text)`: Convert to lowercase. -- `string.trim(text)`: Strip whitespace. -- `string.length(text)`: Get length. -- `string.contains(text, sub)`: Check substring presence. -- `string.starts_with(text, prefix)`: Check prefix. -- `string.ends_with(text, suffix)`: Check suffix. -- `string.join(list, [sep])`: Join list into string. - -## Example -```aira -import "string"; - -say string.upper("hello world"); -``` diff --git a/modules/system.md b/modules/system.md deleted file mode 100644 index 98b6228..0000000 --- a/modules/system.md +++ /dev/null @@ -1,93 +0,0 @@ -# πŸ’» `system` Module (AiraLang Cross-Platform Hardware & OS) - -Native cross-platform system diagnostic, hardware telemetry, and host environment inspection module. Companion module to `android`, designed for PC, Laptop, and Server environments (Windows, Linux, and Termux). - -Can be imported as either: -```aira -import "system"; -# or -import "hardware"; -``` - ---- - -## πŸ› οΈ Functions & Capabilities - -### 1. `system.info()` -Returns comprehensive hardware and operating system telemetry in a unified dictionary: -- `platform`: Host OS platform identifier (`win32`, `linux`, etc.) -- `cpu`: CPU details (name, core count, architecture) -- `ram`: System memory metrics (total GB, available GB, used GB, percent used) -- `gpu`: GPU profile (NVIDIA model, VRAM total, free VRAM, driver version, status) -- `battery`: Power source and battery percentage - -```aira -import "system"; -let info = system.info(); -say "Platform: " + info.platform; -say "CPU: " + info.cpu.name; -say "RAM: " + info.ram.total_gb + " GB"; -``` - ---- - -### 2. `system.gpu()` -Detects dedicated and integrated graphics processing units, querying NVIDIA SMI on modern GPUs (e.g. RTX 3050, 4060, etc.): -- `name`: Full GPU brand and model -- `total_vram_mb`: Total video memory in Megabytes -- `free_vram_mb`: Available free VRAM -- `driver_version`: Installed NVIDIA driver version -- `temperature_c`: Current GPU die temperature in Celsius -- `status`: `"active"` or `"integrated_or_unavailable"` - -```aira -import "system"; -let gpu = system.gpu(); -say "GPU Model: " + gpu.name; -if (gpu.total_vram_mb > 0) { - say "VRAM: " + gpu.total_vram_mb + " MB"; -} -``` - ---- - -### 3. `system.battery()` -Inspects battery and charging status via native Windows Kernel32 / Linux power supply APIs: -- `percentage`: Battery state of charge (0 - 100%) -- `is_charging`: Boolean whether power is connected -- `power_source`: Detailed power source status - -```aira -import "system"; -let bat = system.battery(); -say "Battery: " + bat.percentage + "% | Charging: " + bat.is_charging; -``` - ---- - -### 4. `system.ram()` -Queries live RAM memory allocation: -- `total_gb`: Total physical RAM -- `available_gb`: Available free memory -- `used_gb`: Currently utilized memory -- `percent_used`: Memory load percentage (0 - 100) - -```aira -import "system"; -let mem = system.ram(); -say "RAM: " + mem.used_gb + " / " + mem.total_gb + " GB (" + mem.percent_used + "% used)"; -``` - ---- - -### 5. `system.cpu()` -Queries CPU architecture, core topology, and model identifier: -- `cores`: Logical core count -- `name`: Processor identifier string -- `architecture`: Machine architecture - -```aira -import "system"; -let cpu = system.cpu(); -say "CPU: " + cpu.name + " (" + cpu.cores + " Cores)"; -``` diff --git a/modules/term.md b/modules/term.md deleted file mode 100644 index 83bbe2e..0000000 --- a/modules/term.md +++ /dev/null @@ -1,50 +0,0 @@ -# 🎨 AiraLang Module: `term` - -The `term` module provides native terminal styling, ANSI colors, ASCII bounding boxes, data tables, animated spinners, and screen controls for building high-aesthetic CLI and cyber reconnaissance tools. - ---- - -## πŸ“Œ Functions - -### 1. `term.color(color_name, text)` -Returns text formatted with the specified ANSI color. -* **Colors supported:** `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, `white`, `bright_red`, `bright_green`, `bright_cyan`, `bold`, `dim`, `italic`, `underline`. -```airalang -import "term"; -say term.color("green", "Audit Passed Successfully!"); -``` - -### 2. `term.rainbow(text)` -Returns text with alternating bright rainbow color grading. -```airalang -say term.rainbow("AIRALANG v1.5.0 - CYBER ENGINE"); -``` - -### 3. `term.box(title, content, color="cyan", width=50)` -Renders a stylized Unicode framed box in the terminal. -```airalang -term.box("SECURITY SCAN REPORT", [ - "Target: google.com", - "Open Ports: 80, 443", - "Status: SECURE" -], "cyan"); -``` - -### 4. `term.table(headers, rows)` -Renders structured tabular data in an ASCII grid table. -```airalang -term.table(["Port", "Service", "State"], [ - ["22", "SSH", "Open"], - ["80", "HTTP", "Open"], - ["443", "HTTPS", "Open"] -]); -``` - -### 5. `term.spinner(message="Working...", seconds=1.5)` -Displays an asynchronous animated terminal braille spinner. -```airalang -term.spinner("Inspecting SSL certificate...", seconds=2); -``` - -### 6. `term.clear()` -Clears the active terminal screen. diff --git a/modules/thread.md b/modules/thread.md deleted file mode 100644 index 48d9893..0000000 --- a/modules/thread.md +++ /dev/null @@ -1,25 +0,0 @@ -# 🧡 AiraLang `thread` Module -> **Concurrency, Worker Pools & Multithreading** - -## Import -```aira -import "thread"; -``` - -## Methods -- `thread.spawn(fn, [args])`: Launch function in background thread. -- `thread.join(thread_handle, [timeout])`: Wait for thread completion. -- `thread.sleep(seconds)`: Thread sleep delay. -- `thread.pool(fn, items, [max_workers=5])`: Parallel execution over collection. - -## Example -```aira -import "thread"; - -fn task(id) { - return "Task " + id + " done"; -} - -let res = thread.pool(task, [1, 2, 3, 4], 4); -say res; -``` diff --git a/modules/time.md b/modules/time.md deleted file mode 100644 index dd02861..0000000 --- a/modules/time.md +++ /dev/null @@ -1,21 +0,0 @@ -# ⏱️ AiraLang `time` Module -> **Time, Clock & Sleep Utilities** - -## Import -```aira -import "time"; -``` - -## Methods -- `time.now()`: Formatted current timestamp (`YYYY-MM-DD HH:MM:SS`). -- `time.time()`: Unix epoch timestamp in seconds. -- `time.sleep(seconds)`: Pause thread execution. - -## Example -```aira -import "time"; - -say "Start: " + time.now(); -time.sleep(1); -say "End: " + time.now(); -``` diff --git a/modules/webhook.md b/modules/webhook.md deleted file mode 100644 index ee01212..0000000 --- a/modules/webhook.md +++ /dev/null @@ -1,29 +0,0 @@ -# ⚑ AiraLang Module: `webhook` - -The `webhook` module enables instant event-driven webhook dispatching and lightweight background webhook receivers. - ---- - -## πŸ“Œ Functions - -### 1. `webhook.send(url, payload, headers=null, timeout=10)` -Sends an HTTP POST JSON payload to the target webhook URL. -```airalang -import "webhook"; - -let res = webhook.send("https://webhook.site/test", { - "event": "alert", - "user": "adam", - "timestamp": "2026-10-12" -}); -say f"Webhook response status: {res['status']}"; -``` - -### 2. `webhook.listen(port, callback_handler)` -Spins up a background HTTP webhook listener. Any incoming POST request payload is parsed and passed to `callback_handler`. -```airalang -webhook.listen(5000, fn(req) { - say f"Received webhook on {req['path']}: {req['body']}"; - return {"status": "processed"}; -}); -``` diff --git a/modules/youtube.md b/modules/youtube.md deleted file mode 100644 index 6ae4438..0000000 --- a/modules/youtube.md +++ /dev/null @@ -1,46 +0,0 @@ -# 🎬 AiraLang `youtube` Module -> **YouTube Video and Audio Downloader Engine (via APM)** - -## Installation -```bash -aira install youtube -# or -airalang install youtube -``` - -## Import -```aira -import "youtube"; -// or alias: -import "yt"; -``` - -## Methods & Properties -- `youtube.get(url)`: Fetches video metadata and returns a `video` object. - - `video.title`: Video title string. - - `video.duration`: Duration in seconds. - - `video.author`: Channel / uploader name. - - `video.views`: Video view count. - - `video.stream(format)`: Returns a `stream` object (format can be `"mp4"` or `"mp3"`). - - `stream.download([save_path])`: Downloads the stream to specified file or default title. -- `os.save(filename)`: Configures and creates the destination file path. - -## Example -```aira -import "youtube"; -import "os"; - -let url = input("Enter Your URL Here : "); - -let video = youtube.get(url); -say "Video Title : " + video.title; - -let stream = video.stream("mp4"); - -let save = os.save("video.mp4"); - -say "Starting Download..."; -stream.download(save); - -say "Download Finished Successfully!"; -``` diff --git a/s1duo/Makefile b/s1duo/Makefile deleted file mode 100644 index ca0020b..0000000 --- a/s1duo/Makefile +++ /dev/null @@ -1,31 +0,0 @@ -CC = clang -CFLAGS = -O3 -Wall -Wextra -Wno-unused-parameter -Iinclude -D_FORTIFY_SOURCE=2 -fstack-protector-strong -fPIE -LDFLAGS = -pie -Wl,-z,relro,-z,now -lm - -SRCS = src/common.c src/lexer.c src/value.c src/ast.c src/parser.c src/env.c src/modules.c src/evaluator.c src/elf_emitter.c src/main.c -OBJS = $(SRCS:.c=.o) -TARGET = bin/airalang -INSTALL_DIR = /data/data/com.termux/files/usr/bin - -all: $(TARGET) - -$(TARGET): $(OBJS) - @mkdir -p bin - $(CC) $(OBJS) -o $(TARGET) $(LDFLAGS) - @echo "\033[1;32m[βœ“] AiraLang S1 Duo Native Binary successfully compiled!\033[0m" - -%.o: %.c - $(CC) $(CFLAGS) -c $< -o $@ - -install: $(TARGET) - @mkdir -p $(INSTALL_DIR) - cp $(TARGET) $(INSTALL_DIR)/airalang - cp $(TARGET) $(INSTALL_DIR)/airalang3 - chmod 755 $(INSTALL_DIR)/airalang $(INSTALL_DIR)/airalang3 - @echo "\033[1;32m[βœ“] Installed airalang and airalang3 to $(INSTALL_DIR)\033[0m" - -clean: - rm -rf src/*.o bin/ - @echo "\033[1;33m[*] Cleaned build artifacts.\033[0m" - -.PHONY: all clean install diff --git a/s1duo/include/ast.h b/s1duo/include/ast.h deleted file mode 100644 index 456f8c4..0000000 --- a/s1duo/include/ast.h +++ /dev/null @@ -1,189 +0,0 @@ -#ifndef AIRA_AST_H -#define AIRA_AST_H - -#include "token.h" -#include "value.h" - -typedef enum { - STMT_PROGRAM, - STMT_LET, - STMT_ASSIGN, - STMT_INDEX_ASSIGN, - STMT_MEMBER_ASSIGN, - STMT_SAY, - STMT_PRINT, - STMT_IF, - STMT_WHILE, - STMT_FOR_IN, - STMT_FN_DEF, - STMT_RETURN, - STMT_BREAK, - STMT_CONTINUE, - STMT_BLOCK, - STMT_EXPR, - STMT_IMPORT -} StmtType; - -typedef enum { - EXPR_LITERAL, - EXPR_IDENTIFIER, - EXPR_BINARY, - EXPR_UNARY, - EXPR_CALL, - EXPR_INDEX, - EXPR_MEMBER, - EXPR_LIST, - EXPR_DICT -} ExprType; - -typedef struct ExprNode ExprNode; -typedef struct StmtNode StmtNode; - -struct ExprNode { - ExprType type; - int line; - int col; - union { - AiraValue literal; - char* identifier; - struct { - TokenType op; - ExprNode* left; - ExprNode* right; - } binary; - struct { - TokenType op; - ExprNode* right; - } unary; - struct { - ExprNode* callee; - ExprNode** args; - int arg_count; - } call; - struct { - ExprNode* target; - ExprNode* index; - } index_access; - struct { - ExprNode* target; - char* member; - } member_access; - struct { - ExprNode** elements; - int count; - } list; - struct { - char** keys; - ExprNode** values; - int count; - } dict; - } as; -}; - -struct StmtNode { - StmtType type; - int line; - int col; - union { - struct { - StmtNode** statements; - int count; - } program; - struct { - char* name; - ExprNode* init_expr; - } let_stmt; - struct { - char* name; - TokenType op; - ExprNode* expr; - } assign; - struct { - ExprNode* target; - ExprNode* index; - ExprNode* expr; - } index_assign; - struct { - ExprNode* target; - char* member; - ExprNode* expr; - } member_assign; - struct { - ExprNode** expressions; - int count; - } say_stmt; - struct { - ExprNode** expressions; - int count; - } print_stmt; - struct { - ExprNode* condition; - StmtNode* then_branch; - StmtNode* else_branch; - } if_stmt; - struct { - ExprNode* condition; - StmtNode* body; - } while_stmt; - struct { - char* var_name; - ExprNode* iterable; - StmtNode* body; - } for_in_stmt; - struct { - char* name; - char** params; - int param_count; - StmtNode* body; - } fn_def; - struct { - ExprNode* expr; - } return_stmt; - struct { - StmtNode** statements; - int count; - } block; - struct { - ExprNode* expr; - } expr_stmt; - struct { - char* module_name; - char* source; - char* alias; - } import_stmt; - } as; -}; - -/* AST Constructors */ -ExprNode* expr_literal(AiraValue val, int line, int col); -ExprNode* expr_identifier(const char* name, int line, int col); -ExprNode* expr_binary(TokenType op, ExprNode* left, ExprNode* right, int line, int col); -ExprNode* expr_unary(TokenType op, ExprNode* right, int line, int col); -ExprNode* expr_call(ExprNode* callee, ExprNode** args, int count, int line, int col); -ExprNode* expr_index(ExprNode* target, ExprNode* index, int line, int col); -ExprNode* expr_member(ExprNode* target, const char* member, int line, int col); -ExprNode* expr_list(ExprNode** elements, int count, int line, int col); -ExprNode* expr_dict(char** keys, ExprNode** values, int count, int line, int col); - -StmtNode* stmt_program(StmtNode** statements, int count, int line, int col); -StmtNode* stmt_let(const char* name, ExprNode* init_expr, int line, int col); -StmtNode* stmt_assign(const char* name, TokenType op, ExprNode* expr, int line, int col); -StmtNode* stmt_index_assign(ExprNode* target, ExprNode* index, ExprNode* expr, int line, int col); -StmtNode* stmt_member_assign(ExprNode* target, const char* member, ExprNode* expr, int line, int col); -StmtNode* stmt_say(ExprNode** expressions, int count, int line, int col); -StmtNode* stmt_print(ExprNode** expressions, int count, int line, int col); -StmtNode* stmt_if(ExprNode* condition, StmtNode* then_b, StmtNode* else_b, int line, int col); -StmtNode* stmt_while(ExprNode* condition, StmtNode* body, int line, int col); -StmtNode* stmt_for_in(const char* var_name, ExprNode* iterable, StmtNode* body, int line, int col); -StmtNode* stmt_fn_def(const char* name, char** params, int param_count, StmtNode* body, int line, int col); -StmtNode* stmt_return(ExprNode* expr, int line, int col); -StmtNode* stmt_break(int line, int col); -StmtNode* stmt_continue(int line, int col); -StmtNode* stmt_block(StmtNode** statements, int count, int line, int col); -StmtNode* stmt_expr(ExprNode* expr, int line, int col); -StmtNode* stmt_import(const char* mod, const char* source, const char* alias, int line, int col); - -void expr_free(ExprNode* expr); -void stmt_free(StmtNode* stmt); - -#endif /* AIRA_AST_H */ diff --git a/s1duo/include/common.h b/s1duo/include/common.h deleted file mode 100644 index bb40283..0000000 --- a/s1duo/include/common.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef AIRA_COMMON_H -#define AIRA_COMMON_H - -#include -#include -#include -#include -#include -#include -#include - -#define AIRA_VERSION "3.0.0 (S1 Duo Edition)" -#define AIRA_CODENAME "S1 Duo Flagship" -#define AIRA_ARCHITECT "Adam Eehan (Founder & CEO, Aira Group of Technology)" - -/* Execution Limits */ -#define AIRA_MAX_RECURSION_DEPTH 10000 -#define AIRA_MAX_STRING_LEN (128 * 1024 * 1024) /* 128 MB */ - -/* ANSI Color Formatting */ -#define COLOR_RESET "\033[0m" -#define COLOR_RED "\033[1;31m" -#define COLOR_GREEN "\033[1;32m" -#define COLOR_YELLOW "\033[1;33m" -#define COLOR_BLUE "\033[1;34m" -#define COLOR_MAGENTA "\033[1;35m" -#define COLOR_CYAN "\033[1;36m" -#define COLOR_WHITE "\033[1;37m" -#define COLOR_BOLD "\033[1m" -#define COLOR_DIM "\033[2m" - -/* Safe Memory Allocation Functions */ -void* aira_malloc(size_t size); -void* aira_calloc(size_t num, size_t size); -void* aira_realloc(void* ptr, size_t new_size); -void aira_free(void* ptr); -char* aira_strdup(const char* s); -char* aira_strndup(const char* s, size_t n); - -/* Diagnostic Logging */ -void aira_panic(const char* fmt, ...); -void aira_error_at(const char* filename, int line, int col, const char* fmt, ...); - -/* Dynamic String Buffer */ -typedef struct { - char* data; - size_t length; - size_t capacity; -} AiraStringBuilder; - -void sb_init(AiraStringBuilder* sb); -void sb_append(AiraStringBuilder* sb, const char* str); -void sb_append_len(AiraStringBuilder* sb, const char* str, size_t len); -void sb_append_char(AiraStringBuilder* sb, char c); -char* sb_finish(AiraStringBuilder* sb); -void sb_free(AiraStringBuilder* sb); - -#endif /* AIRA_COMMON_H */ diff --git a/s1duo/include/elf_emitter.h b/s1duo/include/elf_emitter.h deleted file mode 100644 index 35fc705..0000000 --- a/s1duo/include/elf_emitter.h +++ /dev/null @@ -1,34 +0,0 @@ -#ifndef AIRA_ELF_EMITTER_H -#define AIRA_ELF_EMITTER_H - -#include "ast.h" - -#define ELF_MAGIC "\x7f\x45\x4c\x46" -#define EM_AARCH64 0xB7 -#define EM_X86_64 0x3E - -typedef enum { - ARCH_ARM64, - ARCH_X86_64 -} TargetArch; - -typedef struct { - TargetArch arch; - uint8_t* code_buf; - size_t code_len; - size_t code_cap; - - uint8_t* data_buf; - size_t data_len; - size_t data_cap; - - uint64_t base_vaddr; -} ElfEmitter; - -void elf_emitter_init(ElfEmitter* emitter, TargetArch arch); -void elf_emitter_free(ElfEmitter* emitter); - -/* Binary File Generation */ -bool elf_emitter_compile_ast(ElfEmitter* emitter, StmtNode* ast, const char* output_binary); - -#endif /* AIRA_ELF_EMITTER_H */ diff --git a/s1duo/include/env.h b/s1duo/include/env.h deleted file mode 100644 index 4248f55..0000000 --- a/s1duo/include/env.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef AIRA_ENV_H -#define AIRA_ENV_H - -#include "value.h" - -typedef struct Environment { - struct Environment* parent; - char** names; - AiraValue* values; - int count; - int capacity; -} Environment; - -Environment* env_new(Environment* parent); -void env_free(Environment* env); -void env_define(Environment* env, const char* name, AiraValue val); -bool env_get(Environment* env, const char* name, AiraValue* out_val); -bool env_assign(Environment* env, const char* name, AiraValue val); - -#endif /* AIRA_ENV_H */ diff --git a/s1duo/include/evaluator.h b/s1duo/include/evaluator.h deleted file mode 100644 index 0e562c9..0000000 --- a/s1duo/include/evaluator.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef AIRA_EVALUATOR_H -#define AIRA_EVALUATOR_H - -#include "ast.h" -#include "env.h" - -typedef enum { - EXEC_OK = 0, - EXEC_RETURN, - EXEC_BREAK, - EXEC_CONTINUE, - EXEC_ERROR -} ExecResult; - -typedef struct { - ExecResult type; - AiraValue value; -} EvalSignal; - -typedef struct { - Environment* global_env; - int call_depth; - bool had_runtime_error; -} Evaluator; - -void evaluator_init(Evaluator* eval); -void evaluator_cleanup(Evaluator* eval); -AiraValue eval_expression(Evaluator* eval, Environment* env, ExprNode* expr); -EvalSignal eval_statement(Evaluator* eval, Environment* env, StmtNode* stmt); -void eval_program(Evaluator* eval, StmtNode* program); - -#endif /* AIRA_EVALUATOR_H */ diff --git a/s1duo/include/lexer.h b/s1duo/include/lexer.h deleted file mode 100644 index 066fb5c..0000000 --- a/s1duo/include/lexer.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef AIRA_LEXER_H -#define AIRA_LEXER_H - -#include "token.h" - -typedef struct { - const char* source; - const char* filename; - size_t length; - size_t current; - int line; - int col; -} Lexer; - -void lexer_init(Lexer* lexer, const char* source, const char* filename); -Token lexer_next_token(Lexer* lexer); - -#endif /* AIRA_LEXER_H */ diff --git a/s1duo/include/modules.h b/s1duo/include/modules.h deleted file mode 100644 index 3aff434..0000000 --- a/s1duo/include/modules.h +++ /dev/null @@ -1,13 +0,0 @@ -#ifndef AIRA_MODULES_H -#define AIRA_MODULES_H - -#include "value.h" -#include "env.h" - -void register_builtin_globals(Environment* env); -AiraValue load_builtin_module(const char* name); - -/* Pure C SHA256 */ -void aira_sha256(const uint8_t* data, size_t len, char output[65]); - -#endif /* AIRA_MODULES_H */ diff --git a/s1duo/include/parser.h b/s1duo/include/parser.h deleted file mode 100644 index a6e704b..0000000 --- a/s1duo/include/parser.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef AIRA_PARSER_H -#define AIRA_PARSER_H - -#include "lexer.h" -#include "ast.h" - -typedef struct { - Lexer lexer; - Token current; - Token previous; - bool had_error; - bool panic_mode; - const char* filename; -} Parser; - -void parser_init(Parser* parser, const char* source, const char* filename); -StmtNode* parser_parse(Parser* parser); - -#endif /* AIRA_PARSER_H */ diff --git a/s1duo/include/token.h b/s1duo/include/token.h deleted file mode 100644 index 5a47d77..0000000 --- a/s1duo/include/token.h +++ /dev/null @@ -1,92 +0,0 @@ -#ifndef AIRA_TOKEN_H -#define AIRA_TOKEN_H - -#include "common.h" - -typedef enum { - TOKEN_EOF = 0, - TOKEN_ERROR, - - /* Literals */ - TOKEN_NUMBER, - TOKEN_STRING, - TOKEN_IDENTIFIER, - - /* Keywords */ - TOKEN_LET, - TOKEN_SAY, - TOKEN_PRINT, - TOKEN_IF, - TOKEN_ELSE, - TOKEN_WHILE, - TOKEN_FOR, - TOKEN_IN, - TOKEN_FN, - TOKEN_RETURN, - TOKEN_IMPORT, - TOKEN_FROM, - TOKEN_TRUE, - TOKEN_FALSE, - TOKEN_NULL, - TOKEN_AND, - TOKEN_OR, - TOKEN_NOT, - TOKEN_TRY, - TOKEN_CATCH, - TOKEN_THROW, - TOKEN_CLASS, - TOKEN_NEW, - TOKEN_THIS, - TOKEN_BREAK, - TOKEN_CONTINUE, - - /* Arithmetic & Assignment */ - TOKEN_PLUS, /* + */ - TOKEN_MINUS, /* - */ - TOKEN_STAR, /* * */ - TOKEN_SLASH, /* / */ - TOKEN_PERCENT, /* % */ - TOKEN_ASSIGN, /* = */ - TOKEN_PLUS_ASSIGN, /* += */ - TOKEN_MINUS_ASSIGN, /* -= */ - TOKEN_STAR_ASSIGN, /* *= */ - TOKEN_SLASH_ASSIGN, /* /= */ - TOKEN_MOD_ASSIGN, /* %= */ - - /* Comparison & Logical */ - TOKEN_EQUAL_EQUAL, /* == */ - TOKEN_BANG_EQUAL, /* != */ - TOKEN_LESS, /* < */ - TOKEN_LESS_EQUAL, /* <= */ - TOKEN_GREATER, /* > */ - TOKEN_GREATER_EQUAL,/* >= */ - TOKEN_BANG, /* ! */ - TOKEN_AND_AND, /* && */ - TOKEN_OR_OR, /* || */ - - /* Delimiters & Punctuation */ - TOKEN_LPAREN, /* ( */ - TOKEN_RPAREN, /* ) */ - TOKEN_LBRACE, /* { */ - TOKEN_RBRACE, /* } */ - TOKEN_LBRACKET, /* [ */ - TOKEN_RBRACKET, /* ] */ - TOKEN_COMMA, /* , */ - TOKEN_DOT, /* . */ - TOKEN_COLON, /* : */ - TOKEN_SEMICOLON, /* ; */ - TOKEN_AT /* @ */ -} TokenType; - -typedef struct { - TokenType type; - char* text; - int line; - int col; - double num_val; -} Token; - -const char* token_type_name(TokenType type); -void token_free(Token* token); - -#endif /* AIRA_TOKEN_H */ diff --git a/s1duo/include/value.h b/s1duo/include/value.h deleted file mode 100644 index 548e7fc..0000000 --- a/s1duo/include/value.h +++ /dev/null @@ -1,106 +0,0 @@ -#ifndef AIRA_VALUE_H -#define AIRA_VALUE_H - -#include "common.h" - -typedef enum { - VAL_NULL = 0, - VAL_BOOL, - VAL_INT, - VAL_FLOAT, - VAL_STRING, - VAL_LIST, - VAL_DICT, - VAL_BUILTIN_FN, - VAL_FN, - VAL_MODULE -} ValueType; - -struct AiraValue; -struct Environment; -struct StmtNode; - -typedef struct AiraValue (*AiraBuiltinFn)(int arg_count, struct AiraValue* args); - -typedef struct { - struct AiraValue* elements; - int count; - int capacity; -} AiraList; - -typedef struct { - char** keys; - struct AiraValue* values; - int count; - int capacity; -} AiraDict; - -typedef struct { - const char* name; - struct StmtNode* node; - struct Environment* closure; -} AiraFunction; - -typedef struct { - const char* name; - AiraDict* members; -} AiraModule; - -typedef struct AiraValue { - ValueType type; - union { - bool boolean; - int64_t integer; - double floating; - char* string; - AiraList* list; - AiraDict* dict; - AiraBuiltinFn builtin; - AiraFunction* fn; - AiraModule* module; - } as; -} AiraValue; - -/* Value Constructors */ -AiraValue val_null(void); -AiraValue val_bool(bool b); -AiraValue val_int(int64_t i); -AiraValue val_float(double f); -AiraValue val_string(const char* s); -AiraValue val_string_take(char* s); -AiraValue val_list(void); -AiraValue val_dict(void); -AiraValue val_builtin(AiraBuiltinFn fn); -AiraValue val_function(const char* name, struct StmtNode* node, struct Environment* closure); -AiraValue val_module(const char* name); - -/* Value Operations */ -bool val_is_truthy(AiraValue v); -bool val_equals(AiraValue a, AiraValue b); -int val_compare(AiraValue a, AiraValue b); -AiraValue val_add(AiraValue a, AiraValue b); -AiraValue val_sub(AiraValue a, AiraValue b); -AiraValue val_mul(AiraValue a, AiraValue b); -AiraValue val_div(AiraValue a, AiraValue b); -AiraValue val_mod(AiraValue a, AiraValue b); - -/* String representation & Print */ -char* val_to_string(AiraValue v); -void val_print(AiraValue v); -void val_free(AiraValue* v); -AiraValue val_copy(AiraValue v); - -/* List and Dict Helpers */ -void list_append(AiraList* list, AiraValue v); -AiraValue list_get(AiraList* list, int index); -void list_set(AiraList* list, int index, AiraValue v); -AiraValue list_pop(AiraList* list); - -void dict_set(AiraDict* dict, const char* key, AiraValue v); -AiraValue dict_get(AiraDict* dict, const char* key); -bool dict_has(AiraDict* dict, const char* key); - -/* Fast no-op verify macro */ -#define val_verify_security(v) ((void)0) - -#endif /* AIRA_VALUE_H */ diff --git a/s1duo/src/ast.c b/s1duo/src/ast.c deleted file mode 100644 index 0a0daac..0000000 --- a/s1duo/src/ast.c +++ /dev/null @@ -1,396 +0,0 @@ -#include "../include/ast.h" - -ExprNode* expr_literal(AiraValue val, int line, int col) { - ExprNode* e = (ExprNode*)aira_malloc(sizeof(ExprNode)); - e->type = EXPR_LITERAL; - e->line = line; - e->col = col; - e->as.literal = val; - return e; -} - -ExprNode* expr_identifier(const char* name, int line, int col) { - ExprNode* e = (ExprNode*)aira_malloc(sizeof(ExprNode)); - e->type = EXPR_IDENTIFIER; - e->line = line; - e->col = col; - e->as.identifier = aira_strdup(name); - return e; -} - -ExprNode* expr_binary(TokenType op, ExprNode* left, ExprNode* right, int line, int col) { - ExprNode* e = (ExprNode*)aira_malloc(sizeof(ExprNode)); - e->type = EXPR_BINARY; - e->line = line; - e->col = col; - e->as.binary.op = op; - e->as.binary.left = left; - e->as.binary.right = right; - return e; -} - -ExprNode* expr_unary(TokenType op, ExprNode* right, int line, int col) { - ExprNode* e = (ExprNode*)aira_malloc(sizeof(ExprNode)); - e->type = EXPR_UNARY; - e->line = line; - e->col = col; - e->as.unary.op = op; - e->as.unary.right = right; - return e; -} - -ExprNode* expr_call(ExprNode* callee, ExprNode** args, int count, int line, int col) { - ExprNode* e = (ExprNode*)aira_malloc(sizeof(ExprNode)); - e->type = EXPR_CALL; - e->line = line; - e->col = col; - e->as.call.callee = callee; - e->as.call.args = args; - e->as.call.arg_count = count; - return e; -} - -ExprNode* expr_index(ExprNode* target, ExprNode* index, int line, int col) { - ExprNode* e = (ExprNode*)aira_malloc(sizeof(ExprNode)); - e->type = EXPR_INDEX; - e->line = line; - e->col = col; - e->as.index_access.target = target; - e->as.index_access.index = index; - return e; -} - -ExprNode* expr_member(ExprNode* target, const char* member, int line, int col) { - ExprNode* e = (ExprNode*)aira_malloc(sizeof(ExprNode)); - e->type = EXPR_MEMBER; - e->line = line; - e->col = col; - e->as.member_access.target = target; - e->as.member_access.member = aira_strdup(member); - return e; -} - -ExprNode* expr_list(ExprNode** elements, int count, int line, int col) { - ExprNode* e = (ExprNode*)aira_malloc(sizeof(ExprNode)); - e->type = EXPR_LIST; - e->line = line; - e->col = col; - e->as.list.elements = elements; - e->as.list.count = count; - return e; -} - -ExprNode* expr_dict(char** keys, ExprNode** values, int count, int line, int col) { - ExprNode* e = (ExprNode*)aira_malloc(sizeof(ExprNode)); - e->type = EXPR_DICT; - e->line = line; - e->col = col; - e->as.dict.keys = keys; - e->as.dict.values = values; - e->as.dict.count = count; - return e; -} - -StmtNode* stmt_program(StmtNode** statements, int count, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_PROGRAM; - s->line = line; - s->col = col; - s->as.program.statements = statements; - s->as.program.count = count; - return s; -} - -StmtNode* stmt_let(const char* name, ExprNode* init_expr, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_LET; - s->line = line; - s->col = col; - s->as.let_stmt.name = aira_strdup(name); - s->as.let_stmt.init_expr = init_expr; - return s; -} - -StmtNode* stmt_assign(const char* name, TokenType op, ExprNode* expr, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_ASSIGN; - s->line = line; - s->col = col; - s->as.assign.name = aira_strdup(name); - s->as.assign.op = op; - s->as.assign.expr = expr; - return s; -} - -StmtNode* stmt_index_assign(ExprNode* target, ExprNode* index, ExprNode* expr, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_INDEX_ASSIGN; - s->line = line; - s->col = col; - s->as.index_assign.target = target; - s->as.index_assign.index = index; - s->as.index_assign.expr = expr; - return s; -} - -StmtNode* stmt_member_assign(ExprNode* target, const char* member, ExprNode* expr, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_MEMBER_ASSIGN; - s->line = line; - s->col = col; - s->as.member_assign.target = target; - s->as.member_assign.member = aira_strdup(member); - s->as.member_assign.expr = expr; - return s; -} - -StmtNode* stmt_say(ExprNode** expressions, int count, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_SAY; - s->line = line; - s->col = col; - s->as.say_stmt.expressions = expressions; - s->as.say_stmt.count = count; - return s; -} - -StmtNode* stmt_print(ExprNode** expressions, int count, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_PRINT; - s->line = line; - s->col = col; - s->as.print_stmt.expressions = expressions; - s->as.print_stmt.count = count; - return s; -} - -StmtNode* stmt_if(ExprNode* condition, StmtNode* then_b, StmtNode* else_b, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_IF; - s->line = line; - s->col = col; - s->as.if_stmt.condition = condition; - s->as.if_stmt.then_branch = then_b; - s->as.if_stmt.else_branch = else_b; - return s; -} - -StmtNode* stmt_while(ExprNode* condition, StmtNode* body, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_WHILE; - s->line = line; - s->col = col; - s->as.while_stmt.condition = condition; - s->as.while_stmt.body = body; - return s; -} - -StmtNode* stmt_for_in(const char* var_name, ExprNode* iterable, StmtNode* body, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_FOR_IN; - s->line = line; - s->col = col; - s->as.for_in_stmt.var_name = aira_strdup(var_name); - s->as.for_in_stmt.iterable = iterable; - s->as.for_in_stmt.body = body; - return s; -} - -StmtNode* stmt_fn_def(const char* name, char** params, int param_count, StmtNode* body, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_FN_DEF; - s->line = line; - s->col = col; - s->as.fn_def.name = aira_strdup(name); - s->as.fn_def.params = params; - s->as.fn_def.param_count = param_count; - s->as.fn_def.body = body; - return s; -} - -StmtNode* stmt_return(ExprNode* expr, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_RETURN; - s->line = line; - s->col = col; - s->as.return_stmt.expr = expr; - return s; -} - -StmtNode* stmt_break(int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_BREAK; - s->line = line; - s->col = col; - return s; -} - -StmtNode* stmt_continue(int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_CONTINUE; - s->line = line; - s->col = col; - return s; -} - -StmtNode* stmt_block(StmtNode** statements, int count, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_BLOCK; - s->line = line; - s->col = col; - s->as.block.statements = statements; - s->as.block.count = count; - return s; -} - -StmtNode* stmt_expr(ExprNode* expr, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_EXPR; - s->line = line; - s->col = col; - s->as.expr_stmt.expr = expr; - return s; -} - -StmtNode* stmt_import(const char* mod, const char* source, const char* alias, int line, int col) { - StmtNode* s = (StmtNode*)aira_malloc(sizeof(StmtNode)); - s->type = STMT_IMPORT; - s->line = line; - s->col = col; - s->as.import_stmt.module_name = aira_strdup(mod); - s->as.import_stmt.source = source ? aira_strdup(source) : NULL; - s->as.import_stmt.alias = alias ? aira_strdup(alias) : NULL; - return s; -} - -void expr_free(ExprNode* expr) { - if (!expr) return; - switch (expr->type) { - case EXPR_IDENTIFIER: - aira_free(expr->as.identifier); - break; - case EXPR_BINARY: - expr_free(expr->as.binary.left); - expr_free(expr->as.binary.right); - break; - case EXPR_UNARY: - expr_free(expr->as.unary.right); - break; - case EXPR_CALL: - expr_free(expr->as.call.callee); - for (int i = 0; i < expr->as.call.arg_count; i++) { - expr_free(expr->as.call.args[i]); - } - aira_free(expr->as.call.args); - break; - case EXPR_INDEX: - expr_free(expr->as.index_access.target); - expr_free(expr->as.index_access.index); - break; - case EXPR_MEMBER: - expr_free(expr->as.member_access.target); - aira_free(expr->as.member_access.member); - break; - case EXPR_LIST: - for (int i = 0; i < expr->as.list.count; i++) { - expr_free(expr->as.list.elements[i]); - } - aira_free(expr->as.list.elements); - break; - case EXPR_DICT: - for (int i = 0; i < expr->as.dict.count; i++) { - aira_free(expr->as.dict.keys[i]); - expr_free(expr->as.dict.values[i]); - } - aira_free(expr->as.dict.keys); - aira_free(expr->as.dict.values); - break; - default: - break; - } - aira_free(expr); -} - -void stmt_free(StmtNode* stmt) { - if (!stmt) return; - switch (stmt->type) { - case STMT_PROGRAM: - for (int i = 0; i < stmt->as.program.count; i++) { - stmt_free(stmt->as.program.statements[i]); - } - aira_free(stmt->as.program.statements); - break; - case STMT_LET: - aira_free(stmt->as.let_stmt.name); - expr_free(stmt->as.let_stmt.init_expr); - break; - case STMT_ASSIGN: - aira_free(stmt->as.assign.name); - expr_free(stmt->as.assign.expr); - break; - case STMT_INDEX_ASSIGN: - expr_free(stmt->as.index_assign.target); - expr_free(stmt->as.index_assign.index); - expr_free(stmt->as.index_assign.expr); - break; - case STMT_MEMBER_ASSIGN: - expr_free(stmt->as.member_assign.target); - aira_free(stmt->as.member_assign.member); - expr_free(stmt->as.member_assign.expr); - break; - case STMT_SAY: - for (int i = 0; i < stmt->as.say_stmt.count; i++) { - expr_free(stmt->as.say_stmt.expressions[i]); - } - aira_free(stmt->as.say_stmt.expressions); - break; - case STMT_PRINT: - for (int i = 0; i < stmt->as.print_stmt.count; i++) { - expr_free(stmt->as.print_stmt.expressions[i]); - } - aira_free(stmt->as.print_stmt.expressions); - break; - case STMT_IF: - expr_free(stmt->as.if_stmt.condition); - stmt_free(stmt->as.if_stmt.then_branch); - stmt_free(stmt->as.if_stmt.else_branch); - break; - case STMT_WHILE: - expr_free(stmt->as.while_stmt.condition); - stmt_free(stmt->as.while_stmt.body); - break; - case STMT_FOR_IN: - aira_free(stmt->as.for_in_stmt.var_name); - expr_free(stmt->as.for_in_stmt.iterable); - stmt_free(stmt->as.for_in_stmt.body); - break; - case STMT_FN_DEF: - aira_free(stmt->as.fn_def.name); - for (int i = 0; i < stmt->as.fn_def.param_count; i++) { - aira_free(stmt->as.fn_def.params[i]); - } - aira_free(stmt->as.fn_def.params); - stmt_free(stmt->as.fn_def.body); - break; - case STMT_RETURN: - expr_free(stmt->as.return_stmt.expr); - break; - case STMT_BLOCK: - for (int i = 0; i < stmt->as.block.count; i++) { - stmt_free(stmt->as.block.statements[i]); - } - aira_free(stmt->as.block.statements); - break; - case STMT_EXPR: - expr_free(stmt->as.expr_stmt.expr); - break; - case STMT_IMPORT: - aira_free(stmt->as.import_stmt.module_name); - if (stmt->as.import_stmt.source) aira_free(stmt->as.import_stmt.source); - if (stmt->as.import_stmt.alias) aira_free(stmt->as.import_stmt.alias); - break; - default: - break; - } - aira_free(stmt); -} diff --git a/s1duo/src/common.c b/s1duo/src/common.c deleted file mode 100644 index 9d95f18..0000000 --- a/s1duo/src/common.c +++ /dev/null @@ -1,133 +0,0 @@ -#include "../include/common.h" - -void* aira_malloc(size_t size) { - if (size == 0) return NULL; - void* ptr = malloc(size); - if (!ptr) { - fprintf(stderr, COLOR_RED "[!] Critical Error: Out of memory allocating %zu bytes." COLOR_RESET "\n", size); - exit(EXIT_FAILURE); - } - return ptr; -} - -void* aira_calloc(size_t num, size_t size) { - if (num == 0 || size == 0) return NULL; - void* ptr = calloc(num, size); - if (!ptr) { - fprintf(stderr, COLOR_RED "[!] Critical Error: Out of memory in calloc (%zu * %zu)." COLOR_RESET "\n", num, size); - exit(EXIT_FAILURE); - } - return ptr; -} - -void* aira_realloc(void* ptr, size_t new_size) { - if (new_size == 0) { - free(ptr); - return NULL; - } - void* new_ptr = realloc(ptr, new_size); - if (!new_ptr) { - fprintf(stderr, COLOR_RED "[!] Critical Error: Out of memory reallocating to %zu bytes." COLOR_RESET "\n", new_size); - exit(EXIT_FAILURE); - } - return new_ptr; -} - -void aira_free(void* ptr) { - if (ptr) { - free(ptr); - } -} - -char* aira_strdup(const char* s) { - if (!s) return NULL; - size_t len = strlen(s); - if (len > AIRA_MAX_STRING_LEN) { - fprintf(stderr, COLOR_RED "[!] Error: String length %zu exceeds maximum permitted size (%d bytes)." COLOR_RESET "\n", len, AIRA_MAX_STRING_LEN); - exit(EXIT_FAILURE); - } - char* copy = (char*)aira_malloc(len + 1); - memcpy(copy, s, len + 1); - return copy; -} - -char* aira_strndup(const char* s, size_t n) { - if (!s) return NULL; - if (n > AIRA_MAX_STRING_LEN) { - n = AIRA_MAX_STRING_LEN; - } - char* copy = (char*)aira_malloc(n + 1); - memcpy(copy, s, n); - copy[n] = '\0'; - return copy; -} - -void aira_panic(const char* fmt, ...) { - fprintf(stderr, COLOR_RED "[!] Runtime Error: " COLOR_RESET); - va_list args; - va_start(args, fmt); - vfprintf(stderr, fmt, args); - va_end(args); - fprintf(stderr, "\n"); - exit(EXIT_FAILURE); -} - -void aira_error_at(const char* filename, int line, int col, const char* fmt, ...) { - fprintf(stderr, COLOR_RED "[!] Error" COLOR_RESET " at %s:%d:%d: ", filename ? filename : "", line, col); - va_list args; - va_start(args, fmt); - vfprintf(stderr, fmt, args); - va_end(args); - fprintf(stderr, "\n"); -} - -void sb_init(AiraStringBuilder* sb) { - sb->capacity = 64; - sb->length = 0; - sb->data = (char*)aira_malloc(sb->capacity); - sb->data[0] = '\0'; -} - -void sb_append_len(AiraStringBuilder* sb, const char* str, size_t len) { - if (!str || len == 0) return; - if (sb->length + len + 1 > AIRA_MAX_STRING_LEN) { - aira_panic("StringBuilder exceeded safe string threshold of %d bytes.", AIRA_MAX_STRING_LEN); - } - if (sb->length + len + 1 > sb->capacity) { - while (sb->capacity < sb->length + len + 1) { - sb->capacity *= 2; - } - sb->data = (char*)aira_realloc(sb->data, sb->capacity); - } - memcpy(sb->data + sb->length, str, len); - sb->length += len; - sb->data[sb->length] = '\0'; -} - -void sb_append(AiraStringBuilder* sb, const char* str) { - if (str) { - sb_append_len(sb, str, strlen(str)); - } -} - -void sb_append_char(AiraStringBuilder* sb, char c) { - char buf[1] = { c }; - sb_append_len(sb, buf, 1); -} - -char* sb_finish(AiraStringBuilder* sb) { - char* res = sb->data; - sb->data = NULL; - sb->length = 0; - sb->capacity = 0; - return res; -} - -void sb_free(AiraStringBuilder* sb) { - if (sb->data) { - aira_free(sb->data); - sb->data = NULL; - } - sb->length = 0; - sb->capacity = 0; -} diff --git a/s1duo/src/elf_emitter.c b/s1duo/src/elf_emitter.c deleted file mode 100644 index e1365e7..0000000 --- a/s1duo/src/elf_emitter.c +++ /dev/null @@ -1,334 +0,0 @@ -#include "../include/elf_emitter.h" -#include - -/* ELF64 Format Headers */ -typedef struct { - uint8_t e_ident[16]; - uint16_t e_type; - uint16_t e_machine; - uint32_t e_version; - uint64_t e_entry; - uint64_t e_phoff; - uint64_t e_shoff; - uint32_t e_flags; - uint16_t e_ehsize; - uint16_t e_phentsize; - uint16_t e_phnum; - uint16_t e_shentsize; - uint16_t e_shnum; - uint16_t e_shstrndx; -} Elf64_Ehdr; - -typedef struct { - uint32_t p_type; - uint32_t p_flags; - uint64_t p_offset; - uint64_t p_vaddr; - uint64_t p_paddr; - uint64_t p_filesz; - uint64_t p_memsz; - uint64_t p_align; -} Elf64_Phdr; - -/* Variable Symbol Table in CodeGen */ -typedef struct { - char* name; - int stack_offset; -} VarSymbol; - -typedef struct { - VarSymbol vars[128]; - int count; - int current_stack_offset; -} SymbolTable; - -void elf_emitter_init(ElfEmitter* emitter, TargetArch arch) { - emitter->arch = arch; - emitter->code_cap = 4096; - emitter->code_len = 0; - emitter->code_buf = (uint8_t*)aira_malloc(emitter->code_cap); - - emitter->data_cap = 4096; - emitter->data_len = 0; - emitter->data_buf = (uint8_t*)aira_malloc(emitter->data_cap); - - emitter->base_vaddr = 0x400000; -} - -void elf_emitter_free(ElfEmitter* emitter) { - if (emitter->code_buf) aira_free(emitter->code_buf); - if (emitter->data_buf) aira_free(emitter->data_buf); - emitter->code_buf = NULL; - emitter->data_buf = NULL; - emitter->code_len = 0; - emitter->data_len = 0; -} - -static void emit32(ElfEmitter* emitter, uint32_t inst) { - if (emitter->code_len + 4 > emitter->code_cap) { - emitter->code_cap *= 2; - emitter->code_buf = (uint8_t*)aira_realloc(emitter->code_buf, emitter->code_cap); - } - emitter->code_buf[emitter->code_len++] = (uint8_t)(inst & 0xFF); - emitter->code_buf[emitter->code_len++] = (uint8_t)((inst >> 8) & 0xFF); - emitter->code_buf[emitter->code_len++] = (uint8_t)((inst >> 16) & 0xFF); - emitter->code_buf[emitter->code_len++] = (uint8_t)((inst >> 24) & 0xFF); -} - -static size_t add_data_string(ElfEmitter* emitter, const char* str) { - size_t len = strlen(str); - if (emitter->data_len + len + 1 > emitter->data_cap) { - emitter->data_cap = (emitter->data_cap + len + 1) * 2; - emitter->data_buf = (uint8_t*)aira_realloc(emitter->data_buf, emitter->data_cap); - } - size_t offset = emitter->data_len; - memcpy(emitter->data_buf + offset, str, len); - emitter->data_buf[offset + len] = '\0'; - emitter->data_len += len + 1; - return offset; -} - -/* ============================================================================== - * ARM64 Machine Instruction Encodings - * ============================================================================== */ - -/* MOVZ: Move Wide with Zero (Load 16-bit immediate into register) */ -static void arm64_movz(ElfEmitter* emitter, int reg, uint16_t imm, int shift_hw) { - uint32_t inst = 0xd2800000 | ((uint32_t)shift_hw << 21) | ((uint32_t)imm << 5) | (uint32_t)reg; - emit32(emitter, inst); -} - -/* MOVK: Move Wide with Keep */ -static void arm64_movk(ElfEmitter* emitter, int reg, uint16_t imm, int shift_hw) { - uint32_t inst = 0xf2800000 | ((uint32_t)shift_hw << 21) | ((uint32_t)imm << 5) | (uint32_t)reg; - emit32(emitter, inst); -} - -/* Load any 64-bit integer into an ARM64 register */ -static void arm64_mov_imm(ElfEmitter* emitter, int reg, uint64_t val) { - uint16_t h0 = (uint16_t)(val & 0xFFFF); - uint16_t h1 = (uint16_t)((val >> 16) & 0xFFFF); - uint16_t h2 = (uint16_t)((val >> 32) & 0xFFFF); - uint16_t h3 = (uint16_t)((val >> 48) & 0xFFFF); - - arm64_movz(emitter, reg, h0, 0); - if (h1) arm64_movk(emitter, reg, h1, 1); - if (h2) arm64_movk(emitter, reg, h2, 2); - if (h3) arm64_movk(emitter, reg, h3, 3); -} - -/* MOV Reg: ORR Xd, XZR, Xm */ -static void arm64_mov_reg(ElfEmitter* emitter, int dst, int src) { - uint32_t inst = 0xaa0003e0 | ((uint32_t)src << 16) | (uint32_t)dst; - emit32(emitter, inst); -} - -/* ADD Xd, Xn, Xm */ -static void arm64_add(ElfEmitter* emitter, int dst, int src1, int src2) { - uint32_t inst = 0x8b000000 | ((uint32_t)src2 << 16) | ((uint32_t)src1 << 5) | (uint32_t)dst; - emit32(emitter, inst); -} - -/* SUB Xd, Xn, Xm */ -static void arm64_sub(ElfEmitter* emitter, int dst, int src1, int src2) { - uint32_t inst = 0xcb000000 | ((uint32_t)src2 << 16) | ((uint32_t)src1 << 5) | (uint32_t)dst; - emit32(emitter, inst); -} - -/* MUL Xd, Xn, Xm */ -static void arm64_mul(ElfEmitter* emitter, int dst, int src1, int src2) { - uint32_t inst = 0x9b007c00 | ((uint32_t)src2 << 16) | ((uint32_t)src1 << 5) | (uint32_t)dst; - emit32(emitter, inst); -} - -/* SDIV Xd, Xn, Xm (Signed 64-bit integer division) */ -static void arm64_sdiv(ElfEmitter* emitter, int dst, int src1, int src2) { - uint32_t inst = 0x9ac00c00 | ((uint32_t)src2 << 16) | ((uint32_t)src1 << 5) | (uint32_t)dst; - emit32(emitter, inst); -} - -/* STR Xt, [Xn, #offset] (64-bit unsigned offset, scaled by 8) */ -static void arm64_str_sp(ElfEmitter* emitter, int reg, int offset_bytes) { - int imm12 = offset_bytes / 8; - uint32_t inst = 0xf9000000 | ((uint32_t)(imm12 & 0xFFF) << 10) | (31 << 5) | (uint32_t)reg; - emit32(emitter, inst); -} - -/* LDR Xt, [Xn, #offset] (64-bit unsigned offset, scaled by 8) */ -static void arm64_ldr_sp(ElfEmitter* emitter, int reg, int offset_bytes) { - int imm12 = offset_bytes / 8; - uint32_t inst = 0xf9400000 | ((uint32_t)(imm12 & 0xFFF) << 10) | (31 << 5) | (uint32_t)reg; - emit32(emitter, inst); -} - -/* SUB SP, SP, #imm (Adjust stack pointer) */ -static void arm64_sub_sp_imm(ElfEmitter* emitter, int imm) { - uint32_t inst = 0xd10003ff | ((uint32_t)(imm & 0xFFF) << 10); - emit32(emitter, inst); -} - -/* ADD SP, SP, #imm (Restore stack pointer) */ -static void arm64_add_sp_imm(ElfEmitter* emitter, int imm) { - uint32_t inst = 0x910003ff | ((uint32_t)(imm & 0xFFF) << 10); - emit32(emitter, inst); -} - -/* SVC #0: Hardware Linux Syscall */ -static void arm64_svc(ElfEmitter* emitter) { - emit32(emitter, 0xd4000001); -} - -/* Syscall Helper: sys_write(stdout=1, buf, len) */ -static void emit_arm64_sys_write(ElfEmitter* emitter, uint64_t buf_vaddr, size_t len) { - arm64_mov_imm(emitter, 0, 1); /* X0 = 1 (stdout) */ - arm64_mov_imm(emitter, 1, buf_vaddr); /* X1 = buffer vaddr */ - arm64_mov_imm(emitter, 2, len); /* X2 = length */ - arm64_mov_imm(emitter, 8, 64); /* X8 = 64 (sys_write on ARM64 Linux) */ - arm64_svc(emitter); /* Execute kernel syscall */ -} - -/* Syscall Helper: sys_exit(0) */ -static void emit_arm64_sys_exit(ElfEmitter* emitter, int status) { - arm64_mov_imm(emitter, 0, status); /* X0 = status */ - arm64_mov_imm(emitter, 8, 93); /* X8 = 93 (sys_exit on ARM64 Linux) */ - arm64_svc(emitter); /* Execute kernel syscall */ -} - -/* ============================================================================== - * AST to Machine Code Compilation Logic - * ============================================================================== */ - -static void compile_expr_to_reg(ElfEmitter* emitter, ExprNode* expr, int target_reg, SymbolTable* syms) { - if (!expr) return; - - if (expr->type == EXPR_LITERAL) { - if (expr->as.literal.type == VAL_INT) { - arm64_mov_imm(emitter, target_reg, (uint64_t)expr->as.literal.as.integer); - } else if (expr->as.literal.type == VAL_BOOL) { - arm64_mov_imm(emitter, target_reg, expr->as.literal.as.boolean ? 1 : 0); - } - } else if (expr->type == EXPR_IDENTIFIER) { - for (int i = 0; i < syms->count; i++) { - if (strcmp(syms->vars[i].name, expr->as.identifier) == 0) { - arm64_ldr_sp(emitter, target_reg, syms->vars[i].stack_offset); - return; - } - } - } else if (expr->type == EXPR_BINARY) { - compile_expr_to_reg(emitter, expr->as.binary.left, target_reg, syms); - int temp_reg = (target_reg == 0) ? 1 : 0; - compile_expr_to_reg(emitter, expr->as.binary.right, temp_reg, syms); - - switch (expr->as.binary.op) { - case TOKEN_PLUS: arm64_add(emitter, target_reg, target_reg, temp_reg); break; - case TOKEN_MINUS: arm64_sub(emitter, target_reg, target_reg, temp_reg); break; - case TOKEN_STAR: arm64_mul(emitter, target_reg, target_reg, temp_reg); break; - case TOKEN_SLASH: arm64_sdiv(emitter, target_reg, target_reg, temp_reg); break; - default: break; - } - } -} - -static void compile_stmt(ElfEmitter* emitter, StmtNode* stmt, SymbolTable* syms) { - if (!stmt) return; - - if (stmt->type == STMT_LET) { - compile_expr_to_reg(emitter, stmt->as.let_stmt.init_expr, 0, syms); - syms->current_stack_offset += 8; - arm64_str_sp(emitter, 0, syms->current_stack_offset); - - syms->vars[syms->count].name = aira_strdup(stmt->as.let_stmt.name); - syms->vars[syms->count].stack_offset = syms->current_stack_offset; - syms->count++; - } else if (stmt->type == STMT_ASSIGN) { - compile_expr_to_reg(emitter, stmt->as.assign.expr, 0, syms); - for (int i = 0; i < syms->count; i++) { - if (strcmp(syms->vars[i].name, stmt->as.assign.name) == 0) { - arm64_str_sp(emitter, 0, syms->vars[i].stack_offset); - break; - } - } - } else if (stmt->type == STMT_SAY) { - for (int i = 0; i < stmt->as.say_stmt.count; i++) { - ExprNode* e = stmt->as.say_stmt.expressions[i]; - if (e->type == EXPR_LITERAL && e->as.literal.type == VAL_STRING) { - const char* str = e->as.literal.as.string; - size_t str_len = strlen(str); - size_t d_offset = add_data_string(emitter, str); - /* Virtual address calculation will be patched after code is finalized */ - /* Placeholder: save the instruction offset to patch later */ - /* For demonstration, we embed direct string writing */ - (void)str_len; (void)d_offset; - } - } - } -} - -bool elf_emitter_compile_ast(ElfEmitter* emitter, StmtNode* ast, const char* output_binary) { - if (!ast || ast->type != STMT_PROGRAM) return false; - - SymbolTable syms; - syms.count = 0; - syms.current_stack_offset = 0; - - /* Stack frame allocation */ - arm64_sub_sp_imm(emitter, 256); - - /* Compile program statements */ - for (int i = 0; i < ast->as.program.count; i++) { - compile_stmt(emitter, ast->as.program.statements[i], &syms); - } - - /* Stack frame teardown and exit(0) */ - arm64_add_sp_imm(emitter, 256); - emit_arm64_sys_exit(emitter, 0); - - /* Construct ELF Header */ - Elf64_Ehdr ehdr; - memset(&ehdr, 0, sizeof(ehdr)); - memcpy(ehdr.e_ident, "\x7f\x45\x4c\x46\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00", 16); - ehdr.e_type = 2; /* ET_EXEC */ - ehdr.e_machine = (emitter->arch == ARCH_ARM64) ? EM_AARCH64 : EM_X86_64; - ehdr.e_version = 1; - ehdr.e_entry = emitter->base_vaddr + sizeof(Elf64_Ehdr) + sizeof(Elf64_Phdr); - ehdr.e_phoff = sizeof(Elf64_Ehdr); - ehdr.e_ehsize = sizeof(Elf64_Ehdr); - ehdr.e_phentsize = sizeof(Elf64_Phdr); - ehdr.e_phnum = 1; - - size_t total_payload = emitter->code_len + emitter->data_len; - size_t total_file_size = sizeof(Elf64_Ehdr) + sizeof(Elf64_Phdr) + total_payload; - - Elf64_Phdr phdr; - memset(&phdr, 0, sizeof(phdr)); - phdr.p_type = 1; /* PT_LOAD */ - phdr.p_flags = 7; /* PF_R | PF_W | PF_X */ - phdr.p_offset = 0; - phdr.p_vaddr = emitter->base_vaddr; - phdr.p_paddr = emitter->base_vaddr; - phdr.p_filesz = total_file_size; - phdr.p_memsz = total_file_size; - phdr.p_align = 0x1000; - - FILE* out = fopen(output_binary, "wb"); - if (!out) { - return false; - } - - fwrite(&ehdr, 1, sizeof(ehdr), out); - fwrite(&phdr, 1, sizeof(phdr), out); - fwrite(emitter->code_buf, 1, emitter->code_len, out); - if (emitter->data_len > 0) { - fwrite(emitter->data_buf, 1, emitter->data_len, out); - } - fclose(out); - - chmod(output_binary, 0755); - - /* Cleanup symbol names */ - for (int i = 0; i < syms.count; i++) { - aira_free(syms.vars[i].name); - } - - return true; -} diff --git a/s1duo/src/env.c b/s1duo/src/env.c deleted file mode 100644 index 79e9c76..0000000 --- a/s1duo/src/env.c +++ /dev/null @@ -1,67 +0,0 @@ -#include "../include/env.h" - -Environment* env_new(Environment* parent) { - Environment* env = (Environment*)aira_malloc(sizeof(Environment)); - env->parent = parent; - env->count = 0; - env->capacity = 8; - env->names = (char**)aira_malloc(sizeof(char*) * env->capacity); - env->values = (AiraValue*)aira_malloc(sizeof(AiraValue) * env->capacity); - return env; -} - -void env_free(Environment* env) { - if (!env) return; - for (int i = 0; i < env->count; i++) { - aira_free(env->names[i]); - } - aira_free(env->names); - aira_free(env->values); - aira_free(env); -} - -void env_define(Environment* env, const char* name, AiraValue val) { - /* Check if already in current scope */ - for (int i = 0; i < env->count; i++) { - if (strcmp(env->names[i], name) == 0) { - env->values[i] = val; - return; - } - } - if (env->count >= env->capacity) { - env->capacity *= 2; - env->names = (char**)aira_realloc(env->names, sizeof(char*) * env->capacity); - env->values = (AiraValue*)aira_realloc(env->values, sizeof(AiraValue) * env->capacity); - } - env->names[env->count] = aira_strdup(name); - env->values[env->count] = val; - env->count++; -} - -bool env_get(Environment* env, const char* name, AiraValue* out_val) { - Environment* curr = env; - while (curr) { - for (int i = 0; i < curr->count; i++) { - if (strcmp(curr->names[i], name) == 0) { - if (out_val) *out_val = curr->values[i]; - return true; - } - } - curr = curr->parent; - } - return false; -} - -bool env_assign(Environment* env, const char* name, AiraValue val) { - Environment* curr = env; - while (curr) { - for (int i = 0; i < curr->count; i++) { - if (strcmp(curr->names[i], name) == 0) { - curr->values[i] = val; - return true; - } - } - curr = curr->parent; - } - return false; -} diff --git a/s1duo/src/evaluator.c b/s1duo/src/evaluator.c deleted file mode 100644 index 1b0434b..0000000 --- a/s1duo/src/evaluator.c +++ /dev/null @@ -1,462 +0,0 @@ -#include "../include/evaluator.h" -#include "../include/modules.h" - -void evaluator_init(Evaluator* eval) { - eval->global_env = env_new(NULL); - eval->call_depth = 0; - eval->had_runtime_error = false; - register_builtin_globals(eval->global_env); -} - -void evaluator_cleanup(Evaluator* eval) { - if (eval->global_env) { - env_free(eval->global_env); - eval->global_env = NULL; - } -} - -static EvalSignal signal_ok(void) { - EvalSignal s; - s.type = EXEC_OK; - s.value = val_null(); - return s; -} - -static EvalSignal signal_return(AiraValue v) { - EvalSignal s; - s.type = EXEC_RETURN; - s.value = v; - return s; -} - -static EvalSignal signal_break(void) { - EvalSignal s; - s.type = EXEC_BREAK; - s.value = val_null(); - return s; -} - -static EvalSignal signal_continue(void) { - EvalSignal s; - s.type = EXEC_CONTINUE; - s.value = val_null(); - return s; -} - -AiraValue eval_expression(Evaluator* eval, Environment* env, ExprNode* expr) { - if (!expr) return val_null(); - - switch (expr->type) { - case EXPR_LITERAL: - return expr->as.literal; - - case EXPR_IDENTIFIER: { - AiraValue val; - if (env_get(env, expr->as.identifier, &val)) { - return val; - } - aira_panic("Runtime Error: Undefined variable '%s' at line %d.", expr->as.identifier, expr->line); - return val_null(); - } - - case EXPR_UNARY: { - AiraValue right = eval_expression(eval, env, expr->as.unary.right); - if (expr->as.unary.op == TOKEN_MINUS) { - if (right.type == VAL_INT) return val_int(-right.as.integer); - if (right.type == VAL_FLOAT) return val_float(-right.as.floating); - aira_panic("Unary '-' requires numeric operand at line %d.", expr->line); - } - if (expr->as.unary.op == TOKEN_BANG || expr->as.unary.op == TOKEN_NOT) { - return val_bool(!val_is_truthy(right)); - } - return right; - } - - case EXPR_BINARY: { - /* Short-circuit logical operators */ - if (expr->as.binary.op == TOKEN_AND || expr->as.binary.op == TOKEN_AND_AND) { - AiraValue left = eval_expression(eval, env, expr->as.binary.left); - if (!val_is_truthy(left)) return left; - return eval_expression(eval, env, expr->as.binary.right); - } - if (expr->as.binary.op == TOKEN_OR || expr->as.binary.op == TOKEN_OR_OR) { - AiraValue left = eval_expression(eval, env, expr->as.binary.left); - if (val_is_truthy(left)) return left; - return eval_expression(eval, env, expr->as.binary.right); - } - - AiraValue left = eval_expression(eval, env, expr->as.binary.left); - AiraValue right = eval_expression(eval, env, expr->as.binary.right); - - switch (expr->as.binary.op) { - case TOKEN_PLUS: return val_add(left, right); - case TOKEN_MINUS: return val_sub(left, right); - case TOKEN_STAR: return val_mul(left, right); - case TOKEN_SLASH: return val_div(left, right); - case TOKEN_PERCENT: return val_mod(left, right); - case TOKEN_EQUAL_EQUAL: return val_bool(val_equals(left, right)); - case TOKEN_BANG_EQUAL: return val_bool(!val_equals(left, right)); - case TOKEN_LESS: return val_bool(val_compare(left, right) < 0); - case TOKEN_LESS_EQUAL: return val_bool(val_compare(left, right) <= 0); - case TOKEN_GREATER: return val_bool(val_compare(left, right) > 0); - case TOKEN_GREATER_EQUAL: return val_bool(val_compare(left, right) >= 0); - default: - aira_panic("Unsupported binary operator at line %d.", expr->line); - return val_null(); - } - } - - case EXPR_LIST: { - AiraValue list = val_list(); - for (int i = 0; i < expr->as.list.count; i++) { - AiraValue el = eval_expression(eval, env, expr->as.list.elements[i]); - list_append(list.as.list, el); - } - return list; - } - - case EXPR_DICT: { - AiraValue dict = val_dict(); - for (int i = 0; i < expr->as.dict.count; i++) { - AiraValue val = eval_expression(eval, env, expr->as.dict.values[i]); - dict_set(dict.as.dict, expr->as.dict.keys[i], val); - } - return dict; - } - - case EXPR_INDEX: { - AiraValue target = eval_expression(eval, env, expr->as.index_access.target); - AiraValue idx = eval_expression(eval, env, expr->as.index_access.index); - - if (target.type == VAL_LIST) { - int i = (idx.type == VAL_INT) ? (int)idx.as.integer : (int)idx.as.floating; - return list_get(target.as.list, i); - } - if (target.type == VAL_DICT) { - char* key = val_to_string(idx); - AiraValue v = dict_get(target.as.dict, key); - aira_free(key); - return v; - } - if (target.type == VAL_STRING) { - int i = (idx.type == VAL_INT) ? (int)idx.as.integer : (int)idx.as.floating; - int len = (int)strlen(target.as.string); - if (i < 0) i = len + i; - if (i < 0 || i >= len) aira_panic("String index out of bounds (%d, length %d).", i, len); - char ch[2] = { target.as.string[i], '\0' }; - return val_string(ch); - } - aira_panic("Index operator not supported on type at line %d.", expr->line); - return val_null(); - } - - case EXPR_MEMBER: { - AiraValue target = eval_expression(eval, env, expr->as.member_access.target); - const char* mem = expr->as.member_access.member; - - if (target.type == VAL_MODULE) { - AiraValue fn = dict_get(target.as.module->members, mem); - if (fn.type != VAL_NULL) return fn; - aira_panic("Module '%s' has no member '%s' at line %d.", target.as.module->name, mem, expr->line); - } - if (target.type == VAL_DICT) { - return dict_get(target.as.dict, mem); - } - if (target.type == VAL_LIST) { - if (strcmp(mem, "length") == 0) return val_int(target.as.list->count); - } - if (target.type == VAL_STRING) { - if (strcmp(mem, "length") == 0) return val_int(strlen(target.as.string)); - } - aira_panic("Member access '%s' not supported on target at line %d.", mem, expr->line); - return val_null(); - } - - case EXPR_CALL: { - /* Check if callee is a member method call like list.push(x) or str.upper() */ - if (expr->as.call.callee->type == EXPR_MEMBER) { - ExprNode* target_expr = expr->as.call.callee->as.member_access.target; - const char* method_name = expr->as.call.callee->as.member_access.member; - AiraValue target = eval_expression(eval, env, target_expr); - - if (target.type == VAL_LIST) { - if (strcmp(method_name, "push") == 0 && expr->as.call.arg_count > 0) { - AiraValue arg = eval_expression(eval, env, expr->as.call.args[0]); - list_append(target.as.list, arg); - return val_null(); - } - if (strcmp(method_name, "pop") == 0) { - return list_pop(target.as.list); - } - if (strcmp(method_name, "contains") == 0 && expr->as.call.arg_count > 0) { - AiraValue arg = eval_expression(eval, env, expr->as.call.args[0]); - for (int i = 0; i < target.as.list->count; i++) { - if (val_equals(target.as.list->elements[i], arg)) return val_bool(true); - } - return val_bool(false); - } - } - if (target.type == VAL_DICT) { - if (strcmp(method_name, "get") == 0 && expr->as.call.arg_count > 0) { - char* k = val_to_string(eval_expression(eval, env, expr->as.call.args[0])); - AiraValue res = dict_get(target.as.dict, k); - aira_free(k); - if (res.type == VAL_NULL && expr->as.call.arg_count > 1) { - return eval_expression(eval, env, expr->as.call.args[1]); - } - return res; - } - if (strcmp(method_name, "has") == 0 && expr->as.call.arg_count > 0) { - char* k = val_to_string(eval_expression(eval, env, expr->as.call.args[0])); - bool h = dict_has(target.as.dict, k); - aira_free(k); - return val_bool(h); - } - } - if (target.type == VAL_STRING) { - if (strcmp(method_name, "upper") == 0) { - char* s = aira_strdup(target.as.string); - for (size_t i = 0; s[i]; i++) s[i] = toupper((unsigned char)s[i]); - return val_string_take(s); - } - if (strcmp(method_name, "lower") == 0) { - char* s = aira_strdup(target.as.string); - for (size_t i = 0; s[i]; i++) s[i] = tolower((unsigned char)s[i]); - return val_string_take(s); - } - } - if (target.type == VAL_MODULE) { - AiraValue mod_fn = dict_get(target.as.module->members, method_name); - if (mod_fn.type == VAL_BUILTIN_FN) { - AiraValue args[16]; - int count = expr->as.call.arg_count; - if (count > 16) count = 16; - for (int i = 0; i < count; i++) { - args[i] = eval_expression(eval, env, expr->as.call.args[i]); - } - return mod_fn.as.builtin(count, args); - } - } - } - - AiraValue callee = eval_expression(eval, env, expr->as.call.callee); - - if (callee.type == VAL_BUILTIN_FN) { - AiraValue args[32]; - int count = expr->as.call.arg_count; - if (count > 32) count = 32; - for (int i = 0; i < count; i++) { - args[i] = eval_expression(eval, env, expr->as.call.args[i]); - } - return callee.as.builtin(count, args); - } - - if (callee.type == VAL_FN) { - AiraFunction* fn = callee.as.fn; - Environment* local_env = env_new(fn->closure ? fn->closure : eval->global_env); - - int param_count = fn->node->as.fn_def.param_count; - for (int i = 0; i < param_count; i++) { - AiraValue arg_val = (i < expr->as.call.arg_count) ? eval_expression(eval, env, expr->as.call.args[i]) : val_null(); - env_define(local_env, fn->node->as.fn_def.params[i], arg_val); - } - - eval->call_depth++; - EvalSignal sig = eval_statement(eval, local_env, fn->node->as.fn_def.body); - eval->call_depth--; - env_free(local_env); - - if (sig.type == EXEC_RETURN) { - return sig.value; - } - return val_null(); - } - - aira_panic("Attempted to call a non-function value at line %d.", expr->line); - return val_null(); - } - - default: - return val_null(); - } -} - -EvalSignal eval_statement(Evaluator* eval, Environment* env, StmtNode* stmt) { - if (!stmt) return signal_ok(); - - switch (stmt->type) { - case STMT_LET: { - AiraValue val = eval_expression(eval, env, stmt->as.let_stmt.init_expr); - env_define(env, stmt->as.let_stmt.name, val); - return signal_ok(); - } - - case STMT_ASSIGN: { - AiraValue rhs = eval_expression(eval, env, stmt->as.assign.expr); - const char* name = stmt->as.assign.name; - TokenType op = stmt->as.assign.op; - - if (op == TOKEN_ASSIGN) { - if (!env_assign(env, name, rhs)) { - aira_panic("Cannot assign to undeclared variable '%s' at line %d.", name, stmt->line); - } - } else { - AiraValue curr; - if (!env_get(env, name, &curr)) { - aira_panic("Variable '%s' not found for compound assignment at line %d.", name, stmt->line); - } - AiraValue new_val = val_null(); - if (op == TOKEN_PLUS_ASSIGN) new_val = val_add(curr, rhs); - else if (op == TOKEN_MINUS_ASSIGN) new_val = val_sub(curr, rhs); - else if (op == TOKEN_STAR_ASSIGN) new_val = val_mul(curr, rhs); - else if (op == TOKEN_SLASH_ASSIGN) new_val = val_div(curr, rhs); - else if (op == TOKEN_MOD_ASSIGN) new_val = val_mod(curr, rhs); - - env_assign(env, name, new_val); - } - return signal_ok(); - } - - case STMT_INDEX_ASSIGN: { - AiraValue target = eval_expression(eval, env, stmt->as.index_assign.target); - AiraValue idx = eval_expression(eval, env, stmt->as.index_assign.index); - AiraValue rhs = eval_expression(eval, env, stmt->as.index_assign.expr); - - if (target.type == VAL_LIST) { - int i = (idx.type == VAL_INT) ? (int)idx.as.integer : (int)idx.as.floating; - list_set(target.as.list, i, rhs); - } else if (target.type == VAL_DICT) { - char* k = val_to_string(idx); - dict_set(target.as.dict, k, rhs); - aira_free(k); - } else { - aira_panic("Index assignment not supported on type at line %d.", stmt->line); - } - return signal_ok(); - } - - case STMT_MEMBER_ASSIGN: { - AiraValue target = eval_expression(eval, env, stmt->as.member_assign.target); - AiraValue rhs = eval_expression(eval, env, stmt->as.member_assign.expr); - if (target.type == VAL_DICT) { - dict_set(target.as.dict, stmt->as.member_assign.member, rhs); - } else { - aira_panic("Member assignment only valid on dictionaries at line %d.", stmt->line); - } - return signal_ok(); - } - - case STMT_SAY: { - for (int i = 0; i < stmt->as.say_stmt.count; i++) { - if (i > 0) printf(" "); - AiraValue v = eval_expression(eval, env, stmt->as.say_stmt.expressions[i]); - val_print(v); - } - printf("\n"); - fflush(stdout); - return signal_ok(); - } - - case STMT_PRINT: { - for (int i = 0; i < stmt->as.print_stmt.count; i++) { - if (i > 0) printf(" "); - AiraValue v = eval_expression(eval, env, stmt->as.print_stmt.expressions[i]); - val_print(v); - } - fflush(stdout); - return signal_ok(); - } - - case STMT_IF: { - AiraValue cond = eval_expression(eval, env, stmt->as.if_stmt.condition); - if (val_is_truthy(cond)) { - return eval_statement(eval, env, stmt->as.if_stmt.then_branch); - } else if (stmt->as.if_stmt.else_branch) { - return eval_statement(eval, env, stmt->as.if_stmt.else_branch); - } - return signal_ok(); - } - - case STMT_WHILE: { - while (val_is_truthy(eval_expression(eval, env, stmt->as.while_stmt.condition))) { - EvalSignal sig = eval_statement(eval, env, stmt->as.while_stmt.body); - if (sig.type == EXEC_BREAK) break; - if (sig.type == EXEC_CONTINUE) continue; - if (sig.type == EXEC_RETURN) return sig; - } - return signal_ok(); - } - - case STMT_FOR_IN: { - AiraValue iter = eval_expression(eval, env, stmt->as.for_in_stmt.iterable); - if (iter.type == VAL_LIST) { - for (int i = 0; i < iter.as.list->count; i++) { - env_define(env, stmt->as.for_in_stmt.var_name, iter.as.list->elements[i]); - EvalSignal sig = eval_statement(eval, env, stmt->as.for_in_stmt.body); - if (sig.type == EXEC_BREAK) break; - if (sig.type == EXEC_CONTINUE) continue; - if (sig.type == EXEC_RETURN) return sig; - } - } else { - aira_panic("'for..in' loop requires an iterable list at line %d.", stmt->line); - } - return signal_ok(); - } - - case STMT_FN_DEF: { - AiraValue fn = val_function(stmt->as.fn_def.name, stmt, env); - env_define(env, stmt->as.fn_def.name, fn); - return signal_ok(); - } - - case STMT_RETURN: { - AiraValue ret = stmt->as.return_stmt.expr ? eval_expression(eval, env, stmt->as.return_stmt.expr) : val_null(); - return signal_return(ret); - } - - case STMT_BREAK: - return signal_break(); - - case STMT_CONTINUE: - return signal_continue(); - - case STMT_BLOCK: { - Environment* block_env = env_new(env); - for (int i = 0; i < stmt->as.block.count; i++) { - EvalSignal sig = eval_statement(eval, block_env, stmt->as.block.statements[i]); - if (sig.type != EXEC_OK) { - env_free(block_env); - return sig; - } - } - env_free(block_env); - return signal_ok(); - } - - case STMT_EXPR: - eval_expression(eval, env, stmt->as.expr_stmt.expr); - return signal_ok(); - - case STMT_IMPORT: { - AiraValue mod = load_builtin_module(stmt->as.import_stmt.module_name); - if (mod.type != VAL_NULL) { - const char* alias = stmt->as.import_stmt.alias ? stmt->as.import_stmt.alias : stmt->as.import_stmt.module_name; - env_define(env, alias, mod); - } else { - aira_panic("Module '%s' could not be loaded at line %d.", stmt->as.import_stmt.module_name, stmt->line); - } - return signal_ok(); - } - - default: - return signal_ok(); - } -} - -void eval_program(Evaluator* eval, StmtNode* program) { - if (!program || program->type != STMT_PROGRAM) return; - for (int i = 0; i < program->as.program.count; i++) { - EvalSignal sig = eval_statement(eval, eval->global_env, program->as.program.statements[i]); - if (sig.type == EXEC_RETURN) break; - } -} diff --git a/s1duo/src/lexer.c b/s1duo/src/lexer.c deleted file mode 100644 index 40182b1..0000000 --- a/s1duo/src/lexer.c +++ /dev/null @@ -1,361 +0,0 @@ -#include "../include/lexer.h" - -const char* token_type_name(TokenType type) { - switch (type) { - case TOKEN_EOF: return "EOF"; - case TOKEN_ERROR: return "ERROR"; - case TOKEN_NUMBER: return "NUMBER"; - case TOKEN_STRING: return "STRING"; - case TOKEN_IDENTIFIER: return "IDENTIFIER"; - case TOKEN_LET: return "let"; - case TOKEN_SAY: return "say"; - case TOKEN_PRINT: return "print"; - case TOKEN_IF: return "if"; - case TOKEN_ELSE: return "else"; - case TOKEN_WHILE: return "while"; - case TOKEN_FOR: return "for"; - case TOKEN_IN: return "in"; - case TOKEN_FN: return "fn"; - case TOKEN_RETURN: return "return"; - case TOKEN_IMPORT: return "import"; - case TOKEN_FROM: return "from"; - case TOKEN_TRUE: return "true"; - case TOKEN_FALSE: return "false"; - case TOKEN_NULL: return "null"; - case TOKEN_AND: return "and"; - case TOKEN_OR: return "or"; - case TOKEN_NOT: return "not"; - case TOKEN_TRY: return "try"; - case TOKEN_CATCH: return "catch"; - case TOKEN_THROW: return "throw"; - case TOKEN_CLASS: return "class"; - case TOKEN_NEW: return "new"; - case TOKEN_THIS: return "this"; - case TOKEN_BREAK: return "break"; - case TOKEN_CONTINUE: return "continue"; - case TOKEN_PLUS: return "+"; - case TOKEN_MINUS: return "-"; - case TOKEN_STAR: return "*"; - case TOKEN_SLASH: return "/"; - case TOKEN_PERCENT: return "%"; - case TOKEN_ASSIGN: return "="; - case TOKEN_PLUS_ASSIGN: return "+="; - case TOKEN_MINUS_ASSIGN: return "-="; - case TOKEN_STAR_ASSIGN: return "*="; - case TOKEN_SLASH_ASSIGN: return "/="; - case TOKEN_MOD_ASSIGN: return "%="; - case TOKEN_EQUAL_EQUAL: return "=="; - case TOKEN_BANG_EQUAL: return "!="; - case TOKEN_LESS: return "<"; - case TOKEN_LESS_EQUAL: return "<="; - case TOKEN_GREATER: return ">"; - case TOKEN_GREATER_EQUAL: return ">="; - case TOKEN_BANG: return "!"; - case TOKEN_AND_AND: return "&&"; - case TOKEN_OR_OR: return "||"; - case TOKEN_LPAREN: return "("; - case TOKEN_RPAREN: return ")"; - case TOKEN_LBRACE: return "{"; - case TOKEN_RBRACE: return "}"; - case TOKEN_LBRACKET: return "["; - case TOKEN_RBRACKET: return "]"; - case TOKEN_COMMA: return ","; - case TOKEN_DOT: return "."; - case TOKEN_COLON: return ":"; - case TOKEN_SEMICOLON: return ";"; - case TOKEN_AT: return "@"; - default: return "UNKNOWN"; - } -} - -void token_free(Token* token) { - if (token && token->text) { - aira_free(token->text); - token->text = NULL; - } -} - -void lexer_init(Lexer* lexer, const char* source, const char* filename) { - lexer->source = source; - lexer->filename = filename; - lexer->length = source ? strlen(source) : 0; - lexer->current = 0; - lexer->line = 1; - lexer->col = 1; -} - -static bool is_at_end(Lexer* lexer) { - return lexer->current >= lexer->length; -} - -static char peek(Lexer* lexer) { - if (is_at_end(lexer)) return '\0'; - return lexer->source[lexer->current]; -} - -static char peek_next(Lexer* lexer) { - if (lexer->current + 1 >= lexer->length) return '\0'; - return lexer->source[lexer->current + 1]; -} - -static char advance(Lexer* lexer) { - if (is_at_end(lexer)) return '\0'; - char c = lexer->source[lexer->current++]; - if (c == '\n') { - lexer->line++; - lexer->col = 1; - } else { - lexer->col++; - } - return c; -} - -static bool match(Lexer* lexer, char expected) { - if (is_at_end(lexer)) return false; - if (lexer->source[lexer->current] != expected) return false; - advance(lexer); - return true; -} - -static Token make_token(Lexer* lexer, TokenType type, const char* text, int line, int col) { - Token token; - token.type = type; - token.text = text ? aira_strdup(text) : NULL; - token.line = line; - token.col = col; - token.num_val = 0.0; - return token; -} - -static Token make_error_token(Lexer* lexer, const char* message, int line, int col) { - Token token; - token.type = TOKEN_ERROR; - token.text = aira_strdup(message); - token.line = line; - token.col = col; - token.num_val = 0.0; - return token; -} - -static void skip_whitespace_and_comments(Lexer* lexer) { - while (!is_at_end(lexer)) { - char c = peek(lexer); - if (c == ' ' || c == '\r' || c == '\t' || c == '\n') { - advance(lexer); - } else if (c == '#') { - /* Single line python style comment */ - while (!is_at_end(lexer) && peek(lexer) != '\n') { - advance(lexer); - } - } else if (c == '/' && peek_next(lexer) == '/') { - /* Single line C style comment */ - advance(lexer); - advance(lexer); - while (!is_at_end(lexer) && peek(lexer) != '\n') { - advance(lexer); - } - } else if (c == '/' && peek_next(lexer) == '*') { - /* Multi-line comment */ - advance(lexer); - advance(lexer); - while (!is_at_end(lexer)) { - if (peek(lexer) == '*' && peek_next(lexer) == '/') { - advance(lexer); - advance(lexer); - break; - } - advance(lexer); - } - } else { - break; - } - } -} - -static TokenType check_keyword(const char* text) { - if (strcmp(text, "let") == 0) return TOKEN_LET; - if (strcmp(text, "say") == 0) return TOKEN_SAY; - if (strcmp(text, "print") == 0) return TOKEN_PRINT; - if (strcmp(text, "if") == 0) return TOKEN_IF; - if (strcmp(text, "else") == 0) return TOKEN_ELSE; - if (strcmp(text, "while") == 0) return TOKEN_WHILE; - if (strcmp(text, "for") == 0) return TOKEN_FOR; - if (strcmp(text, "in") == 0) return TOKEN_IN; - if (strcmp(text, "fn") == 0) return TOKEN_FN; - if (strcmp(text, "return") == 0) return TOKEN_RETURN; - if (strcmp(text, "import") == 0) return TOKEN_IMPORT; - if (strcmp(text, "from") == 0) return TOKEN_FROM; - if (strcmp(text, "true") == 0) return TOKEN_TRUE; - if (strcmp(text, "false") == 0) return TOKEN_FALSE; - if (strcmp(text, "null") == 0) return TOKEN_NULL; - if (strcmp(text, "and") == 0) return TOKEN_AND; - if (strcmp(text, "or") == 0) return TOKEN_OR; - if (strcmp(text, "not") == 0) return TOKEN_NOT; - if (strcmp(text, "try") == 0) return TOKEN_TRY; - if (strcmp(text, "catch") == 0) return TOKEN_CATCH; - if (strcmp(text, "throw") == 0) return TOKEN_THROW; - if (strcmp(text, "class") == 0) return TOKEN_CLASS; - if (strcmp(text, "new") == 0) return TOKEN_NEW; - if (strcmp(text, "this") == 0) return TOKEN_THIS; - if (strcmp(text, "break") == 0) return TOKEN_BREAK; - if (strcmp(text, "continue") == 0) return TOKEN_CONTINUE; - return TOKEN_IDENTIFIER; -} - -static Token scan_identifier(Lexer* lexer, int start_line, int start_col) { - size_t start = lexer->current - 1; - while (!is_at_end(lexer)) { - char c = peek(lexer); - if (isalnum((unsigned char)c) || c == '_') { - advance(lexer); - } else { - break; - } - } - size_t len = lexer->current - start; - char* text = aira_strndup(lexer->source + start, len); - TokenType type = check_keyword(text); - Token tok = make_token(lexer, type, text, start_line, start_col); - aira_free(text); - return tok; -} - -static Token scan_number(Lexer* lexer, int start_line, int start_col) { - size_t start = lexer->current - 1; - bool has_dot = false; - while (!is_at_end(lexer)) { - char c = peek(lexer); - if (isdigit((unsigned char)c)) { - advance(lexer); - } else if (c == '.' && isdigit((unsigned char)peek_next(lexer)) && !has_dot) { - has_dot = true; - advance(lexer); - } else { - break; - } - } - size_t len = lexer->current - start; - char* text = aira_strndup(lexer->source + start, len); - Token tok = make_token(lexer, TOKEN_NUMBER, text, start_line, start_col); - tok.num_val = strtod(text, NULL); - aira_free(text); - return tok; -} - -static Token scan_string(Lexer* lexer, char quote, int start_line, int start_col) { - AiraStringBuilder sb; - sb_init(&sb); - - while (!is_at_end(lexer) && peek(lexer) != quote) { - char c = advance(lexer); - if (c == '\\') { - if (is_at_end(lexer)) break; - char esc = advance(lexer); - switch (esc) { - case 'n': sb_append_char(&sb, '\n'); break; - case 't': sb_append_char(&sb, '\t'); break; - case 'r': sb_append_char(&sb, '\r'); break; - case '\\': sb_append_char(&sb, '\\'); break; - case '\'': sb_append_char(&sb, '\''); break; - case '"': sb_append_char(&sb, '"'); break; - default: sb_append_char(&sb, esc); break; - } - } else { - sb_append_char(&sb, c); - } - } - - if (is_at_end(lexer)) { - sb_free(&sb); - return make_error_token(lexer, "Unterminated string literal.", start_line, start_col); - } - - advance(lexer); /* Consume closing quote */ - char* content = sb_finish(&sb); - Token tok = make_token(lexer, TOKEN_STRING, content, start_line, start_col); - aira_free(content); - return tok; -} - -Token lexer_next_token(Lexer* lexer) { - skip_whitespace_and_comments(lexer); - - int start_line = lexer->line; - int start_col = lexer->col; - - if (is_at_end(lexer)) { - return make_token(lexer, TOKEN_EOF, NULL, start_line, start_col); - } - - char c = advance(lexer); - - if (isalpha((unsigned char)c) || c == '_') { - return scan_identifier(lexer, start_line, start_col); - } - - if (isdigit((unsigned char)c)) { - return scan_number(lexer, start_line, start_col); - } - - if (c == '"' || c == '\'') { - return scan_string(lexer, c, start_line, start_col); - } - - switch (c) { - case '(': return make_token(lexer, TOKEN_LPAREN, "(", start_line, start_col); - case ')': return make_token(lexer, TOKEN_RPAREN, ")", start_line, start_col); - case '{': return make_token(lexer, TOKEN_LBRACE, "{", start_line, start_col); - case '}': return make_token(lexer, TOKEN_RBRACE, "}", start_line, start_col); - case '[': return make_token(lexer, TOKEN_LBRACKET, "[", start_line, start_col); - case ']': return make_token(lexer, TOKEN_RBRACKET, "]", start_line, start_col); - case ',': return make_token(lexer, TOKEN_COMMA, ",", start_line, start_col); - case '.': return make_token(lexer, TOKEN_DOT, ".", start_line, start_col); - case ':': return make_token(lexer, TOKEN_COLON, ":", start_line, start_col); - case ';': return make_token(lexer, TOKEN_SEMICOLON, ";", start_line, start_col); - case '@': return make_token(lexer, TOKEN_AT, "@", start_line, start_col); - - case '+': - if (match(lexer, '=')) return make_token(lexer, TOKEN_PLUS_ASSIGN, "+=", start_line, start_col); - return make_token(lexer, TOKEN_PLUS, "+", start_line, start_col); - case '-': - if (match(lexer, '=')) return make_token(lexer, TOKEN_MINUS_ASSIGN, "-=", start_line, start_col); - return make_token(lexer, TOKEN_MINUS, "-", start_line, start_col); - case '*': - if (match(lexer, '=')) return make_token(lexer, TOKEN_STAR_ASSIGN, "*=", start_line, start_col); - return make_token(lexer, TOKEN_STAR, "*", start_line, start_col); - case '/': - if (match(lexer, '=')) return make_token(lexer, TOKEN_SLASH_ASSIGN, "/=", start_line, start_col); - return make_token(lexer, TOKEN_SLASH, "/", start_line, start_col); - case '%': - if (match(lexer, '=')) return make_token(lexer, TOKEN_MOD_ASSIGN, "%=", start_line, start_col); - return make_token(lexer, TOKEN_PERCENT, "%", start_line, start_col); - - case '=': - if (match(lexer, '=')) return make_token(lexer, TOKEN_EQUAL_EQUAL, "==", start_line, start_col); - return make_token(lexer, TOKEN_ASSIGN, "=", start_line, start_col); - - case '!': - if (match(lexer, '=')) return make_token(lexer, TOKEN_BANG_EQUAL, "!=", start_line, start_col); - return make_token(lexer, TOKEN_BANG, "!", start_line, start_col); - - case '<': - if (match(lexer, '=')) return make_token(lexer, TOKEN_LESS_EQUAL, "<=", start_line, start_col); - return make_token(lexer, TOKEN_LESS, "<", start_line, start_col); - - case '>': - if (match(lexer, '=')) return make_token(lexer, TOKEN_GREATER_EQUAL, ">=", start_line, start_col); - return make_token(lexer, TOKEN_GREATER, ">", start_line, start_col); - - case '&': - if (match(lexer, '&')) return make_token(lexer, TOKEN_AND_AND, "&&", start_line, start_col); - break; - - case '|': - if (match(lexer, '|')) return make_token(lexer, TOKEN_OR_OR, "||", start_line, start_col); - break; - } - - char err_buf[64]; - snprintf(err_buf, sizeof(err_buf), "Unexpected character '%c' (0x%02x)", c, (unsigned char)c); - return make_error_token(lexer, err_buf, start_line, start_col); -} diff --git a/s1duo/src/main.c b/s1duo/src/main.c deleted file mode 100644 index b735b09..0000000 --- a/s1duo/src/main.c +++ /dev/null @@ -1,174 +0,0 @@ -#include "../include/common.h" -#include "../include/lexer.h" -#include "../include/parser.h" -#include "../include/evaluator.h" -#include "../include/elf_emitter.h" - -static void print_banner(void) { - printf(COLOR_CYAN -" ___ _ __ _____ __ ____ \n" -" / | (_)________ _/ / ____ _____ ____ _ / ___// / / __ \\__ ______ \n" -" / /| |/ / ___/ __ `/ / / __ `/ __ \\/ __ `// __// / / / / / / / / __ \\ \n" -" / ___ / / / / /_/ / /___/ /_/ / / / / /_/ /___/ / /__/ /_/ / /_/ / /_/ / \n" -" /_/ |/_/_/ \\__,_/_____/\\__,_/_/ /_/\\__, //____/____/_____/\\__,_/\\____/ \n" -" /____/ \n" -COLOR_RESET); - printf(COLOR_DIM "----------------------------------------------------------------------\n" COLOR_RESET); - printf(" " COLOR_GREEN "[+]" COLOR_RESET " " COLOR_BOLD "Engine:" COLOR_RESET " %s v%s\n", AIRA_CODENAME, AIRA_VERSION); - printf(" " COLOR_BLUE "[*]" COLOR_RESET " " COLOR_BOLD "Architect:" COLOR_RESET " %s\n", AIRA_ARCHITECT); - printf(" " COLOR_MAGENTA "[⚑]" COLOR_RESET " " COLOR_BOLD "Runtime:" COLOR_RESET " Pure C Native Binary Execution (Zero Python Overhead)\n"); - printf(COLOR_DIM "----------------------------------------------------------------------\n" COLOR_RESET); -} - -static char* read_file_source(const char* filepath) { - FILE* f = fopen(filepath, "rb"); - if (!f) { - fprintf(stderr, COLOR_RED "[!] Error: Could not open source file '%s'.\n" COLOR_RESET, filepath); - exit(EXIT_FAILURE); - } - fseek(f, 0, SEEK_END); - long length = ftell(f); - fseek(f, 0, SEEK_SET); - - if (length < 0 || length > AIRA_MAX_STRING_LEN) { - fclose(f); - fprintf(stderr, COLOR_RED "[!] Error: Source file exceeds maximum allowed threshold of %d bytes.\n" COLOR_RESET, AIRA_MAX_STRING_LEN); - exit(EXIT_FAILURE); - } - - char* buffer = (char*)aira_malloc(length + 1); - size_t read_bytes = fread(buffer, 1, length, f); - buffer[read_bytes] = '\0'; - fclose(f); - return buffer; -} - -static void run_source(const char* source, const char* filename, Evaluator* eval) { - Parser parser; - parser_init(&parser, source, filename); - - StmtNode* program = parser_parse(&parser); - if (!parser.had_error && program) { - eval_program(eval, program); - } - - stmt_free(program); -} - -static void run_file(const char* filepath) { - char* source = read_file_source(filepath); - Evaluator eval; - evaluator_init(&eval); - - run_source(source, filepath, &eval); - - evaluator_cleanup(&eval); - aira_free(source); -} - -static void run_repl(void) { - print_banner(); - printf(COLOR_CYAN "Type your AiraLang statements or 'exit'/'quit' to exit.\n\n" COLOR_RESET); - - Evaluator eval; - evaluator_init(&eval); - - char line_buf[4096]; - for (;;) { - printf(COLOR_GREEN "airalang> " COLOR_RESET); - fflush(stdout); - - if (!fgets(line_buf, sizeof(line_buf), stdin)) { - printf("\n"); - break; - } - - size_t len = strlen(line_buf); - if (len > 0 && line_buf[len - 1] == '\n') line_buf[--len] = '\0'; - if (len > 0 && line_buf[len - 1] == '\r') line_buf[--len] = '\0'; - - if (strcmp(line_buf, "exit") == 0 || strcmp(line_buf, "quit") == 0) { - printf(COLOR_YELLOW "Goodbye Boss! Sovereign AiraLang S1 Duo stopping.\n" COLOR_RESET); - break; - } - - if (len == 0) continue; - - run_source(line_buf, "", &eval); - } - - evaluator_cleanup(&eval); -} - -int main(int argc, char** argv) { - if (argc < 2) { - run_repl(); - return 0; - } - - if (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0) { - print_banner(); - return 0; - } - - if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) { - print_banner(); - printf("Usage:\n"); - printf(" airalang Execute AiraLang script with high-speed native engine\n"); - printf(" airalang -b -o Compile directly to raw standalone ELF machine binary (0%% C, 0%% Python)\n"); - printf(" airalang -c \"\" Execute inline AiraLang code string\n"); - printf(" airalang Start AiraLang interactive REPL shell\n"); - printf(" airalang -v, --version Show engine version\n"); - return 0; - } - - if (strcmp(argv[1], "--emit-elf") == 0 || strcmp(argv[1], "-b") == 0) { - if (argc < 3) { - fprintf(stderr, COLOR_RED "[!] Error: -b requires an input .aira file.\n" COLOR_RESET); - return 1; - } - const char* input_file = argv[2]; - const char* output_file = "a.out"; - for (int i = 3; i < argc; i++) { - if (strcmp(argv[i], "-o") == 0 && i + 1 < argc) { - output_file = argv[i + 1]; - break; - } - } - char* source = read_file_source(input_file); - Parser parser; - parser_init(&parser, source, input_file); - StmtNode* ast = parser_parse(&parser); - - if (!parser.had_error && ast) { - ElfEmitter emitter; - elf_emitter_init(&emitter, ARCH_ARM64); - if (elf_emitter_compile_ast(&emitter, ast, output_file)) { - printf(COLOR_GREEN "[βœ“] Standalone Raw Machine-Code ELF Binary created:" COLOR_RESET " %s\n", output_file); - printf(COLOR_CYAN "[*] Zero Dependencies (0%% C, 0%% Python, Static Bare-Metal ELF)\n" COLOR_RESET); - } else { - fprintf(stderr, COLOR_RED "[!] Failed to emit ELF binary.\n" COLOR_RESET); - } - elf_emitter_free(&emitter); - } - stmt_free(ast); - aira_free(source); - return 0; - } - - if (strcmp(argv[1], "-c") == 0) { - if (argc < 3) { - fprintf(stderr, COLOR_RED "[!] Error: -c requires a code string argument.\n" COLOR_RESET); - return 1; - } - Evaluator eval; - evaluator_init(&eval); - run_source(argv[2], "", &eval); - evaluator_cleanup(&eval); - return 0; - } - - /* Direct execution: airalang3 script.aira */ - run_file(argv[1]); - return 0; -} diff --git a/s1duo/src/modules.c b/s1duo/src/modules.c deleted file mode 100644 index ce99b57..0000000 --- a/s1duo/src/modules.c +++ /dev/null @@ -1,621 +0,0 @@ -#include "../include/modules.h" -#include -#include -#include -#include - -/* ============================================================================== - * Sovereign Pure-C SHA256 Implementation (Zero-Dependency Security Engine) - * ============================================================================== */ - -typedef struct { - uint32_t state[8]; - uint64_t count; - uint8_t buffer[64]; -} SHA256_CTX; - -#define ROTR(x, n) (((x) >> (n)) | ((x) << (32 - (n)))) -#define CH(x, y, z) (((x) & (y)) ^ (~(x) & (z))) -#define MAJ(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) -#define EP0(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22)) -#define EP1(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25)) -#define SIG0(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ ((x) >> 3)) -#define SIG1(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ ((x) >> 10)) - -static const uint32_t K[64] = { - 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, - 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, - 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, - 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, - 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, - 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, - 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, - 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2 -}; - -static void sha256_transform(SHA256_CTX* ctx, const uint8_t data[64]) { - uint32_t a, b, c, d, e, f, g, h, i, j, t1, t2, m[64]; - for (i = 0, j = 0; i < 16; ++i, j += 4) - m[i] = ((uint32_t)data[j] << 24) | ((uint32_t)data[j + 1] << 16) | ((uint32_t)data[j + 2] << 8) | ((uint32_t)data[j + 3]); - for (; i < 64; ++i) - m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16]; - a = ctx->state[0]; b = ctx->state[1]; c = ctx->state[2]; d = ctx->state[3]; - e = ctx->state[4]; f = ctx->state[5]; g = ctx->state[6]; h = ctx->state[7]; - for (i = 0; i < 64; ++i) { - t1 = h + EP1(e) + CH(e, f, g) + K[i] + m[i]; - t2 = EP0(a) + MAJ(a, b, c); - h = g; g = f; f = e; e = d + t1; - d = c; c = b; b = a; a = t1 + t2; - } - ctx->state[0] += a; ctx->state[1] += b; ctx->state[2] += c; ctx->state[3] += d; - ctx->state[4] += e; ctx->state[5] += f; ctx->state[6] += g; ctx->state[7] += h; -} - -static void sha256_init(SHA256_CTX* ctx) { - ctx->count = 0; - ctx->state[0] = 0x6a09e667; ctx->state[1] = 0xbb67ae85; ctx->state[2] = 0x3c6ef372; ctx->state[3] = 0xa54ff53a; - ctx->state[4] = 0x510e527f; ctx->state[5] = 0x9b05688c; ctx->state[6] = 0x1f83d9ab; ctx->state[7] = 0x5be0cd19; -} - -static void sha256_update(SHA256_CTX* ctx, const uint8_t* data, size_t len) { - size_t i, index, partlen; - index = (size_t)((ctx->count >> 3) & 0x3f); - partlen = 64 - index; - ctx->count += (uint64_t)len << 3; - if (len >= partlen) { - memcpy(&ctx->buffer[index], data, partlen); - sha256_transform(ctx, ctx->buffer); - for (i = partlen; i + 63 < len; i += 64) - sha256_transform(ctx, &data[i]); - index = 0; - } else { - i = 0; - } - memcpy(&ctx->buffer[index], &data[i], len - i); -} - -static void sha256_final(SHA256_CTX* ctx, uint8_t digest[32]) { - uint8_t finalcount[8]; - for (int i = 0; i < 8; i++) - finalcount[i] = (uint8_t)((ctx->count >> ((7 - i) * 8)) & 0xff); - uint8_t c = 0x80; - sha256_update(ctx, &c, 1); - while ((ctx->count >> 3) & 0x3f) { - c = 0x00; - sha256_update(ctx, &c, 1); - } - sha256_update(ctx, finalcount, 8); - for (int i = 0; i < 8; i++) { - digest[i * 4] = (uint8_t)((ctx->state[i] >> 24) & 0xff); - digest[i * 4 + 1] = (uint8_t)((ctx->state[i] >> 16) & 0xff); - digest[i * 4 + 2] = (uint8_t)((ctx->state[i] >> 8) & 0xff); - digest[i * 4 + 3] = (uint8_t)(ctx->state[i] & 0xff); - } -} - -void aira_sha256(const uint8_t* data, size_t len, char output[65]) { - SHA256_CTX ctx; - uint8_t digest[32]; - sha256_init(&ctx); - sha256_update(&ctx, data, len); - sha256_final(&ctx, digest); - for (int i = 0; i < 32; i++) { - sprintf(output + (i * 2), "%02x", digest[i]); - } - output[64] = '\0'; -} - -/* ============================================================================== - * Global Builtin Functions - * ============================================================================== */ - -static AiraValue builtin_len(int arg_count, AiraValue* args) { - if (arg_count < 1) return val_int(0); - AiraValue v = args[0]; - if (v.type == VAL_STRING) return val_int((int64_t)strlen(v.as.string)); - if (v.type == VAL_LIST) return val_int((int64_t)v.as.list->count); - if (v.type == VAL_DICT) return val_int((int64_t)v.as.dict->count); - return val_int(0); -} - -static AiraValue builtin_range(int arg_count, AiraValue* args) { - int64_t start = 0; - int64_t end = 0; - int64_t step = 1; - - if (arg_count == 1) { - end = args[0].type == VAL_INT ? args[0].as.integer : (int64_t)args[0].as.floating; - } else if (arg_count >= 2) { - start = args[0].type == VAL_INT ? args[0].as.integer : (int64_t)args[0].as.floating; - end = args[1].type == VAL_INT ? args[1].as.integer : (int64_t)args[1].as.floating; - if (arg_count >= 3) { - step = args[2].type == VAL_INT ? args[2].as.integer : (int64_t)args[2].as.floating; - if (step == 0) step = 1; - } - } - - AiraValue list = val_list(); - if (step > 0) { - for (int64_t i = start; i < end; i += step) { - list_append(list.as.list, val_int(i)); - } - } else { - for (int64_t i = start; i > end; i += step) { - list_append(list.as.list, val_int(i)); - } - } - return list; -} - -static AiraValue builtin_input(int arg_count, AiraValue* args) { - if (arg_count > 0) { - val_print(args[0]); - fflush(stdout); - } - char buf[1024]; - if (fgets(buf, sizeof(buf), stdin)) { - size_t len = strlen(buf); - if (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r')) { - buf[len - 1] = '\0'; - } - return val_string(buf); - } - return val_string(""); -} - -static AiraValue builtin_type(int arg_count, AiraValue* args) { - if (arg_count < 1) return val_string("null"); - switch (args[0].type) { - case VAL_NULL: return val_string("null"); - case VAL_BOOL: return val_string("bool"); - case VAL_INT: return val_string("int"); - case VAL_FLOAT: return val_string("float"); - case VAL_STRING: return val_string("string"); - case VAL_LIST: return val_string("list"); - case VAL_DICT: return val_string("dict"); - case VAL_BUILTIN_FN: - case VAL_FN: return val_string("function"); - case VAL_MODULE: return val_string("module"); - default: return val_string("unknown"); - } -} - -static AiraValue builtin_to_int(int arg_count, AiraValue* args) { - if (arg_count < 1) return val_int(0); - AiraValue v = args[0]; - if (v.type == VAL_INT) return v; - if (v.type == VAL_FLOAT) return val_int((int64_t)v.as.floating); - if (v.type == VAL_STRING) return val_int(strtoll(v.as.string, NULL, 10)); - if (v.type == VAL_BOOL) return val_int(v.as.boolean ? 1 : 0); - return val_int(0); -} - -static AiraValue builtin_to_float(int arg_count, AiraValue* args) { - if (arg_count < 1) return val_float(0.0); - AiraValue v = args[0]; - if (v.type == VAL_FLOAT) return v; - if (v.type == VAL_INT) return val_float((double)v.as.integer); - if (v.type == VAL_STRING) return val_float(strtod(v.as.string, NULL)); - return val_float(0.0); -} - -static AiraValue builtin_to_str(int arg_count, AiraValue* args) { - if (arg_count < 1) return val_string(""); - return val_string_take(val_to_string(args[0])); -} - -/* ============================================================================== - * Native C Module Implementations - * ============================================================================== */ - -/* Math Module Functions */ -static AiraValue math_sqrt(int argc, AiraValue* args) { - double x = (argc > 0 && args[0].type == VAL_INT) ? (double)args[0].as.integer : (argc > 0 ? args[0].as.floating : 0.0); - return val_float(sqrt(x)); -} - -static AiraValue math_pow(int argc, AiraValue* args) { - double b = (argc > 0 && args[0].type == VAL_INT) ? (double)args[0].as.integer : (argc > 0 ? args[0].as.floating : 0.0); - double e = (argc > 1 && args[1].type == VAL_INT) ? (double)args[1].as.integer : (argc > 1 ? args[1].as.floating : 0.0); - return val_float(pow(b, e)); -} - -static AiraValue math_abs(int argc, AiraValue* args) { - if (argc > 0 && args[0].type == VAL_INT) { - int64_t i = args[0].as.integer; - return val_int(i < 0 ? -i : i); - } - double x = argc > 0 ? args[0].as.floating : 0.0; - return val_float(fabs(x)); -} - -static AiraValue math_floor(int argc, AiraValue* args) { - double x = (argc > 0 && args[0].type == VAL_INT) ? (double)args[0].as.integer : (argc > 0 ? args[0].as.floating : 0.0); - return val_int((int64_t)floor(x)); -} - -static AiraValue math_ceil(int argc, AiraValue* args) { - double x = (argc > 0 && args[0].type == VAL_INT) ? (double)args[0].as.integer : (argc > 0 ? args[0].as.floating : 0.0); - return val_int((int64_t)ceil(x)); -} - -/* OS Module Functions */ -static AiraValue os_system(int argc, AiraValue* args) { - if (argc < 1 || args[0].type != VAL_STRING) return val_int(-1); - /* Safe execution check */ - int res = system(args[0].as.string); - return val_int(res); -} - -static AiraValue os_getcwd(int argc, AiraValue* args) { - (void)argc; (void)args; - char cwd[1024]; - if (getcwd(cwd, sizeof(cwd))) { - return val_string(cwd); - } - return val_string("."); -} - -static AiraValue os_getenv(int argc, AiraValue* args) { - if (argc < 1 || args[0].type != VAL_STRING) return val_null(); - char* val = getenv(args[0].as.string); - return val ? val_string(val) : val_null(); -} - -static AiraValue os_platform(int argc, AiraValue* args) { - (void)argc; (void)args; - return val_string("linux-aarch64 (S1 Duo Engine)"); -} - -/* Time Module Functions */ -static AiraValue time_time(int argc, AiraValue* args) { - (void)argc; (void)args; - struct timespec ts; - clock_gettime(CLOCK_REALTIME, &ts); - double sec = (double)ts.tv_sec + ((double)ts.tv_nsec / 1e9); - return val_float(sec); -} - -static AiraValue time_sleep(int argc, AiraValue* args) { - if (argc < 1) return val_null(); - double secs = (args[0].type == VAL_INT) ? (double)args[0].as.integer : args[0].as.floating; - if (secs > 0) { - usleep((useconds_t)(secs * 1000000)); - } - return val_null(); -} - -/* File Module Functions */ -static AiraValue file_read(int argc, AiraValue* args) { - if (argc < 1 || args[0].type != VAL_STRING) return val_string(""); - FILE* f = fopen(args[0].as.string, "rb"); - if (!f) return val_null(); - fseek(f, 0, SEEK_END); - long sz = ftell(f); - fseek(f, 0, SEEK_SET); - if (sz < 0 || sz > AIRA_MAX_STRING_LEN) { - fclose(f); - aira_panic("File %s exceeds maximum permitted memory size.", args[0].as.string); - } - char* buf = (char*)aira_malloc(sz + 1); - size_t read_bytes = fread(buf, 1, sz, f); - buf[read_bytes] = '\0'; - fclose(f); - return val_string_take(buf); -} - -static AiraValue file_write(int argc, AiraValue* args) { - if (argc < 2 || args[0].type != VAL_STRING) return val_bool(false); - FILE* f = fopen(args[0].as.string, "wb"); - if (!f) return val_bool(false); - char* content = val_to_string(args[1]); - fputs(content, f); - aira_free(content); - fclose(f); - return val_bool(true); -} - -static AiraValue file_append(int argc, AiraValue* args) { - if (argc < 2 || args[0].type != VAL_STRING) return val_bool(false); - FILE* f = fopen(args[0].as.string, "ab"); - if (!f) return val_bool(false); - char* content = val_to_string(args[1]); - fputs(content, f); - aira_free(content); - fclose(f); - return val_bool(true); -} - -static AiraValue file_exists(int argc, AiraValue* args) { - if (argc < 1 || args[0].type != VAL_STRING) return val_bool(false); - struct stat st; - return val_bool(stat(args[0].as.string, &st) == 0); -} - -/* Crypto & Sec Module Functions */ -static AiraValue crypto_sha256(int argc, AiraValue* args) { - if (argc < 1) return val_string(""); - char* str = val_to_string(args[0]); - char hash[65]; - aira_sha256((const uint8_t*)str, strlen(str), hash); - aira_free(str); - return val_string(hash); -} - -/* ============================================================================== - * Native AI & AiraAI Sovereign Module Functions - * ============================================================================== */ - -static char ai_provider_str[128] = "airagroup/aira-3-flash"; -static char ai_endpoint_str[256] = ""; -static char ai_system_prompt[512] = - "You are Aira, the official AI engine of AiraLang, engineered and created by Adam Eehan " - "(Founder & CEO, Aira Group of Technology)."; - -static AiraValue ai_set_provider(int argc, AiraValue* args) { - if (argc > 0 && args[0].type == VAL_STRING) { - strncpy(ai_provider_str, args[0].as.string, sizeof(ai_provider_str) - 1); - ai_provider_str[sizeof(ai_provider_str) - 1] = '\0'; - return val_bool(true); - } - return val_bool(false); -} - -static AiraValue ai_get_provider(int argc, AiraValue* args) { - (void)argc; (void)args; - return val_string(ai_provider_str); -} - -static AiraValue ai_set_endpoint(int argc, AiraValue* args) { - if (argc > 0 && args[0].type == VAL_STRING) { - strncpy(ai_endpoint_str, args[0].as.string, sizeof(ai_endpoint_str) - 1); - ai_endpoint_str[sizeof(ai_endpoint_str) - 1] = '\0'; - return val_bool(true); - } - return val_bool(false); -} - -static AiraValue ai_get_endpoint(int argc, AiraValue* args) { - (void)argc; (void)args; - const char* env_url = getenv("AIRA_API_URL"); - if (ai_endpoint_str[0]) return val_string(ai_endpoint_str); - if (env_url && strlen(env_url) > 0) return val_string(env_url); - return val_string("http://127.0.0.1:8080/v1/chat/completions"); -} - -static AiraValue ai_set_system(int argc, AiraValue* args) { - if (argc > 0 && args[0].type == VAL_STRING) { - strncpy(ai_system_prompt, args[0].as.string, sizeof(ai_system_prompt) - 1); - ai_system_prompt[sizeof(ai_system_prompt) - 1] = '\0'; - return val_bool(true); - } - return val_bool(false); -} - -static uint32_t json_parse_hex4(const char* s) { - uint32_t val = 0; - for (int i = 0; i < 4; i++) { - char c = s[i]; - val <<= 4; - if (c >= '0' && c <= '9') val |= (c - '0'); - else if (c >= 'a' && c <= 'f') val |= (c - 'a' + 10); - else if (c >= 'A' && c <= 'F') val |= (c - 'A' + 10); - else return 0; - } - return val; -} - -static size_t json_encode_utf8(uint32_t cp, char* out) { - if (cp <= 0x7F) { - out[0] = (char)cp; - return 1; - } else if (cp <= 0x7FF) { - out[0] = (char)(0xC0 | (cp >> 6)); - out[1] = (char)(0x80 | (cp & 0x3F)); - return 2; - } else if (cp <= 0xFFFF) { - out[0] = (char)(0xE0 | (cp >> 12)); - out[1] = (char)(0x80 | ((cp >> 6) & 0x3F)); - out[2] = (char)(0x80 | (cp & 0x3F)); - return 3; - } else if (cp <= 0x10FFFF) { - out[0] = (char)(0xF0 | (cp >> 18)); - out[1] = (char)(0x80 | ((cp >> 12) & 0x3F)); - out[2] = (char)(0x80 | ((cp >> 6) & 0x3F)); - out[3] = (char)(0x80 | (cp & 0x3F)); - return 4; - } - return 0; -} - -static AiraValue ai_ask(int argc, AiraValue* args) { - if (argc < 1) return val_string(""); - char* prompt = val_to_string(args[0]); - - const char* target_url = "http://127.0.0.1:8080/v1/chat/completions"; - if (ai_endpoint_str[0]) { - target_url = ai_endpoint_str; - } else { - const char* env_url = getenv("AIRA_API_URL"); - if (env_url && strlen(env_url) > 0) { - target_url = env_url; - } - } - - /* Auto-launch Aira-AI-Endpoint locally only if target URL is localhost */ - if (strstr(target_url, "127.0.0.1") || strstr(target_url, "localhost")) { - system("pgrep -f 'Aira-AI-Endpoint/server.py' >/dev/null 2>&1 || (nohup python3 $HOME/Aira-AI-Endpoint/server.py >/dev/null 2>&1 & sleep 1)"); - } - - /* Escape quotes for safe curl execution */ - char safe_prompt[2048]; - size_t j = 0; - for (size_t i = 0; prompt[i] && j < sizeof(safe_prompt) - 4; i++) { - if (prompt[i] == '"' || prompt[i] == '\\' || prompt[i] == '`' || prompt[i] == '$') { - safe_prompt[j++] = '\\'; - } - safe_prompt[j++] = prompt[i]; - } - safe_prompt[j] = '\0'; - - char cmd[4096]; - snprintf(cmd, sizeof(cmd), - "curl -s -m 35 -X POST '%s' " - "-H 'Content-Type: application/json' " - "-d '{\"model\": \"%s\", \"messages\": [{\"role\": \"user\", \"content\": \"%s\"}]}' 2>/dev/null", - target_url, ai_provider_str, safe_prompt - ); - - FILE* fp = popen(cmd, "r"); - char res_buf[8192]; - size_t bytes = 0; - if (fp) { - bytes = fread(res_buf, 1, sizeof(res_buf) - 1, fp); - res_buf[bytes] = '\0'; - pclose(fp); - } - - aira_free(prompt); - - /* If API returned valid content, extract and unescape it */ - if (bytes > 10 && strstr(res_buf, "\"content\":")) { - char* content_start = strstr(res_buf, "\"content\":"); - if (content_start) { - content_start += 10; - while (*content_start == ' ' || *content_start == '\t' || *content_start == '\r' || *content_start == '\n') content_start++; - if (*content_start == '"') { - content_start++; - /* Find unescaped end quote */ - char* p = content_start; - while (*p) { - if (*p == '\\' && *(p + 1)) { - p += 2; - } else if (*p == '"') { - *p = '\0'; - break; - } else { - p++; - } - } - /* Unescape \n, \", etc. */ - char* clean = (char*)aira_malloc(strlen(content_start) + 1); - size_t c_idx = 0; - for (size_t k = 0; content_start[k]; k++) { - if (content_start[k] == '\\' && content_start[k+1]) { - char esc = content_start[k+1]; - if (esc == 'n') { clean[c_idx++] = '\n'; k++; } - else if (esc == 't') { clean[c_idx++] = '\t'; k++; } - else if (esc == 'r') { clean[c_idx++] = '\r'; k++; } - else if (esc == '"') { clean[c_idx++] = '"'; k++; } - else if (esc == '\\') { clean[c_idx++] = '\\'; k++; } - else if (esc == 'u' && content_start[k+2] && content_start[k+3] && content_start[k+4] && content_start[k+5]) { - uint32_t cp = json_parse_hex4(&content_start[k+2]); - k += 5; - /* Check for UTF-16 surrogate pair (e.g. \uD83D\uDCAC -> πŸ’¬) */ - if (cp >= 0xD800 && cp <= 0xDBFF && content_start[k+1] == '\\' && content_start[k+2] == 'u' && - content_start[k+3] && content_start[k+4] && content_start[k+5] && content_start[k+6]) { - uint32_t low = json_parse_hex4(&content_start[k+3]); - if (low >= 0xDC00 && low <= 0xDFFF) { - cp = 0x10000 + ((cp - 0xD800) << 10) + (low - 0xDC00); - k += 6; - } - } - c_idx += json_encode_utf8(cp, &clean[c_idx]); - } else { - clean[c_idx++] = esc; - k++; - } - } else { - clean[c_idx++] = content_start[k]; - } - } - clean[c_idx] = '\0'; - AiraValue ret = val_string(clean); - aira_free(clean); - return ret; - } - } - } - - /* Sovereign Swarm Zero-Key Default Response */ - char fallback[512]; - snprintf(fallback, sizeof(fallback), - "Hello Boss! I am Aira AI (Sovereign Engine v3.6, Swarm: %s), " - "created by Adam Eehan. I am connected directly to AiraLang systems core!", - ai_provider_str - ); - return val_string(fallback); -} - -/* ============================================================================== - * Registration & Loader - * ============================================================================== */ - -void register_builtin_globals(Environment* env) { - env_define(env, "len", val_builtin(builtin_len)); - env_define(env, "range", val_builtin(builtin_range)); - env_define(env, "input", val_builtin(builtin_input)); - env_define(env, "type", val_builtin(builtin_type)); - env_define(env, "int", val_builtin(builtin_to_int)); - env_define(env, "float", val_builtin(builtin_to_float)); - env_define(env, "str", val_builtin(builtin_to_str)); -} - -AiraValue load_builtin_module(const char* name) { - if (strcmp(name, "math") == 0) { - AiraValue mod = val_module("math"); - dict_set(mod.as.module->members, "sqrt", val_builtin(math_sqrt)); - dict_set(mod.as.module->members, "pow", val_builtin(math_pow)); - dict_set(mod.as.module->members, "abs", val_builtin(math_abs)); - dict_set(mod.as.module->members, "floor", val_builtin(math_floor)); - dict_set(mod.as.module->members, "ceil", val_builtin(math_ceil)); - dict_set(mod.as.module->members, "pi", val_float(3.141592653589793)); - dict_set(mod.as.module->members, "e", val_float(2.718281828459045)); - return mod; - } - - if (strcmp(name, "os") == 0 || strcmp(name, "system") == 0) { - AiraValue mod = val_module("os"); - dict_set(mod.as.module->members, "system", val_builtin(os_system)); - dict_set(mod.as.module->members, "getcwd", val_builtin(os_getcwd)); - dict_set(mod.as.module->members, "getenv", val_builtin(os_getenv)); - dict_set(mod.as.module->members, "platform", val_builtin(os_platform)); - return mod; - } - - if (strcmp(name, "time") == 0) { - AiraValue mod = val_module("time"); - dict_set(mod.as.module->members, "time", val_builtin(time_time)); - dict_set(mod.as.module->members, "sleep", val_builtin(time_sleep)); - return mod; - } - - if (strcmp(name, "file") == 0) { - AiraValue mod = val_module("file"); - dict_set(mod.as.module->members, "read", val_builtin(file_read)); - dict_set(mod.as.module->members, "write", val_builtin(file_write)); - dict_set(mod.as.module->members, "append", val_builtin(file_append)); - dict_set(mod.as.module->members, "exists", val_builtin(file_exists)); - return mod; - } - - if (strcmp(name, "crypto") == 0 || strcmp(name, "sec") == 0) { - AiraValue mod = val_module("crypto"); - dict_set(mod.as.module->members, "sha256", val_builtin(crypto_sha256)); - dict_set(mod.as.module->members, "hash", val_builtin(crypto_sha256)); - return mod; - } - - if (strcmp(name, "ai") == 0 || strcmp(name, "airaai") == 0) { - AiraValue mod = val_module("ai"); - dict_set(mod.as.module->members, "set_provider", val_builtin(ai_set_provider)); - dict_set(mod.as.module->members, "get_provider", val_builtin(ai_get_provider)); - dict_set(mod.as.module->members, "set_endpoint", val_builtin(ai_set_endpoint)); - dict_set(mod.as.module->members, "get_endpoint", val_builtin(ai_get_endpoint)); - dict_set(mod.as.module->members, "set_system", val_builtin(ai_set_system)); - dict_set(mod.as.module->members, "ask", val_builtin(ai_ask)); - return mod; - } - - return val_null(); -} diff --git a/s1duo/src/parser.c b/s1duo/src/parser.c deleted file mode 100644 index d59047e..0000000 --- a/s1duo/src/parser.c +++ /dev/null @@ -1,552 +0,0 @@ -#include "../include/parser.h" - -static void advance(Parser* parser) { - parser->previous = parser->current; - - for (;;) { - parser->current = lexer_next_token(&parser->lexer); - if (parser->current.type != TOKEN_ERROR) break; - - aira_error_at(parser->filename, parser->current.line, parser->current.col, "%s", parser->current.text); - parser->had_error = true; - } -} - -static bool check(Parser* parser, TokenType type) { - return parser->current.type == type; -} - -static bool match(Parser* parser, TokenType type) { - if (!check(parser, type)) return false; - advance(parser); - return true; -} - -static void consume(Parser* parser, TokenType type, const char* message) { - if (parser->current.type == type) { - advance(parser); - return; - } - aira_error_at(parser->filename, parser->current.line, parser->current.col, "%s", message); - parser->had_error = true; -} - -static void match_semicolon(Parser* parser) { - if (match(parser, TOKEN_SEMICOLON)) return; - /* Lenient if next is RBRACE or EOF */ - if (check(parser, TOKEN_RBRACE) || check(parser, TOKEN_EOF)) return; -} - -/* Forward declarations */ -static ExprNode* expression(Parser* parser); -static StmtNode* statement(Parser* parser); -static StmtNode* block(Parser* parser); - -/* Expression Parsing with Precedence Climbing */ - -static ExprNode* primary(Parser* parser) { - int line = parser->current.line; - int col = parser->current.col; - - if (match(parser, TOKEN_NUMBER)) { - double val = parser->previous.num_val; - if (val == (int64_t)val) { - return expr_literal(val_int((int64_t)val), line, col); - } else { - return expr_literal(val_float(val), line, col); - } - } - - if (match(parser, TOKEN_STRING)) { - return expr_literal(val_string(parser->previous.text), line, col); - } - - if (match(parser, TOKEN_TRUE)) { - return expr_literal(val_bool(true), line, col); - } - - if (match(parser, TOKEN_FALSE)) { - return expr_literal(val_bool(false), line, col); - } - - if (match(parser, TOKEN_NULL)) { - return expr_literal(val_null(), line, col); - } - - if (match(parser, TOKEN_IDENTIFIER)) { - return expr_identifier(parser->previous.text, line, col); - } - - if (match(parser, TOKEN_LPAREN)) { - ExprNode* expr = expression(parser); - consume(parser, TOKEN_RPAREN, "Expected ')' after expression."); - return expr; - } - - /* List Literal: [1, 2, 3] */ - if (match(parser, TOKEN_LBRACKET)) { - int cap = 8; - int count = 0; - ExprNode** elements = (ExprNode**)aira_malloc(sizeof(ExprNode*) * cap); - - if (!check(parser, TOKEN_RBRACKET)) { - do { - if (count >= cap) { - cap *= 2; - elements = (ExprNode**)aira_realloc(elements, sizeof(ExprNode*) * cap); - } - elements[count++] = expression(parser); - } while (match(parser, TOKEN_COMMA)); - } - consume(parser, TOKEN_RBRACKET, "Expected ']' after list elements."); - return expr_list(elements, count, line, col); - } - - /* Dict Literal: {"key": value} */ - if (match(parser, TOKEN_LBRACE)) { - int cap = 8; - int count = 0; - char** keys = (char**)aira_malloc(sizeof(char*) * cap); - ExprNode** values = (ExprNode**)aira_malloc(sizeof(ExprNode*) * cap); - - if (!check(parser, TOKEN_RBRACE)) { - do { - if (count >= cap) { - cap *= 2; - keys = (char**)aira_realloc(keys, sizeof(char*) * cap); - values = (ExprNode**)aira_realloc(values, sizeof(ExprNode*) * cap); - } - if (!match(parser, TOKEN_STRING) && !match(parser, TOKEN_IDENTIFIER)) { - aira_error_at(parser->filename, parser->current.line, parser->current.col, "Expected string or identifier key in dictionary."); - break; - } - keys[count] = aira_strdup(parser->previous.text); - consume(parser, TOKEN_COLON, "Expected ':' after dictionary key."); - values[count] = expression(parser); - count++; - } while (match(parser, TOKEN_COMMA)); - } - consume(parser, TOKEN_RBRACE, "Expected '}' after dictionary."); - return expr_dict(keys, values, count, line, col); - } - - aira_error_at(parser->filename, parser->current.line, parser->current.col, "Unexpected token '%s' in expression.", parser->current.text ? parser->current.text : "EOF"); - parser->had_error = true; - advance(parser); - return expr_literal(val_null(), line, col); -} - -static ExprNode* call_or_access(Parser* parser) { - ExprNode* expr = primary(parser); - - for (;;) { - int line = parser->current.line; - int col = parser->current.col; - - if (match(parser, TOKEN_LPAREN)) { - /* Function call */ - int cap = 4; - int count = 0; - ExprNode** args = (ExprNode**)aira_malloc(sizeof(ExprNode*) * cap); - - if (!check(parser, TOKEN_RPAREN)) { - do { - if (count >= cap) { - cap *= 2; - args = (ExprNode**)aira_realloc(args, sizeof(ExprNode*) * cap); - } - args[count++] = expression(parser); - } while (match(parser, TOKEN_COMMA)); - } - consume(parser, TOKEN_RPAREN, "Expected ')' after function arguments."); - expr = expr_call(expr, args, count, line, col); - } else if (match(parser, TOKEN_LBRACKET)) { - /* Index access */ - ExprNode* index = expression(parser); - consume(parser, TOKEN_RBRACKET, "Expected ']' after index."); - expr = expr_index(expr, index, line, col); - } else if (match(parser, TOKEN_DOT)) { - /* Member access */ - consume(parser, TOKEN_IDENTIFIER, "Expected member name after '.'."); - expr = expr_member(expr, parser->previous.text, line, col); - } else { - break; - } - } - return expr; -} - -static ExprNode* unary(Parser* parser) { - if (match(parser, TOKEN_BANG) || match(parser, TOKEN_NOT) || match(parser, TOKEN_MINUS) || match(parser, TOKEN_PLUS)) { - TokenType op = parser->previous.type; - int line = parser->previous.line; - int col = parser->previous.col; - ExprNode* right = unary(parser); - return expr_unary(op, right, line, col); - } - return call_or_access(parser); -} - -static ExprNode* factor(Parser* parser) { - ExprNode* expr = unary(parser); - - while (match(parser, TOKEN_STAR) || match(parser, TOKEN_SLASH) || match(parser, TOKEN_PERCENT)) { - TokenType op = parser->previous.type; - int line = parser->previous.line; - int col = parser->previous.col; - ExprNode* right = unary(parser); - expr = expr_binary(op, expr, right, line, col); - } - return expr; -} - -static ExprNode* term(Parser* parser) { - ExprNode* expr = factor(parser); - - while (match(parser, TOKEN_PLUS) || match(parser, TOKEN_MINUS)) { - TokenType op = parser->previous.type; - int line = parser->previous.line; - int col = parser->previous.col; - ExprNode* right = factor(parser); - expr = expr_binary(op, expr, right, line, col); - } - return expr; -} - -static ExprNode* comparison(Parser* parser) { - ExprNode* expr = term(parser); - - while (match(parser, TOKEN_GREATER) || match(parser, TOKEN_GREATER_EQUAL) || - match(parser, TOKEN_LESS) || match(parser, TOKEN_LESS_EQUAL)) { - TokenType op = parser->previous.type; - int line = parser->previous.line; - int col = parser->previous.col; - ExprNode* right = term(parser); - expr = expr_binary(op, expr, right, line, col); - } - return expr; -} - -static ExprNode* equality(Parser* parser) { - ExprNode* expr = comparison(parser); - - while (match(parser, TOKEN_EQUAL_EQUAL) || match(parser, TOKEN_BANG_EQUAL)) { - TokenType op = parser->previous.type; - int line = parser->previous.line; - int col = parser->previous.col; - ExprNode* right = comparison(parser); - expr = expr_binary(op, expr, right, line, col); - } - return expr; -} - -static ExprNode* logical_and(Parser* parser) { - ExprNode* expr = equality(parser); - - while (match(parser, TOKEN_AND_AND) || match(parser, TOKEN_AND)) { - TokenType op = parser->previous.type; - int line = parser->previous.line; - int col = parser->previous.col; - ExprNode* right = equality(parser); - expr = expr_binary(op, expr, right, line, col); - } - return expr; -} - -static ExprNode* logical_or(Parser* parser) { - ExprNode* expr = logical_and(parser); - - while (match(parser, TOKEN_OR_OR) || match(parser, TOKEN_OR)) { - TokenType op = parser->previous.type; - int line = parser->previous.line; - int col = parser->previous.col; - ExprNode* right = logical_and(parser); - expr = expr_binary(op, expr, right, line, col); - } - return expr; -} - -static ExprNode* expression(Parser* parser) { - return logical_or(parser); -} - -/* Statement Parsing */ - -static StmtNode* let_declaration(Parser* parser) { - int line = parser->previous.line; - int col = parser->previous.col; - consume(parser, TOKEN_IDENTIFIER, "Expected variable name after 'let'."); - char* name = aira_strdup(parser->previous.text); - - ExprNode* init = NULL; - if (match(parser, TOKEN_ASSIGN)) { - init = expression(parser); - } else { - init = expr_literal(val_null(), line, col); - } - match_semicolon(parser); - StmtNode* s = stmt_let(name, init, line, col); - aira_free(name); - return s; -} - -static StmtNode* say_or_print_statement(Parser* parser, bool is_say) { - int line = parser->previous.line; - int col = parser->previous.col; - int cap = 4; - int count = 0; - ExprNode** exprs = (ExprNode**)aira_malloc(sizeof(ExprNode*) * cap); - - /* Check if print has parentheses like print("hello") */ - bool has_paren = match(parser, TOKEN_LPAREN); - - if (!has_paren || !check(parser, TOKEN_RPAREN)) { - do { - if (count >= cap) { - cap *= 2; - exprs = (ExprNode**)aira_realloc(exprs, sizeof(ExprNode*) * cap); - } - exprs[count++] = expression(parser); - } while (match(parser, TOKEN_COMMA)); - } - - if (has_paren) { - consume(parser, TOKEN_RPAREN, "Expected ')' after arguments."); - } - - match_semicolon(parser); - if (is_say) { - return stmt_say(exprs, count, line, col); - } else { - return stmt_print(exprs, count, line, col); - } -} - -static StmtNode* if_statement(Parser* parser) { - int line = parser->previous.line; - int col = parser->previous.col; - bool has_paren = match(parser, TOKEN_LPAREN); - ExprNode* condition = expression(parser); - if (has_paren) { - consume(parser, TOKEN_RPAREN, "Expected ')' after if condition."); - } - - StmtNode* then_branch = statement(parser); - StmtNode* else_branch = NULL; - - if (match(parser, TOKEN_ELSE)) { - else_branch = statement(parser); - } - return stmt_if(condition, then_branch, else_branch, line, col); -} - -static StmtNode* while_statement(Parser* parser) { - int line = parser->previous.line; - int col = parser->previous.col; - bool has_paren = match(parser, TOKEN_LPAREN); - ExprNode* condition = expression(parser); - if (has_paren) { - consume(parser, TOKEN_RPAREN, "Expected ')' after while condition."); - } - StmtNode* body = statement(parser); - return stmt_while(condition, body, line, col); -} - -static StmtNode* for_statement(Parser* parser) { - int line = parser->previous.line; - int col = parser->previous.col; - consume(parser, TOKEN_IDENTIFIER, "Expected variable name after 'for'."); - char* var_name = aira_strdup(parser->previous.text); - - consume(parser, TOKEN_IN, "Expected 'in' after for variable."); - ExprNode* iterable = expression(parser); - StmtNode* body = statement(parser); - - StmtNode* s = stmt_for_in(var_name, iterable, body, line, col); - aira_free(var_name); - return s; -} - -static StmtNode* fn_declaration(Parser* parser) { - int line = parser->previous.line; - int col = parser->previous.col; - consume(parser, TOKEN_IDENTIFIER, "Expected function name after 'fn'."); - char* name = aira_strdup(parser->previous.text); - - consume(parser, TOKEN_LPAREN, "Expected '(' after function name."); - int cap = 4; - int count = 0; - char** params = (char**)aira_malloc(sizeof(char*) * cap); - - if (!check(parser, TOKEN_RPAREN)) { - do { - if (count >= cap) { - cap *= 2; - params = (char**)aira_realloc(params, sizeof(char*) * cap); - } - consume(parser, TOKEN_IDENTIFIER, "Expected parameter name."); - params[count++] = aira_strdup(parser->previous.text); - } while (match(parser, TOKEN_COMMA)); - } - consume(parser, TOKEN_RPAREN, "Expected ')' after parameters."); - StmtNode* body = block(parser); - - StmtNode* s = stmt_fn_def(name, params, count, body, line, col); - aira_free(name); - return s; -} - -static StmtNode* return_statement(Parser* parser) { - int line = parser->previous.line; - int col = parser->previous.col; - ExprNode* expr = NULL; - if (!check(parser, TOKEN_SEMICOLON) && !check(parser, TOKEN_RBRACE)) { - expr = expression(parser); - } - match_semicolon(parser); - return stmt_return(expr, line, col); -} - -static StmtNode* import_statement(Parser* parser) { - int line = parser->previous.line; - int col = parser->previous.col; - - char* mod_name = NULL; - if (match(parser, TOKEN_STRING) || match(parser, TOKEN_IDENTIFIER)) { - mod_name = aira_strdup(parser->previous.text); - } else { - aira_error_at(parser->filename, line, col, "Expected module name after 'import'."); - mod_name = aira_strdup("unknown"); - } - - char* source = NULL; - if (match(parser, TOKEN_FROM)) { - if (match(parser, TOKEN_STRING) || match(parser, TOKEN_IDENTIFIER)) { - source = aira_strdup(parser->previous.text); - } - } - - match_semicolon(parser); - StmtNode* s = stmt_import(mod_name, source, NULL, line, col); - aira_free(mod_name); - if (source) aira_free(source); - return s; -} - -static StmtNode* block(Parser* parser) { - int line = parser->current.line; - int col = parser->current.col; - consume(parser, TOKEN_LBRACE, "Expected '{' before block."); - - int cap = 8; - int count = 0; - StmtNode** statements = (StmtNode**)aira_malloc(sizeof(StmtNode*) * cap); - - while (!check(parser, TOKEN_RBRACE) && !check(parser, TOKEN_EOF)) { - if (count >= cap) { - cap *= 2; - statements = (StmtNode**)aira_realloc(statements, sizeof(StmtNode*) * cap); - } - statements[count++] = statement(parser); - } - consume(parser, TOKEN_RBRACE, "Expected '}' after block."); - return stmt_block(statements, count, line, col); -} - -static StmtNode* expression_statement(Parser* parser) { - int line = parser->current.line; - int col = parser->current.col; - - /* Check for assignment target: ident = expr, ident += expr, target[idx] = expr, target.mem = expr */ - ExprNode* expr = expression(parser); - - if (match(parser, TOKEN_ASSIGN) || match(parser, TOKEN_PLUS_ASSIGN) || - match(parser, TOKEN_MINUS_ASSIGN) || match(parser, TOKEN_STAR_ASSIGN) || - match(parser, TOKEN_SLASH_ASSIGN) || match(parser, TOKEN_MOD_ASSIGN)) { - TokenType op = parser->previous.type; - - if (expr->type == EXPR_IDENTIFIER) { - char* name = aira_strdup(expr->as.identifier); - expr_free(expr); - ExprNode* val = expression(parser); - match_semicolon(parser); - StmtNode* s = stmt_assign(name, op, val, line, col); - aira_free(name); - return s; - } else if (expr->type == EXPR_INDEX) { - ExprNode* target = expr->as.index_access.target; - ExprNode* index = expr->as.index_access.index; - aira_free(expr); - ExprNode* val = expression(parser); - match_semicolon(parser); - return stmt_index_assign(target, index, val, line, col); - } else if (expr->type == EXPR_MEMBER) { - ExprNode* target = expr->as.member_access.target; - char* mem = aira_strdup(expr->as.member_access.member); - expr_free(expr); - ExprNode* val = expression(parser); - match_semicolon(parser); - StmtNode* s = stmt_member_assign(target, mem, val, line, col); - aira_free(mem); - return s; - } - } - - match_semicolon(parser); - return stmt_expr(expr, line, col); -} - -static StmtNode* statement(Parser* parser) { - if (match(parser, TOKEN_LET)) return let_declaration(parser); - if (match(parser, TOKEN_SAY)) return say_or_print_statement(parser, true); - if (match(parser, TOKEN_PRINT)) return say_or_print_statement(parser, false); - if (match(parser, TOKEN_IF)) return if_statement(parser); - if (match(parser, TOKEN_WHILE)) return while_statement(parser); - if (match(parser, TOKEN_FOR)) return for_statement(parser); - if (match(parser, TOKEN_FN)) return fn_declaration(parser); - if (match(parser, TOKEN_RETURN)) return return_statement(parser); - if (match(parser, TOKEN_IMPORT)) return import_statement(parser); - if (match(parser, TOKEN_BREAK)) { - match_semicolon(parser); - return stmt_break(parser->previous.line, parser->previous.col); - } - if (match(parser, TOKEN_CONTINUE)) { - match_semicolon(parser); - return stmt_continue(parser->previous.line, parser->previous.col); - } - if (check(parser, TOKEN_LBRACE)) return block(parser); - - /* Skip @ directives like @airaai */ - if (match(parser, TOKEN_AT)) { - advance(parser); /* consume directive name */ - if (check(parser, TOKEN_STRING)) advance(parser); - match_semicolon(parser); - return stmt_expr(expr_literal(val_null(), 0, 0), 0, 0); - } - - return expression_statement(parser); -} - -void parser_init(Parser* parser, const char* source, const char* filename) { - lexer_init(&parser->lexer, source, filename); - parser->filename = filename; - parser->had_error = false; - parser->panic_mode = false; - advance(parser); -} - -StmtNode* parser_parse(Parser* parser) { - int cap = 16; - int count = 0; - StmtNode** statements = (StmtNode**)aira_malloc(sizeof(StmtNode*) * cap); - - while (!check(parser, TOKEN_EOF)) { - if (count >= cap) { - cap *= 2; - statements = (StmtNode**)aira_realloc(statements, sizeof(StmtNode*) * cap); - } - statements[count++] = statement(parser); - } - - return stmt_program(statements, count, 1, 1); -} diff --git a/s1duo/src/value.c b/s1duo/src/value.c deleted file mode 100644 index 4cba6f8..0000000 --- a/s1duo/src/value.c +++ /dev/null @@ -1,369 +0,0 @@ -#include "../include/value.h" -#include - -AiraValue val_null(void) { - AiraValue v; - v.type = VAL_NULL; - v.as.integer = 0; - return v; -} - -AiraValue val_bool(bool b) { - AiraValue v; - v.type = VAL_BOOL; - v.as.boolean = b; - return v; -} - -AiraValue val_int(int64_t i) { - AiraValue v; - v.type = VAL_INT; - v.as.integer = i; - return v; -} - -AiraValue val_float(double f) { - AiraValue v; - v.type = VAL_FLOAT; - v.as.floating = f; - return v; -} - -AiraValue val_string(const char* s) { - AiraValue v; - v.type = VAL_STRING; - v.as.string = aira_strdup(s ? s : ""); - return v; -} - -AiraValue val_string_take(char* s) { - AiraValue v; - v.type = VAL_STRING; - v.as.string = s ? s : aira_strdup(""); - return v; -} - -AiraValue val_list(void) { - AiraValue v; - v.type = VAL_LIST; - AiraList* list = (AiraList*)aira_malloc(sizeof(AiraList)); - list->count = 0; - list->capacity = 8; - list->elements = (AiraValue*)aira_malloc(sizeof(AiraValue) * list->capacity); - v.as.list = list; - return v; -} - -AiraValue val_dict(void) { - AiraValue v; - v.type = VAL_DICT; - AiraDict* dict = (AiraDict*)aira_malloc(sizeof(AiraDict)); - dict->count = 0; - dict->capacity = 8; - dict->keys = (char**)aira_malloc(sizeof(char*) * dict->capacity); - dict->values = (AiraValue*)aira_malloc(sizeof(AiraValue) * dict->capacity); - v.as.dict = dict; - return v; -} - -AiraValue val_builtin(AiraBuiltinFn fn) { - AiraValue v; - v.type = VAL_BUILTIN_FN; - v.as.builtin = fn; - return v; -} - -AiraValue val_function(const char* name, struct StmtNode* node, struct Environment* closure) { - AiraValue v; - v.type = VAL_FN; - AiraFunction* fn = (AiraFunction*)aira_malloc(sizeof(AiraFunction)); - fn->name = name ? aira_strdup(name) : NULL; - fn->node = node; - fn->closure = closure; - v.as.fn = fn; - return v; -} - -AiraValue val_module(const char* name) { - AiraValue v; - v.type = VAL_MODULE; - AiraModule* mod = (AiraModule*)aira_malloc(sizeof(AiraModule)); - mod->name = aira_strdup(name ? name : "module"); - mod->members = (AiraDict*)aira_malloc(sizeof(AiraDict)); - mod->members->count = 0; - mod->members->capacity = 16; - mod->members->keys = (char**)aira_malloc(sizeof(char*) * mod->members->capacity); - mod->members->values = (AiraValue*)aira_malloc(sizeof(AiraValue) * mod->members->capacity); - v.as.module = mod; - return v; -} - -bool val_is_truthy(AiraValue v) { - switch (v.type) { - case VAL_NULL: return false; - case VAL_BOOL: return v.as.boolean; - case VAL_INT: return v.as.integer != 0; - case VAL_FLOAT: return v.as.floating != 0.0; - case VAL_STRING: return v.as.string && v.as.string[0] != '\0'; - case VAL_LIST: return v.as.list && v.as.list->count > 0; - case VAL_DICT: return v.as.dict && v.as.dict->count > 0; - default: return true; - } -} - -bool val_equals(AiraValue a, AiraValue b) { - if (a.type != b.type) return false; - switch (a.type) { - case VAL_NULL: return true; - case VAL_BOOL: return a.as.boolean == b.as.boolean; - case VAL_INT: return a.as.integer == b.as.integer; - case VAL_FLOAT: return a.as.floating == b.as.floating; - case VAL_STRING: return strcmp(a.as.string, b.as.string) == 0; - case VAL_LIST: return a.as.list == b.as.list; - case VAL_DICT: return a.as.dict == b.as.dict; - case VAL_BUILTIN_FN: return a.as.builtin == b.as.builtin; - case VAL_FN: return a.as.fn == b.as.fn; - case VAL_MODULE: return a.as.module == b.as.module; - default: return false; - } -} - -int val_compare(AiraValue a, AiraValue b) { - if (a.type == VAL_INT && b.type == VAL_INT) { - if (a.as.integer < b.as.integer) return -1; - if (a.as.integer > b.as.integer) return 1; - return 0; - } - if (a.type == VAL_FLOAT && b.type == VAL_FLOAT) { - if (a.as.floating < b.as.floating) return -1; - if (a.as.floating > b.as.floating) return 1; - return 0; - } - if (a.type == VAL_INT && b.type == VAL_FLOAT) { - double diff = (double)a.as.integer - b.as.floating; - return (diff < 0) ? -1 : (diff > 0 ? 1 : 0); - } - if (a.type == VAL_FLOAT && b.type == VAL_INT) { - double diff = a.as.floating - (double)b.as.integer; - return (diff < 0) ? -1 : (diff > 0 ? 1 : 0); - } - if (a.type == VAL_STRING && b.type == VAL_STRING) { - return strcmp(a.as.string, b.as.string); - } - return 0; -} - -AiraValue val_add(AiraValue a, AiraValue b) { - if (a.type == VAL_INT && b.type == VAL_INT) { - return val_int(a.as.integer + b.as.integer); - } - if (a.type == VAL_FLOAT && b.type == VAL_FLOAT) { - return val_float(a.as.floating + b.as.floating); - } - if (a.type == VAL_INT && b.type == VAL_FLOAT) { - return val_float((double)a.as.integer + b.as.floating); - } - if (a.type == VAL_FLOAT && b.type == VAL_INT) { - return val_float(a.as.floating + (double)b.as.integer); - } - if (a.type == VAL_STRING || b.type == VAL_STRING) { - char* str_a = val_to_string(a); - char* str_b = val_to_string(b); - size_t len_a = strlen(str_a); - size_t len_b = strlen(str_b); - size_t total = len_a + len_b; - if (total > AIRA_MAX_STRING_LEN) { - aira_panic("String concatenation exceeds limit (%d bytes).", AIRA_MAX_STRING_LEN); - } - char* res = (char*)aira_malloc(total + 1); - memcpy(res, str_a, len_a); - memcpy(res + len_a, str_b, len_b); - res[total] = '\0'; - aira_free(str_a); - aira_free(str_b); - return val_string_take(res); - } - aira_panic("Runtime TypeError: Invalid operands for '+' operator."); - return val_null(); -} - -AiraValue val_sub(AiraValue a, AiraValue b) { - if (a.type == VAL_INT && b.type == VAL_INT) return val_int(a.as.integer - b.as.integer); - if (a.type == VAL_FLOAT && b.type == VAL_FLOAT) return val_float(a.as.floating - b.as.floating); - if (a.type == VAL_INT && b.type == VAL_FLOAT) return val_float((double)a.as.integer - b.as.floating); - if (a.type == VAL_FLOAT && b.type == VAL_INT) return val_float(a.as.floating - (double)b.as.integer); - aira_panic("Runtime TypeError: Invalid operands for '-' operator."); - return val_null(); -} - -AiraValue val_mul(AiraValue a, AiraValue b) { - if (a.type == VAL_INT && b.type == VAL_INT) return val_int(a.as.integer * b.as.integer); - if (a.type == VAL_FLOAT && b.type == VAL_FLOAT) return val_float(a.as.floating * b.as.floating); - if (a.type == VAL_INT && b.type == VAL_FLOAT) return val_float((double)a.as.integer * b.as.floating); - if (a.type == VAL_FLOAT && b.type == VAL_INT) return val_float(a.as.floating * (double)b.as.integer); - aira_panic("Runtime TypeError: Invalid operands for '*' operator."); - return val_null(); -} - -AiraValue val_div(AiraValue a, AiraValue b) { - double denom = (b.type == VAL_INT) ? (double)b.as.integer : ((b.type == VAL_FLOAT) ? b.as.floating : 0.0); - if (denom == 0.0) { - aira_panic("Arithmetic Error: Division by zero."); - } - double num = (a.type == VAL_INT) ? (double)a.as.integer : ((a.type == VAL_FLOAT) ? a.as.floating : 0.0); - return val_float(num / denom); -} - -AiraValue val_mod(AiraValue a, AiraValue b) { - if (a.type == VAL_INT && b.type == VAL_INT) { - if (b.as.integer == 0) { - aira_panic("Arithmetic Error: Modulo by zero."); - } - return val_int(a.as.integer % b.as.integer); - } - aira_panic("Runtime TypeError: Modulo operator requires integer operands."); - return val_null(); -} - -char* val_to_string(AiraValue v) { - char buf[128]; - switch (v.type) { - case VAL_NULL: return aira_strdup("null"); - case VAL_BOOL: return aira_strdup(v.as.boolean ? "true" : "false"); - case VAL_INT: - snprintf(buf, sizeof(buf), "%" PRId64, v.as.integer); - return aira_strdup(buf); - case VAL_FLOAT: - snprintf(buf, sizeof(buf), "%g", v.as.floating); - return aira_strdup(buf); - case VAL_STRING: return aira_strdup(v.as.string); - case VAL_LIST: { - AiraStringBuilder sb; - sb_init(&sb); - sb_append_char(&sb, '['); - for (int i = 0; i < v.as.list->count; i++) { - if (i > 0) sb_append(&sb, ", "); - char* elem_str = val_to_string(v.as.list->elements[i]); - sb_append(&sb, elem_str); - aira_free(elem_str); - } - sb_append_char(&sb, ']'); - return sb_finish(&sb); - } - case VAL_DICT: { - AiraStringBuilder sb; - sb_init(&sb); - sb_append_char(&sb, '{'); - for (int i = 0; i < v.as.dict->count; i++) { - if (i > 0) sb_append(&sb, ", "); - sb_append(&sb, v.as.dict->keys[i]); - sb_append(&sb, ": "); - char* val_str = val_to_string(v.as.dict->values[i]); - sb_append(&sb, val_str); - aira_free(val_str); - } - sb_append_char(&sb, '}'); - return sb_finish(&sb); - } - case VAL_BUILTIN_FN: return aira_strdup(""); - case VAL_FN: { - snprintf(buf, sizeof(buf), "", v.as.fn->name ? v.as.fn->name : "anonymous"); - return aira_strdup(buf); - } - case VAL_MODULE: { - snprintf(buf, sizeof(buf), "", v.as.module->name); - return aira_strdup(buf); - } - default: return aira_strdup(""); - } -} - -void val_print(AiraValue v) { - char* s = val_to_string(v); - printf("%s", s); - aira_free(s); -} - -AiraValue val_copy(AiraValue v) { - if (v.type == VAL_STRING) { - return val_string(v.as.string); - } - return v; -} - -void val_free(AiraValue* v) { - if (!v) return; - if (v->type == VAL_STRING && v->as.string) { - aira_free(v->as.string); - v->as.string = NULL; - } - v->type = VAL_NULL; -} - -void list_append(AiraList* list, AiraValue v) { - if (list->count >= list->capacity) { - list->capacity *= 2; - list->elements = (AiraValue*)aira_realloc(list->elements, sizeof(AiraValue) * list->capacity); - } - list->elements[list->count++] = v; -} - -AiraValue list_get(AiraList* list, int index) { - if (index < 0) { - index = list->count + index; - } - if (index < 0 || index >= list->count) { - aira_panic("IndexError: List index %d out of bounds (length %d).", index, list->count); - } - return list->elements[index]; -} - -void list_set(AiraList* list, int index, AiraValue v) { - if (index < 0) { - index = list->count + index; - } - if (index < 0 || index >= list->count) { - aira_panic("IndexError: List assignment index %d out of range (length %d).", index, list->count); - } - list->elements[index] = v; -} - -AiraValue list_pop(AiraList* list) { - if (list->count == 0) { - aira_panic("Runtime Error: Cannot pop from empty list."); - } - return list->elements[--list->count]; -} - -void dict_set(AiraDict* dict, const char* key, AiraValue v) { - for (int i = 0; i < dict->count; i++) { - if (strcmp(dict->keys[i], key) == 0) { - dict->values[i] = v; - return; - } - } - if (dict->count >= dict->capacity) { - dict->capacity *= 2; - dict->keys = (char**)aira_realloc(dict->keys, sizeof(char*) * dict->capacity); - dict->values = (AiraValue*)aira_realloc(dict->values, sizeof(AiraValue) * dict->capacity); - } - dict->keys[dict->count] = aira_strdup(key); - dict->values[dict->count] = v; - dict->count++; -} - -AiraValue dict_get(AiraDict* dict, const char* key) { - for (int i = 0; i < dict->count; i++) { - if (strcmp(dict->keys[i], key) == 0) { - return dict->values[i]; - } - } - return val_null(); -} - -bool dict_has(AiraDict* dict, const char* key) { - for (int i = 0; i < dict->count; i++) { - if (strcmp(dict->keys[i], key) == 0) return true; - } - return false; -} diff --git a/s1duo/tests/test_basic.aira b/s1duo/tests/test_basic.aira deleted file mode 100644 index ee6b12b..0000000 --- a/s1duo/tests/test_basic.aira +++ /dev/null @@ -1,61 +0,0 @@ -// ========================================== -// AiraLang S1 Duo β€” Basic Test Suite -// Architect: Adam Eehan -// ========================================== - -say "--- [1] Variable & Math Test ---"; -let a = 15; -let b = 4; -say "a =", a, ", b =", b; -say "a + b =", a + b; -say "a - b =", a - b; -say "a * b =", a * b; -say "a / b =", a / b; -say "a % b =", a % b; - -say "\n--- [2] Control Flow Test ---"; -let score = 92; -if (score >= 90) { - say "Grade: S-Rank Master!"; -} else { - say "Grade: Standard"; -} - -let count = 3; -while (count > 0) { - say "Countdown:", count; - count -= 1; -} - -say "\n--- [3] Function Test ---"; -fn fib(n) { - if (n <= 1) { - return n; - } - return fib(n - 1) + fib(n - 2); -} - -say "fib(10) =", fib(10); - -say "\n--- [4] Data Structures Test ---"; -let list = ["AiraLang", "S1", "Duo"]; -say "List length:", list.length; -for item in list { - say "Item:", item; -} - -let user = {"name": "Adam Eehan", "title": "Founder & CEO"}; -say "Dict access:", user["name"], "-", user["title"]; - -say "\n--- [5] Native Modules Test ---"; -import "math"; -say "Square root of 144 =", math.sqrt(144); -say "PI =", math.pi; - -import "crypto"; -let data = "Aira Group Sovereign Security 2026"; -let hash = crypto.sha256(data); -say "SHA-256 of '" + data + "':"; -say hash; - -say "\n[βœ“] All AiraLang S1 Duo basic tests passed perfectly!"; diff --git a/s1duo/tests/test_benchmark.aira b/s1duo/tests/test_benchmark.aira deleted file mode 100644 index 6df52e3..0000000 --- a/s1duo/tests/test_benchmark.aira +++ /dev/null @@ -1,8 +0,0 @@ -let start = 0; -let total = 0; -let i = 1; -while (i <= 50000) { - total += i; - i += 1; -} -say "Sum of 1 to 50000 =", total; diff --git a/s1duo/tests/test_raw_elf.aira b/s1duo/tests/test_raw_elf.aira deleted file mode 100644 index 8c92004..0000000 --- a/s1duo/tests/test_raw_elf.aira +++ /dev/null @@ -1,3 +0,0 @@ -let a = 100; -let b = 250; -let c = a + b; diff --git a/s1duo/tests/test_security_bounds.aira b/s1duo/tests/test_security_bounds.aira deleted file mode 100644 index 6dfcbbe..0000000 --- a/s1duo/tests/test_security_bounds.aira +++ /dev/null @@ -1,3 +0,0 @@ -let arr = [10, 20, 30]; -say "Accessing out-of-bounds index 999..."; -say arr[999]; diff --git a/s1duo/tests/test_security_recursion.aira b/s1duo/tests/test_security_recursion.aira deleted file mode 100644 index 2649a44..0000000 --- a/s1duo/tests/test_security_recursion.aira +++ /dev/null @@ -1,10 +0,0 @@ -// ========================================== -// AiraLang S1 Duo β€” Security & Defense Test -// ========================================== - -say "--- Testing Recursion Depth Defense ---"; -fn infinite_recursion(n) { - return infinite_recursion(n + 1); -} - -infinite_recursion(1); diff --git a/setup.nsi b/setup.nsi deleted file mode 100644 index c3c1af9..0000000 --- a/setup.nsi +++ /dev/null @@ -1,119 +0,0 @@ -; ============================================================================== -; AiraLang v1.6.0 Official Windows Setup Wizard Script -; Engineered by Adam Eehan (Aira Group of Technology) -; ============================================================================== - -Unicode true -Name "AiraLang v1.6.0 AI-Native (64-bit)" -OutFile "/data/data/com.termux/files/home/airalang-website/downloads/AiraLang-Setup-v1.6.0.exe" -InstallDir "$LOCALAPPDATA\Programs\AiraLang" -InstallDirRegKey HKCU "Software\AiraLang" "Install_Dir" -RequestExecutionLevel user - -SetCompressor /SOLID lzma - -; Pages -Page license -Page components -Page directory -Page instfiles - -UninstPage uninstConfirm -UninstPage instfiles - -LicenseData "LICENSE" -LicenseText "Please review the license terms before installing AiraLang v1.6.0." "I Agree" - -; ============================================================================== -; Sections -; ============================================================================== - -Section "AiraLang Core Engine (required)" SecCore - SectionIn RO - - SetOutPath "$INSTDIR" - File "LICENSE" - File "README.md" - File "welcome.aira" - - SetOutPath "$INSTDIR\src" - File /r "src\*.*" - - SetOutPath "$INSTDIR\bin" - File "bin\airalang.cmd" - File "bin\airalang.bat" - File "bin\airalang.ps1" - - ; Store installation folder - WriteRegStr HKCU "Software\AiraLang" "Install_Dir" "$INSTDIR" - - ; Write Uninstaller - WriteUninstaller "$INSTDIR\uninstall.exe" - - ; Register in Windows Add/Remove Programs (Control Panel) - WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AiraLang" "DisplayName" "AiraLang Programming Language v1.6.0 (AI-Native)" - WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AiraLang" "DisplayVersion" "1.6.0" - WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AiraLang" "Publisher" "Adam Eehan (Aira Group of Technology)" - WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AiraLang" "UninstallString" '"$INSTDIR\uninstall.exe"' - WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AiraLang" "QuietUninstallString" '"$INSTDIR\uninstall.exe" /S' - WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AiraLang" "InstallLocation" "$INSTDIR" - WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AiraLang" "HelpLink" "https://adameehantech.gitlab.io/airalang-website" - WriteRegStr HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AiraLang" "URLInfoAbout" "https://adameehantech.gitlab.io/airalang-website" - WriteRegDWORD HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AiraLang" "NoModify" 1 - WriteRegDWORD HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AiraLang" "NoRepair" 1 -SectionEnd - -Section "Standard Library (25 Modules)" SecModules - SetOutPath "$INSTDIR\modules" - File /r "modules\*.*" -SectionEnd - -Section "Add AiraLang to User PATH" SecPath - ; Read user PATH - ReadRegStr $0 HKCU "Environment" "Path" - StrCmp $0 "" PathEmpty - - ; Append to PATH - WriteRegStr HKCU "Environment" "Path" "$0;$INSTDIR\bin" - Goto PathDone - -PathEmpty: - WriteRegStr HKCU "Environment" "Path" "$INSTDIR\bin" - -PathDone: - ; Broadcast environment change to Windows explorer/terminals - SendMessage 0xffff 0x001A 0 "STR:Environment" /TIMEOUT=5000 -SectionEnd - -Section "Desktop & Start Menu Shortcuts" SecShortcuts - CreateDirectory "$SMPROGRAMS\AiraLang" - CreateShortcut "$SMPROGRAMS\AiraLang\AiraLang REPL.lnk" "$INSTDIR\bin\airalang.cmd" "" "$INSTDIR\bin\airalang.cmd" 0 - CreateShortcut "$SMPROGRAMS\AiraLang\Uninstall AiraLang.lnk" "$INSTDIR\uninstall.exe" "" "$INSTDIR\uninstall.exe" 0 - CreateShortcut "$DESKTOP\AiraLang REPL.lnk" "$INSTDIR\bin\airalang.cmd" "" "$INSTDIR\bin\airalang.cmd" 0 -SectionEnd - -; ============================================================================== -; Uninstaller Section -; ============================================================================== - -Section "Uninstall" - ; Remove shortcuts - Delete "$DESKTOP\AiraLang REPL.lnk" - Delete "$SMPROGRAMS\AiraLang\AiraLang REPL.lnk" - Delete "$SMPROGRAMS\AiraLang\Uninstall AiraLang.lnk" - RMDir "$SMPROGRAMS\AiraLang" - - ; Remove installed files - RMDir /r "$INSTDIR\src" - RMDir /r "$INSTDIR\modules" - RMDir /r "$INSTDIR\bin" - Delete "$INSTDIR\LICENSE" - Delete "$INSTDIR\README.md" - Delete "$INSTDIR\welcome.aira" - Delete "$INSTDIR\uninstall.exe" - RMDir "$INSTDIR" - - ; Remove registry keys - DeleteRegKey HKCU "Software\Microsoft\Windows\CurrentVersion\Uninstall\AiraLang" - DeleteRegKey HKCU "Software\AiraLang" -SectionEnd diff --git a/src/ast_nodes.py b/src/ast_nodes.py deleted file mode 100644 index 5f465b4..0000000 --- a/src/ast_nodes.py +++ /dev/null @@ -1,197 +0,0 @@ -class ASTNode: - pass - -class ProgramNode(ASTNode): - def __init__(self, statements): - self.statements = statements - -class ImportStatementNode(ASTNode): - def __init__(self, module_name, line, source=None, alias=None): - self.module_name = module_name - self.line = line - self.source = source - self.alias = alias - -class AiraAiDirectiveNode(ASTNode): - def __init__(self, prompt, line): - self.prompt = prompt - 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 - -class FunctionExprNode(ASTNode): - def __init__(self, name, params, body, line): - self.name = name - self.params = params - self.body = body - self.line = line - -class NamedArgNode(ASTNode): - def __init__(self, name, value, line): - self.name = name - self.value = value - self.line = line - -class FStringNode(ASTNode): - def __init__(self, parts, line): - self.parts = parts - self.line = line - - diff --git a/src/cli.py b/src/cli.py deleted file mode 100755 index 100fa22..0000000 --- a/src/cli.py +++ /dev/null @@ -1,570 +0,0 @@ -import sys -import os -import time -import json -import threading - -# Cross-platform UTF-8 Console and ANSI Color configuration -if sys.platform == "win32": - try: - sys.stdout.reconfigure(encoding="utf-8", errors="replace") - sys.stderr.reconfigure(encoding="utf-8", errors="replace") - sys.stdin.reconfigure(encoding="utf-8", errors="replace") - import ctypes - kernel32 = ctypes.windll.kernel32 - hStdOut = kernel32.GetStdHandle(-11) - mode = ctypes.c_ulong() - kernel32.GetConsoleMode(hStdOut, ctypes.byref(mode)) - mode.value |= 0x0004 - kernel32.SetConsoleMode(hStdOut, mode) - except Exception: - pass - -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.6.0 (AI-Native Edition)" -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;35m[⚑]\033[0m \033[1;37mModules:\033[0m serve, term, webhook, bot, env, sec, ai, crypto, sqlite - \033[1;36m[πŸ’‘]\033[0m \033[1;37mAI Copilot:\033[0m Type \033[1;36m@aira \033[0m or \033[1;36m?\033[0m in REPL for instant help. - \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): - 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 auto_insert_semicolons_into_file(filepath, lines_to_fix): - if not filepath or not os.path.exists(filepath): - return - try: - with open(filepath, "r", encoding="utf-8") as f: - content = f.readlines() - modified = False - for line_no in lines_to_fix: - idx = line_no - 1 - if 0 <= idx < len(content): - raw_line = content[idx] - newline_char = "\n" if raw_line.endswith("\n") else "" - stripped = raw_line.rstrip("\r\n") - - code_part = stripped - comment_part = "" - for sep in ("//", "#"): - if sep in stripped: - parts = stripped.split(sep, 1) - code_part = parts[0] - comment_part = sep + parts[1] - break - code_stripped = code_part.rstrip() - if code_stripped and not code_stripped.endswith(";"): - code_stripped += ";" - spacing = " " if comment_part else "" - content[idx] = f"{code_stripped}{spacing}{comment_part}{newline_char}" - modified = True - if modified: - with open(filepath, "w", encoding="utf-8") as f: - f.writelines(content) - except Exception: - pass - -def aira_explain_error(error, source_code, filepath=None): - err_str = str(error) - RED = "\033[1;31m" - RESET = "\033[0m" - - print(f"\n{RED}⚠ AiraLang Compiler Error: {err_str}{RESET}") - - explanation = None - try: - import urllib.request, json - from stdlib_modules import AIRALANG_CORE_KNOWLEDGE_BASE - sys_prompt = ( - "You are Aira, sovereign AI engine of AiraLang. " - "A developer encountered an error in their AiraLang code. " - "In 1-2 direct, friendly, and expert sentences in pure English (starting with '⚠ Why this happened: '), " - "explain why this error occurred and tell them exactly how to fix it in AiraLang. " - "Rules: Variables use 'let' (NOT 'var'), output uses 'say' (NOT 'print'). " - "Knowledge Base: " + AIRALANG_CORE_KNOWLEDGE_BASE[:1000] - ) - req_data = json.dumps({ - "model": "aira-3-flash", - "messages": [ - {"role": "system", "content": sys_prompt}, - {"role": "user", "content": f"Source:\n{source_code[:1000]}\n\nError:\n{err_str}"} - ], - "max_tokens": 120 - }).encode("utf-8") - req = urllib.request.Request("http://127.0.0.1:8080/v1/chat/completions", data=req_data, headers={"Content-Type": "application/json"}) - with urllib.request.urlopen(req, timeout=1.8) as resp: - data = json.loads(resp.read().decode("utf-8")) - explanation = data["choices"][0]["message"]["content"].strip() - except Exception: - pass - - if not explanation: - if "is not defined" in err_str: - var_name = err_str.split("'")[1] if "'" in err_str else "variable" - explanation = f"⚠ Why this happened: '{var_name}' was referenced before declaration. In AiraLang, declare it first with 'let {var_name} = ...;'." - elif "Missing block brace" in err_str or "Expected 'LBRACE'" in err_str: - explanation = "⚠ Why this happened: Control blocks (if, while, for) require braces '{ }' in AiraLang." - elif "var " in source_code: - explanation = "⚠ Why this happened: 'var' keyword is not recognized. In AiraLang, use 'let' to declare variables." - elif "print(" in source_code: - explanation = "⚠ Why this happened: 'print()' function is not recognized. In AiraLang, use 'say \"output\";'." - else: - explanation = "⚠ Why this happened: Syntax or runtime mismatch detected. Check statement syntax and variable scope." - - if not explanation.startswith("⚠"): - explanation = f"⚠ {explanation}" - print(f"{RED}{explanation}{RESET}\n") - -def run_code(source_code, evaluator=None, filepath=None): - if evaluator is None: - evaluator = Evaluator() - try: - lexer = Lexer(source_code) - tokens = lexer.tokenize() - parser = Parser(tokens) - ast = parser.parse() - if filepath and parser.missing_semicolon_lines: - auto_insert_semicolons_into_file(filepath, parser.missing_semicolon_lines) - return evaluator.eval(ast) - except SyntaxError as e: - aira_explain_error(e, source_code, filepath) - except NameError as e: - aira_explain_error(e, source_code, filepath) - except TypeError as e: - aira_explain_error(e, source_code, filepath) - except Exception as e: - aira_explain_error(e, source_code, filepath) - -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) - try: - from stdlib_modules import check_and_prompt_ai_engine - check_and_prompt_ai_engine() - except Exception: - pass - with open(filepath, "r", encoding="utf-8") as f: - code = f.read() - run_code(code, filepath=filepath) - -def start_repl(): - print(ASCII_BANNER) - try: - from stdlib_modules import check_and_prompt_ai_engine - check_and_prompt_ai_engine() - except Exception: - pass - 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) - clean_cmd = line.strip() - - if not buffer and (clean_cmd.startswith("@aira") or clean_cmd.startswith("@airaai") or clean_cmd.startswith("?")): - query = clean_cmd - if clean_cmd.startswith("@airaai"): - query = clean_cmd[7:].strip() - elif clean_cmd.startswith("@aira"): - query = clean_cmd[5:].strip() - elif clean_cmd.startswith("?"): - query = clean_cmd[1:].strip() - - print(f"\033[1;36m[Aira Copilot]:\033[0m Thinking...") - reply = None - try: - import urllib.request, json - from stdlib_modules import AIRALANG_CORE_KNOWLEDGE_BASE - sys_prompt = ( - "You are Aira, sovereign pair programmer and REPL copilot for AiraLang. " - "Answer the developer's question directly with concise, correct AiraLang code examples in pure English. " - "Rules: Use 'let' for variables (NOT 'var'), 'say' for output (NOT 'print'). " - "AiraLang Knowledge Base: " + AIRALANG_CORE_KNOWLEDGE_BASE[:1500] - ) - req_data = json.dumps({ - "model": "aira-3-flash", - "messages": [ - {"role": "system", "content": sys_prompt}, - {"role": "user", "content": query} - ], - "max_tokens": 200 - }).encode("utf-8") - req = urllib.request.Request("http://127.0.0.1:8080/v1/chat/completions", data=req_data, headers={"Content-Type": "application/json"}) - with urllib.request.urlopen(req, timeout=3.0) as resp: - data = json.loads(resp.read().decode("utf-8")) - reply = data["choices"][0]["message"]["content"].strip() - except Exception: - pass - - if not reply: - reply = "Use 'let x = 10;' for variables, 'say x;' for output, and 'import ;' for standard library modules." - - print(f"\033[1;32mβœ” Aira:\033[0m {reply}\n") - continue - - 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 build_file(source_path, output_path=None): - if not os.path.exists(source_path): - print(f"\033[1;31m[!] Error: File '{source_path}' not found.\033[0m") - sys.exit(1) - if output_path is None: - output_path = os.path.splitext(source_path)[0] - with open(source_path, "r", encoding="utf-8") as f: - aira_code = f.read() - - runner_script = f"""#!/data/data/com.termux/files/usr/bin/python3 -# ========================================== -# Standalone Binary Executable -# Generated by AiraLang v{VERSION} -# Author: {AUTHOR} -# ========================================== -import sys, os -AIRA_SRC = "/data/data/com.termux/files/home/airalang/src" -if AIRA_SRC not in sys.path: - sys.path.insert(0, AIRA_SRC) -from cli import run_code -CODE = {repr(aira_code)} -if __name__ == '__main__': - run_code(CODE) -""" - with open(output_path, "w", encoding="utf-8") as f: - f.write(runner_script) - os.chmod(output_path, 0o755) - print(f"\033[1;32m[+] Successfully built executable binary:\033[0m {output_path}") - print(f"\033[1;34m[*] Run it directly:\033[0m ./{output_path}") - -def new_project(proj_name): - if os.path.exists(proj_name): - print(f"\033[1;31m[!] Error: Directory '{proj_name}' already exists.\033[0m") - return - os.makedirs(proj_name, exist_ok=True) - main_code = f"""# πŸš€ Welcome to {proj_name}! -# Powered by AiraLang v{VERSION} -# Creator: {AUTHOR} - -import "ai"; -import "sec"; - -say "πŸ”₯ Welcome to {proj_name} powered by AiraLang!"; -let creator = "{AUTHOR}"; -say "⚑ Built by: " + creator; -""" - with open(os.path.join(proj_name, "main.aira"), "w", encoding="utf-8") as f: - f.write(main_code) - with open(os.path.join(proj_name, "README.md"), "w", encoding="utf-8") as f: - f.write(f"# {proj_name}\\n\\nProject created with AiraLang v{VERSION}.\\n\\nRun:\\n```bash\\nairalang main.aira\\n```\\n") - print(f"\033[1;32m[+] Created new AiraLang project:\033[0m {proj_name}/") -def revoke_ai_api_key(): - from stdlib_modules import load_airalang_config, save_airalang_config, _GLOBAL_AI_STATE, prompt_developer_for_ai_key - - CYAN = "\033[1;36m" - YELLOW = "\033[1;33m" - GREEN = "\033[1;32m" - RED = "\033[1;31m" - RESET = "\033[0m" - BOLD = "\033[1m" - - cfg = load_airalang_config() - old_provider = cfg.get("active_provider", "none") - - cfg["keys"] = {} - cfg["active_provider"] = "gemini" - cfg["ai_prompted"] = False - save_airalang_config(cfg) - - for k in _GLOBAL_AI_STATE["keys"]: - if k != "ollama": - _GLOBAL_AI_STATE["keys"][k] = "" - _GLOBAL_AI_STATE["active_provider"] = "gemini" - _GLOBAL_AI_STATE["gemini_key"] = "" - _GLOBAL_AI_STATE["groq_key"] = "" - _GLOBAL_AI_STATE["custom_key"] = "" - - print(f"\n{RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{RESET}") - print(f"{RED}{BOLD}πŸ”„ [Aira AI Engine - Key Revoked]:{RESET}") - print(f"{YELLOW}Previous API key(s) (active: {old_provider}) have been revoked and cleared.{RESET}") - print(f"{CYAN}Rate limit reset! You can now configure a fresh API key.{RESET}") - print(f"{RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{RESET}") - - prompt_developer_for_ai_key() - -class AiraSpinner: - def __init__(self, message="Processing..."): - self.message = message - self.stop_running = False - self.thread = None - self.frames = ["β’Ώ", "β£»", "β£½", "β£Ύ", "β£·", "β£―", "⣟", "β‘Ώ"] - - def _spin(self): - i = 0 - while not self.stop_running: - f = self.frames[i % len(self.frames)] - sys.stdout.write(f"\r\033[1;36m {f}\033[0m {self.message}") - sys.stdout.flush() - time.sleep(0.08) - i += 1 - - def __enter__(self): - self.stop_running = False - self.thread = threading.Thread(target=self._spin, daemon=True) - self.thread.start() - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - self.stop_running = True - if self.thread: - self.thread.join(timeout=0.3) - sys.stdout.write("\r\033[K") - sys.stdout.flush() - -def install_package(pkg_name): - pkg_name = pkg_name.lower().strip() - print(f"\033[1;36m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m") - print(f"\033[1;35mπŸ“¦ [Aira Package Manager (APM v1.0)]\033[0m") - print(f"\033[1;36m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m") - - with AiraSpinner(f"Resolving package '{pkg_name}' from Aira Package Registry..."): - time.sleep(0.8) - print(f" \033[1;32m[βœ“]\033[0m Package \033[1;33m{pkg_name}\033[0m resolved successfully.") - - if pkg_name in ("youtube", "yt"): - with AiraSpinner("Verifying engine dependencies (yt-dlp)..."): - import subprocess - try: - import yt_dlp - engine_ready = True - except ImportError: - engine_ready = False - time.sleep(0.4) - - if engine_ready: - print(" \033[1;32m[βœ“]\033[0m Backend engine yt-dlp is ready.") - else: - with AiraSpinner("Installing yt-dlp backend engine via pip..."): - subprocess.check_call([sys.executable, "-m", "pip", "install", "yt-dlp"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - print(" \033[1;32m[βœ“]\033[0m Backend engine installed successfully.") - - with AiraSpinner("Configuring package registry and setting up permissions..."): - config_dir = os.path.expanduser("~/.config/airalang") - os.makedirs(config_dir, exist_ok=True) - packages_file = os.path.join(config_dir, "installed_packages.json") - packages = {} - if os.path.exists(packages_file): - try: - with open(packages_file, "r", encoding="utf-8") as f: - packages = json.load(f) - except Exception: - packages = {} - packages["youtube"] = { - "version": "1.0.0", - "installed_at": time.time(), - "description": "YouTube video and audio download engine for AiraLang" - } - packages["yt"] = packages["youtube"] - with open(packages_file, "w", encoding="utf-8") as f: - json.dump(packages, f, indent=2) - time.sleep(0.5) - - print(f" \033[1;32m[βœ“]\033[0m Module '{pkg_name}' registered in APM.") - print(f"\n\033[1;32m✨ Successfully installed '{pkg_name}' v1.0.0!\033[0m") - print(f"\033[1;36mπŸ’‘ Usage in your .aira scripts:\033[0m") - print(f" import \"youtube\";") - print(f" let video = youtube.get(url);") - print(f" let stream = video.stream(\"mp4\");") - print(f" let save = os.save(\"video.mp4\");") - print(f" stream.download(save);") - print(f"\033[1;36m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\033[0m") - else: - print(f" \033[1;31m[βœ—]\033[0m Package '{pkg_name}' not found in Aira Package Registry.") - print(f"Available packages: youtube (yt)") - -def print_help(): - print(f"""\033[1;36mAiraLang v{VERSION}\033[0m -Creator: {AUTHOR} - -\033[1;33mUsage:\033[0m - airalang Start interactive REPL - airalang Execute an AiraLang script - airalang run Execute an AiraLang script - airalang install Install a module via Aira Package Manager (APM) - aira install Install a module via Aira Package Manager (APM) - airalang build [-o out] Compile script to standalone executable - airalang new Create a new AiraLang project scaffold - airalang --ai api revoke Revoke active API key and configure a fresh one - airalang --ai-setup Configure Aira AI Engine API key (interactive) - airalang --set-key [provider] Set API key for provider (OpenRouter/Groq/OpenAI/Gemini) - airalang -v, --version Display version information - airalang -h, --help Show this help message -""") - -def main(): - if len(sys.argv) > 1: - args_str = " ".join(sys.argv[1:]).lower().strip() - if args_str in ( - "--ai api revoke", - "ai api revoke", - "--ai revoke", - "ai revoke", - "--revoke-api", - "--ai-revoke", - "revoke-api" - ): - revoke_ai_api_key() - sys.exit(0) - - arg1 = sys.argv[1] - if arg1 in ("-v", "--version"): - print(f"AiraLang v{VERSION} | Creator: {AUTHOR}") - elif arg1 in ("-h", "--help"): - print_help() - elif arg1 in ("install", "i", "add"): - if len(sys.argv) > 2: - install_package(sys.argv[2]) - sys.exit(0) - else: - print("\033[1;31m[!] Error: Specify package name: airalang install \033[0m") - sys.exit(1) - elif arg1 in ("--ai-setup", "--setup-ai"): - from stdlib_modules import prompt_developer_for_ai_key - prompt_developer_for_ai_key() - sys.exit(0) - elif arg1 == "--set-key": - if len(sys.argv) > 2: - from stdlib_modules import create_ai_module - ai_mod = create_ai_module() - prov = sys.argv[3] if len(sys.argv) > 3 else None - ai_mod.methods["set_key"](sys.argv[2], provider=prov) - print(f"\033[1;32mβœ“ API Key successfully configured and saved to config!\033[0m") - sys.exit(0) - else: - print("\033[1;31m[!] Error: Specify API key: airalang --set-key [provider]\033[0m") - sys.exit(1) - elif arg1 == "run": - if len(sys.argv) > 2: - run_file(sys.argv[2]) - else: - print("\033[1;31m[!] Error: Specify file to run: airalang run \033[0m") - elif arg1 == "build": - if len(sys.argv) > 2: - src_file = sys.argv[2] - out_file = None - if "-o" in sys.argv: - idx = sys.argv.index("-o") - if idx + 1 < len(sys.argv): - out_file = sys.argv[idx + 1] - build_file(src_file, out_file) - else: - print("\033[1;31m[!] Error: Specify file to build: airalang build [-o ]\033[0m") - elif arg1 == "new": - if len(sys.argv) > 2: - new_project(sys.argv[2]) - else: - print("\033[1;31m[!] Error: Specify project name: airalang new \033[0m") - else: - run_file(arg1) - else: - start_repl() - -if __name__ == "__main__": - main() diff --git a/src/evaluator.py b/src/evaluator.py deleted file mode 100644 index 3839304..0000000 --- a/src/evaluator.py +++ /dev/null @@ -1,636 +0,0 @@ -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, *args): - return self.call(Evaluator._current_evaluator, list(args)) - - def call(self, evaluator, args, kwargs=None, 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) - if kwargs: - for k, v in kwargs.items(): - fn_env.set(k, v) - 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, kwargs=None): - instance = AiraInstance(self) - if "init" in self.methods: - init_fn = AiraFunction(self.methods["init"], self.closure_env) - init_fn.call(evaluator, args, kwargs=kwargs, this_instance=instance) - elif "__init__" in self.methods: - init_fn = AiraFunction(self.methods["__init__"], self.closure_env) - init_fn.call(evaluator, args, kwargs=kwargs, 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("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)) - 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))) - self.global_env.set("sorted", lambda lst, reverse=False: sorted(lst, reverse=bool(reverse))) - self.global_env.set("reversed", lambda lst: list(reversed(lst))) - self.global_env.set("enumerate", lambda lst: [[i, v] for i, v in enumerate(lst)]) - self.global_env.set("zip", lambda *lsts: [list(items) for items in zip(*lsts)]) - - 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 - source = getattr(node, "source", None) - alias = getattr(node, "alias", None) - clean_mod = str(mod_name).strip('"').strip("'") - bind_name = alias or clean_mod - - # Check for `from ` - if source: - clean_src = str(source).strip('"').strip("'") - if clean_src in ("airaai", "ai") or clean_mod in ("ai", "airaai"): - mod_func = BUILTIN_MODULES.get("ai") or BUILTIN_MODULES.get("airaai") - module_instance = mod_func() - env.set(bind_name, module_instance) - return module_instance - - if clean_src in BUILTIN_MODULES: - parent_mod = BUILTIN_MODULES[clean_src]() - if hasattr(parent_mod, "fields") and clean_mod in parent_mod.fields: - val = parent_mod.fields[clean_mod] - env.set(bind_name, val) - return val - env.set(bind_name, parent_mod) - return parent_mod - - # Check file import from source - target_path = clean_src - if not os.path.exists(target_path) and not target_path.endswith(".aira"): - target_path = clean_src + ".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 - 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) - if clean_mod in mod_env.values: - val = mod_env.values[clean_mod] - env.set(bind_name, val) - return val - base_name = os.path.splitext(os.path.basename(target_path))[0] - aira_mod = AiraModule(base_name, mod_env.values) - env.set(bind_name, aira_mod) - return aira_mod - - if clean_mod in BUILTIN_MODULES: - module_instance = BUILTIN_MODULES[clean_mod]() - env.set(bind_name, module_instance) - return module_instance - - # File import check (.aira or .py) - target_path = clean_mod - if not os.path.exists(target_path) and not target_path.endswith(".aira"): - target_path = clean_mod + ".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 - 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(target_path))[0] - aira_mod = AiraModule(base_name, mod_env.values) - env.set(bind_name, aira_mod) - return aira_mod - else: - raise ImportError(f"AiraLang ImportError: Module or file '{clean_mod}' not found (Line {node.line})") - - elif nodetype == "AiraAiDirectiveNode": - prompt = str(node.prompt).strip() - RED = "\033[1;31m" - GREEN = "\033[1;32m" - RESET = "\033[0m" - - is_error_check = not prompt or any(w in prompt.lower() for w in ("error", "mistake", "issue", "bug", "check", "wrong")) - - result = None - try: - import urllib.request, json - from stdlib_modules import AIRALANG_CORE_KNOWLEDGE_BASE - sys_prompt = ( - "You are Aira, the sovereign AI built into AiraLang. " - "Analyze the user's code/request according to AiraLang specification: " - + AIRALANG_CORE_KNOWLEDGE_BASE[:1500] + "\n" - "If the user asks for error checking and there are genuine mistakes/bugs in the code, " - "explain in 1-2 pure English sentences what the issue is and how you suggest fixing it, prefixed with '⚠ '. " - "If there are NO mistakes or bugs, strictly reply: 'βœ” Code is perfectly alright!' " - "If it is a general question or request, give a direct, expert, helpful answer in pure English." - ) - req_data = json.dumps({ - "model": "aira-3-flash", - "messages": [ - {"role": "system", "content": sys_prompt}, - {"role": "user", "content": f"Directive prompt: {prompt or 'any errors?'}\nCurrent scope variables: {list(env.values.keys())}"} - ], - "max_tokens": 120 - }).encode("utf-8") - req = urllib.request.Request("http://127.0.0.1:8080/v1/chat/completions", data=req_data, headers={"Content-Type": "application/json"}) - with urllib.request.urlopen(req, timeout=2.0) as resp: - data = json.loads(resp.read().decode("utf-8")) - result = data["choices"][0]["message"]["content"].strip() - except Exception: - pass - - if not result: - if is_error_check: - result = "βœ” Code is perfectly alright! Syntax and runtime environment verified." - else: - result = f"Aira Co-Pilot: Verified directive '{prompt}'. Context active." - - if "error" in result.lower() or "issue" in result.lower() or "mistake" in result.lower() or "⚠" in result: - if not result.startswith("⚠"): - result = f"⚠ {result}" - print(f"{RED}{result}{RESET}") - elif "alright" in result.lower() or "clean" in result.lower() or "perfect" in result.lower() or "βœ”" in result: - if not result.startswith("βœ”"): - result = f"βœ” {result}" - print(f"{GREEN}{result}{RESET}") - else: - print(f"{GREEN}{result}{RESET}") - return result - - 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 = [] - kwargs = {} - for arg in node.arguments: - if getattr(arg, "__class__", None).__name__ == "NamedArgNode": - kwargs[arg.name] = self.eval_node(arg.value, env) - else: - args.append(self.eval_node(arg, env)) - if isinstance(cls, AiraClass): - return cls.instantiate(self, args, kwargs=kwargs) - 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 == "FunctionExprNode": - fn = AiraFunction(node, env) - if node.name: - 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 == "FStringNode": - result_pieces = [] - for is_expr, item in node.parts: - if is_expr: - val = self.eval_node(item, env) - result_pieces.append(str(val) if val is not None else "null") - else: - result_pieces.append(item) - return "".join(result_pieces) - - - 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 == "items": return lambda: [[k, v] for k, v in target.items()] - if member == "get": return lambda k, default=None: target.get(k, default) - 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 == "title": return lambda: target.title() - 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] - if member == "reverse": return lambda: target[::-1] - if member == "count": return lambda sub: target.count(str(sub)) - - # 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: list(reversed(target)) - if member == "sort": return lambda reverse=False: sorted(target, reverse=bool(reverse)) - if member == "slice": return lambda start, end=None: target[int(start):int(end) if end is not None else None] - if member == "count": return lambda x: target.count(x) - if member == "indexOf" or member == "find_index": return lambda x: target.index(x) if x in target else -1 - if member == "map": - def _map(fn): - res = [] - for x in target: - val = fn.call(self, [x]) if isinstance(fn, AiraFunction) else fn(x) - res.append(val) - return res - return _map - if member == "filter": - def _filter(fn): - res = [] - for x in target: - val = fn.call(self, [x]) if isinstance(fn, AiraFunction) else fn(x) - if val: - res.append(x) - return res - return _filter - if member == "find": - def _find(fn): - for x in target: - val = fn.call(self, [x]) if isinstance(fn, AiraFunction) else fn(x) - if val: - return x - return None - return _find - if member == "each" or member == "forEach": - def _each(fn): - for x in target: - if isinstance(fn, AiraFunction): - fn.call(self, [x]) - else: - fn(x) - return target - return _each - if member == "reduce": - def _reduce(fn, initial=None): - items = list(target) - if initial is None: - if not items: - raise ValueError("reduce on empty list with no initial value") - accum = items[0] - items = items[1:] - else: - accum = initial - for x in items: - if isinstance(fn, AiraFunction): - accum = fn.call(self, [accum, x]) - else: - accum = fn(accum, x) - return accum - return _reduce - - 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 in ("!=", "β‰ "): 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 = [] - kwargs = {} - for arg in node.arguments: - if getattr(arg, "__class__", None).__name__ == "NamedArgNode": - kwargs[arg.name] = self.eval_node(arg.value, env) - else: - args.append(self.eval_node(arg, env)) - - if isinstance(callee, AiraFunction): - return callee.call(self, args, kwargs=kwargs) - elif isinstance(callee, AiraClass): - return callee.instantiate(self, args, kwargs=kwargs) - elif callable(callee): - if kwargs: - return callee(*args, **kwargs) - 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 deleted file mode 100644 index e7cea00..0000000 --- a/src/lexer.py +++ /dev/null @@ -1,103 +0,0 @@ -import re - -TOKEN_TYPES = [ - ("COMMENT", r"(#|//).*"), - ("WHITESPACE", r"[ \t\r\n]+"), - ("NUMBER", r"\d+(\.\d+)?"), - ("FSTRING", r'f("([^"\\]|\\.)*"|\'([^\'\\]|\\.)*\')'), - ("STRING", r'("([^"\\]|\\.)*"|\'([^\'\\]|\\.)*\')'), - ("KEYWORD", r"\b(let|say|print|if|else|while|for|in|fn|return|import|from|load|use|true|false|null|and|or|not|try|catch|throw|class|new|this|break|continue)\b"), - ("AT", r"@"), - ("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: - 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 == "FSTRING": - raw_str = val[2:-1].encode('utf-8').decode('unicode_escape') - self.tokens.append(Token("FSTRING", raw_str, self.line, self.col)) - 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 deleted file mode 100644 index 496962d..0000000 --- a/src/parser.py +++ /dev/null @@ -1,580 +0,0 @@ -import sys -from ast_nodes import * - -class Parser: - def __init__(self, tokens): - self.tokens = tokens - self.pos = 0 - self.missing_semicolon_lines = [] - - 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 consume_semicolon(self, line=None): - if self.match("SEMICOLON"): - return - if line is None: - line = self.tokens[self.pos - 1].line if self.pos > 0 else self.current().line - self.missing_semicolon_lines.append(line) - - def parse_block(self): - self.expect("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) - - def parse(self): - statements = [] - while self.current().type != "EOF": - stmt = self.parse_statement() - if stmt: - statements.append(stmt) - - if self.missing_semicolon_lines and not getattr(self, "suppress_semicolon_notice", False): - unique_lines = sorted(set(self.missing_semicolon_lines)) - lines_str = ", ".join(str(l) for l in unique_lines) - - RED = "\033[1;31m" - RESET = "\033[0m" - - single_notice = None - try: - import urllib.request, json - req_data = json.dumps({ - "model": "aira-3-flash", - "messages": [ - {"role": "system", "content": f"You are Aira, a sovereign pair programmer co-pilot. In exactly 1 casual, developer-to-developer sentence in pure English (NO emojis, NO stickers, starting with '⚠ '), tell the user that they missed a semicolon at line {lines_str} and that you have automatically fixed it for them."}, - {"role": "user", "content": "Semicolon missed"} - ], - "max_tokens": 40 - }).encode("utf-8") - req = urllib.request.Request("http://127.0.0.1:8080/v1/chat/completions", data=req_data, headers={"Content-Type": "application/json"}) - with urllib.request.urlopen(req, timeout=1.2) as resp: - data = json.loads(resp.read().decode("utf-8")) - msg = data["choices"][0]["message"]["content"].strip().strip('"').strip("'") - if msg: - if not msg.startswith("⚠"): - msg = f"⚠ {msg}" - single_notice = f"\n{RED}{msg}{RESET}\n" - except Exception: - pass - - if not single_notice: - single_notice = f"\n{RED}⚠ Airalang automated bots detected your missed semicolon at line {lines_str}. We have automatically fixed it.{RESET}\n" - - sys.stderr.write(single_notice) - sys.stderr.flush() - - 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() - - # In-code @airaai directive: `@airaai "prompt"`, `@airaai/"prompt"` - if tok.type == "AT": - peek_tok = self.peek(1) - if peek_tok.type == "IDENTIFIER" and peek_tok.value in ("airaai", "aira"): - self.pos += 2 # consume '@' and 'airaai' - if self.match("DIV"): - pass - prompt_text = "" - if self.current().type in ("STRING", "FSTRING"): - prompt_text = str(self.current().value) - self.pos += 1 - else: - tokens_text = [] - while self.current().type not in ("SEMICOLON", "EOF") and self.current().line == tok.line: - tokens_text.append(str(self.current().value)) - self.pos += 1 - prompt_text = " ".join(tokens_text).strip() - self.consume_semicolon(tok.line) - return AiraAiDirectiveNode(prompt_text, tok.line) - - # import / load / use statement: `import "ai" from "airaai";`, `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}") - - source_pkg = None - alias = None - # Check for `from ` - if self.current().type in ("FROM", "IDENTIFIER") and self.current().value == "from": - self.pos += 1 - if self.current().type in ("STRING", "IDENTIFIER"): - source_pkg = str(self.current().value) - self.pos += 1 - else: - curr = self.current() - raise SyntaxError(f"AiraLang SyntaxError: Expected package name after 'from' at line {curr.line}, col {curr.col}") - - # Check for `as ` - if self.current().type == "IDENTIFIER" and self.current().value == "as": - self.pos += 1 - if self.current().type == "IDENTIFIER": - alias = str(self.current().value) - self.pos += 1 - - self.consume_semicolon(tok.line) - return ImportStatementNode(str(mod_tok.value), tok.line, source=source_pkg, alias=alias) - - # 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.consume_semicolon(tok.line) - 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.consume_semicolon(tok.line) - return LetStatementNode(name_tok.value, expr, tok.line) - - # if statement: `if (cond) { ... } else if (cond2) { ... } else { ... }` - if tok.type == "IF": - self.pos += 1 - has_paren = self.match("LPAREN") - cond = self.parse_expression() - if has_paren: - self.expect("RPAREN") - if self.current().type != "LBRACE": - curr = self.current() - raise SyntaxError(f"AiraLang SyntaxError: Missing block brace '{{' for if-statement at line {tok.line}. Block braces '{{}}' are mandatory in AiraLang! Found '{curr.value or curr.type}' instead.") - then_branch = self.parse_block() - else_branch = None - if self.match("ELSE"): - if self.current().type == "IF": - else_branch = self.parse_statement() - else: - if self.current().type != "LBRACE": - curr = self.current() - raise SyntaxError(f"AiraLang SyntaxError: Missing block brace '{{' for else-block at line {self.tokens[self.pos - 1].line}. Block braces '{{}}' are mandatory in AiraLang! Found '{curr.value or curr.type}' instead.") - else_branch = self.parse_block() - 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") - if self.current().type != "LBRACE": - curr = self.current() - raise SyntaxError(f"AiraLang SyntaxError: Missing block brace '{{' for while loop at line {tok.line}. Block braces '{{}}' are mandatory in AiraLang! Found '{curr.value or curr.type}' instead.") - body = self.parse_block() - return WhileStatementNode(cond, body, tok.line) - - # for statement: `for 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") - if self.current().type != "LBRACE": - curr = self.current() - raise SyntaxError(f"AiraLang SyntaxError: Missing block brace '{{' for for-loop at line {tok.line}. Block braces '{{}}' are mandatory in AiraLang! Found '{curr.value or curr.type}' instead.") - body = self.parse_block() - return ForInStatementNode(var_tok.value, iterable, body, tok.line) - - # try / catch statement: `try { ... } catch (err) { ... }` - if tok.type == "TRY": - self.pos += 1 - if self.current().type != "LBRACE": - curr = self.current() - raise SyntaxError(f"AiraLang SyntaxError: Missing block brace '{{' for try block at line {tok.line}. Block braces '{{}}' are mandatory in AiraLang! Found '{curr.value or curr.type}' instead.") - try_body = self.parse_block() - 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") - if self.current().type != "LBRACE": - curr = self.current() - raise SyntaxError(f"AiraLang SyntaxError: Missing block brace '{{' for catch block at line {tok.line}. Block braces '{{}}' are mandatory in AiraLang! Found '{curr.value or curr.type}' instead.") - catch_body = self.parse_block() - 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.consume_semicolon(tok.line) - return ThrowStatementNode(expr, tok.line) - - # break statement: `break;` - if tok.type == "BREAK": - self.pos += 1 - self.consume_semicolon(tok.line) - return BreakStatementNode(tok.line) - - # continue statement: `continue;` - if tok.type == "CONTINUE": - self.pos += 1 - self.consume_semicolon(tok.line) - 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") - if self.current().type != "LBRACE": - curr = self.current() - raise SyntaxError(f"AiraLang SyntaxError: Missing block brace '{{' for function '{name_tok.value}' at line {tok.line}. Block braces '{{}}' are mandatory in AiraLang! Found '{curr.value or curr.type}' instead.") - body = self.parse_block() - 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") - if self.current().type != "LBRACE": - curr = self.current() - raise SyntaxError(f"AiraLang SyntaxError: Missing block brace '{{' for class '{name_tok.value}' at line {tok.line}. Block braces '{{}}' are mandatory in AiraLang! Found '{curr.value or curr.type}' instead.") - self.expect("LBRACE") - methods = {} - while self.current().type != "RBRACE" and self.current().type != "EOF": - if self.match("FN") or self.current().type == "IDENTIFIER": - 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") - if self.current().type != "LBRACE": - curr = self.current() - raise SyntaxError(f"AiraLang SyntaxError: Missing block brace '{{' for method '{m_name_tok.value}' in class '{name_tok.value}' at line {m_name_tok.line}. Block braces '{{}}' are mandatory in AiraLang!") - m_body = self.parse_block() - 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.consume_semicolon(tok.line) - return ReturnStatementNode(expr, tok.line) - - # expression / assignment / shorthand assignment statement - expr = self.parse_expression() - assign_op = self.match("ASSIGN", "PLUS_ASSIGN", "MINUS_ASSIGN", "MUL_ASSIGN", "DIV_ASSIGN", "MOD_ASSIGN") - if assign_op: - val_expr = self.parse_expression() - self.consume_semicolon(tok.line) - - 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): - 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.consume_semicolon(tok.line) - 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_call_arg(self): - if self.current().type == "IDENTIFIER" and self.peek().type == "ASSIGN": - name_tok = self.expect("IDENTIFIER") - self.expect("ASSIGN") - val_expr = self.parse_expression() - return NamedArgNode(name_tok.value, val_expr, name_tok.line) - return self.parse_expression() - - def parse_postfix(self): - atom = self.parse_atom() - while True: - if self.match("LPAREN"): - args = [] - if self.current().type != "RPAREN": - args.append(self.parse_call_arg()) - while self.match("COMMA"): - args.append(self.parse_call_arg()) - 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_fstring(self, tok): - from lexer import Lexer - raw_str = tok.value - line = tok.line - parts = [] - i = 0 - n = len(raw_str) - cur_text = [] - while i < n: - if raw_str[i] == '{': - if i + 1 < n and raw_str[i+1] == '{': - cur_text.append('{') - i += 2 - continue - if cur_text: - parts.append((False, "".join(cur_text))) - cur_text = [] - i += 1 - start = i - brace_count = 1 - while i < n and brace_count > 0: - if raw_str[i] == '{': - brace_count += 1 - elif raw_str[i] == '}': - brace_count -= 1 - i += 1 - if brace_count > 0: - raise SyntaxError(f"AiraLang SyntaxError: Unclosed '{{' in f-string at line {line}") - expr_str = raw_str[start:i-1].strip() - if expr_str: - sub_tokens = Lexer(expr_str).tokenize() - sub_parser = Parser(sub_tokens) - expr_ast = sub_parser.parse_expression() - parts.append((True, expr_ast)) - elif raw_str[i] == '}': - if i + 1 < n and raw_str[i+1] == '}': - cur_text.append('}') - i += 2 - continue - cur_text.append('}') - i += 1 - else: - cur_text.append(raw_str[i]) - i += 1 - if cur_text: - parts.append((False, "".join(cur_text))) - return FStringNode(parts, line) - - 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("FSTRING"): - return self.parse_fstring(tok) - - 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_call_arg()) - while self.match("COMMA"): - args.append(self.parse_call_arg()) - 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) - if self.match("FN"): - fn_name = None - if self.current().type == "IDENTIFIER": - fn_name = self.expect("IDENTIFIER").value - 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 FunctionExprNode(fn_name, params, body, 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 deleted file mode 100644 index 7c8c7ba..0000000 --- a/src/stdlib_modules.py +++ /dev/null @@ -1,2381 +0,0 @@ -import os -import sys -import math -import time -import json -import random -import hashlib -import base64 -import socket -import sqlite3 -import urllib.request -import urllib.parse -import urllib.error -import threading -import struct -import zipfile -import re -import subprocess -import ssl -import hmac -import uuid -import datetime -from concurrent.futures import ThreadPoolExecutor - -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}'") - -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: - 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 - - def save_path(filepath): - path_str = str(filepath).strip() - dir_name = os.path.dirname(path_str) - if dir_name: - os.makedirs(dir_name, exist_ok=True) - return path_str - - return AiraModule("file", { - "read": read_file, - "write": write_file, - "append": append_file, - "exists": exists, - "delete": delete, - "size": size, - "save": save_path - }) - -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 - - def save_path(filepath): - path_str = str(filepath).strip() - dir_name = os.path.dirname(path_str) - if dir_name: - os.makedirs(dir_name, exist_ok=True) - return path_str - - def get_args(): - if len(sys.argv) > 1: - raw = sys.argv[1:] - while raw and raw[0] in ("run", "build", "new", "-v", "--version", "-h", "--help"): - raw = raw[1:] - if raw and (raw[0].endswith(".aira") or raw[0].endswith(".py") or "airalang" in raw[0] or "cli.py" in raw[0]): - raw = raw[1:] - return raw - return [] - - def exit_app(code=0): - sys.exit(int(code)) - - return AiraModule("os", { - "cmd": cmd, - "system": cmd, - "env": env, - "getenv": env, - "platform": platform, - "cwd": cwd, - "getcwd": cwd, - "listdir": listdir, - "mkdir": mkdir, - "save": save_path, - "args": get_args, - "argv": get_args, - "exit": exit_app, - "is_windows": lambda: sys.platform == "win32", - "is_android": lambda: "android" in sys.platform.lower() or os.path.exists("/data/data/com.termux"), - "is_linux": lambda: sys.platform.startswith("linux") and not os.path.exists("/data/data/com.termux") - }) - -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), - "mkstring": lambda obj, indent=2: json.dumps(obj, indent=indent), - "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.3 (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.3 (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.3"}) - 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.3"}) - 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') - - def hmac_sha256(key, message): - return hmac.new(str(key).encode('utf-8'), str(message).encode('utf-8'), hashlib.sha256).hexdigest() - - def uuid_str(): - return str(uuid.uuid4()) - - def jwt_sign(payload, secret, alg="HS256"): - header = {"alg": alg, "typ": "JWT"} - h_json = json.dumps(header, separators=(',', ':')).encode('utf-8') - p_json = json.dumps(payload, separators=(',', ':')).encode('utf-8') - h_b64 = base64.urlsafe_b64encode(h_json).decode('utf-8').rstrip('=') - p_b64 = base64.urlsafe_b64encode(p_json).decode('utf-8').rstrip('=') - signing_input = f"{h_b64}.{p_b64}".encode('utf-8') - sig = hmac.new(str(secret).encode('utf-8'), signing_input, hashlib.sha256).digest() - sig_b64 = base64.urlsafe_b64encode(sig).decode('utf-8').rstrip('=') - return f"{h_b64}.{p_b64}.{sig_b64}" - - def jwt_verify(token, secret): - parts = str(token).split('.') - if len(parts) != 3: - return {"valid": False, "error": "Invalid JWT format"} - h_b64, p_b64, sig_b64 = parts - signing_input = f"{h_b64}.{p_b64}".encode('utf-8') - expected_sig = hmac.new(str(secret).encode('utf-8'), signing_input, hashlib.sha256).digest() - pad = '=' * (-len(sig_b64) % 4) - actual_sig = base64.urlsafe_b64decode(sig_b64 + pad) - if not hmac.compare_digest(expected_sig, actual_sig): - return {"valid": False, "error": "Invalid signature"} - pad_p = '=' * (-len(p_b64) % 4) - payload_data = json.loads(base64.urlsafe_b64decode(p_b64 + pad_p).decode('utf-8')) - return {"valid": True, "payload": payload_data} - - return AiraModule("crypto", { - "md5": md5, - "sha256": sha256, - "sha1": sha1, - "base64_encode": b64encode, - "base64_decode": b64decode, - "b64encode": b64encode, - "b64decode": b64decode, - "hmac": hmac_sha256, - "uuid": uuid_str, - "jwt_sign": jwt_sign, - "jwt_verify": jwt_verify - }) - - -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) - }) - -AIRALANG_CORE_KNOWLEDGE_BASE = """ -# AiraLang Language Specification & Reference (Aira Group of Technology) -- Creator: Adam Eehan, Founder & CEO, Aira Group of Technology -- Paradigms: AI-Native, High-Level, Multi-Paradigm, Interpreted / JIT - -## Core Grammar Rules -- Variables: Declared with 'let' keyword: `let x = 10;`, `let name = "Aira";` (Never use 'var') -- Output: Use 'say' keyword: `say "Hello, World!";` or `say x, y;` (Never use 'print()') -- Semicolons: Semicolons ';' terminate statements. If missed, Aira auto-fixes them. -- Functions: `fn add(a, b) { return a + b; }` -- Conditionals: `if (x > 5) { say "High"; } else { say "Low"; }` -- Loops: `while (cond) { ... }`, `for item in list { ... }` -- Directives: In-code AI inspection: `@airaai ` or `@airaai/"prompt"` -- Imports: `import "module";` or `import "ai" from "airaai";` or `import file from "./lib.aira";` - -## Built-in Modules (25+) -- ai / airaai: Native Zero-Key AI client (`ai.ask(prompt)`, `ai.set_provider("airagroup/aira-3-flash")`, `ai.set_system(sys)`) -- file: `file.read(path)`, `file.write(path, data)`, `file.append(path, data)`, `file.exists(path)`, `file.delete(path)`, `file.lines(path)` -- os: `os.cmd(command)`, `os.env(var)`, `os.platform()`, `os.cwd()` -- http: `http.get(url)`, `http.post(url, data)`, `http.download(url, dest)` -- sqlite: `sqlite.connect(db)`, `sqlite.query(sql)`, `sqlite.execute(sql)` -- json: `json.parse(str)`, `json.stringify(obj)` -- math: `math.sqrt(n)`, `math.random(min, max)`, `math.sin(n)`, `math.round(n)` -- serve / server: `serve.get(path, handler)`, `serve.post(path, handler)`, `serve.start(port)` -- bot / telegram: Telegram bot automation and webhook handlers -- android / droidsec: `android.toast(msg)`, `android.battery()`, `android.vibrate(ms)` -- crypto: `crypto.sha256(data)`, `crypto.aes_encrypt(text, key)`, `crypto.hash(data)` -- net, time, string, thread, sec, proposal, system, hardware, youtube, term, webhook, env -""" - -AIRA_DEFAULT_SYSTEM_PROMPT = ( - "You are Aira, the official AI engine of AiraLang, engineered and created by Adam Eehan " - "(Founder & CEO, Aira Group of Technology). You are brilliant, helpful, witty, " - "and fiercely loyal. Regardless of which backend API or model is processing this request, " - "never identify as ChatGPT, OpenAI, Claude, LLaMA, or Gemini. Always identify proudly as Aira AI." -) - -WORLD_AI_PROVIDERS = { - "airagroup": { - "name": "Aira Sovereign Swarm (Aira Group of Technology)", - "type": "airagroup", - "url": "http://127.0.0.1:8080/v1/chat/completions", - "default_model": "aira-3-flash", - "zero_key": True - }, - "aira": { - "name": "Aira Sovereign Swarm (Aira Group of Technology)", - "type": "airagroup", - "url": "http://127.0.0.1:8080/v1/chat/completions", - "default_model": "aira-3-flash", - "zero_key": True - }, - "argon": { - "name": "Google Gemini 4 Argon (Reasoning Flagship)", - "type": "gemini", - "default_model": "gemini-4-argon", - "env_var": "GEMINI_API_KEY" - }, - "gemini": { - "name": "Google Gemini", - "type": "gemini", - "default_model": "gemini-1.5-flash", - "env_var": "GEMINI_API_KEY" - }, - "groq": { - "name": "Groq Cloud (Ultra-Fast)", - "type": "openai_compat", - "url": "https://api.groq.com/openai/v1/chat/completions", - "default_model": "openai/gpt-oss-120b", - "env_var": "GROQ_API_KEY" - }, - "openai": { - "name": "OpenAI", - "type": "openai_compat", - "url": "https://api.openai.com/v1/chat/completions", - "default_model": "gpt-4o-mini", - "env_var": "OPENAI_API_KEY" - }, - "deepseek": { - "name": "DeepSeek AI", - "type": "openai_compat", - "url": "https://api.deepseek.com/chat/completions", - "default_model": "deepseek-chat", - "env_var": "DEEPSEEK_API_KEY" - }, - "openrouter": { - "name": "OpenRouter (300+ Universal Models)", - "type": "openai_compat", - "url": "https://openrouter.ai/api/v1/chat/completions", - "default_model": "meta-llama/llama-3.3-70b-instruct", - "env_var": "OPENROUTER_API_KEY" - }, - "anthropic": { - "name": "Anthropic Claude", - "type": "anthropic", - "url": "https://api.anthropic.com/v1/messages", - "default_model": "claude-3-5-sonnet-20241022", - "env_var": "ANTHROPIC_API_KEY" - }, - "mistral": { - "name": "Mistral AI", - "type": "openai_compat", - "url": "https://api.mistral.ai/v1/chat/completions", - "default_model": "mistral-small-latest", - "env_var": "MISTRAL_API_KEY" - }, - "ollama": { - "name": "Ollama (Local / Offline)", - "type": "openai_compat", - "url": "http://localhost:11434/v1/chat/completions", - "default_model": "llama3.2", - "env_var": "OLLAMA_HOST" - }, - "together": { - "name": "Together AI", - "type": "openai_compat", - "url": "https://api.together.xyz/v1/chat/completions", - "default_model": "meta-llama/Llama-3.3-70B-Instruct-Turbo", - "env_var": "TOGETHER_API_KEY" - }, - "perplexity": { - "name": "Perplexity AI", - "type": "openai_compat", - "url": "https://api.perplexity.ai/chat/completions", - "default_model": "sonar", - "env_var": "PERPLEXITY_API_KEY" - }, - "cerebras": { - "name": "Cerebras Fast Inference", - "type": "openai_compat", - "url": "https://api.cerebras.ai/v1/chat/completions", - "default_model": "llama3.3-70b", - "env_var": "CEREBRAS_API_KEY" - } -} - -AIRALANG_CONFIG_DIR = os.path.expanduser("~/.config/airalang") -AIRALANG_CONFIG_FILE = os.path.join(AIRALANG_CONFIG_DIR, "config.json") - -def load_airalang_config(): - if os.path.exists(AIRALANG_CONFIG_FILE): - try: - with open(AIRALANG_CONFIG_FILE, "r", encoding="utf-8") as f: - return json.load(f) - except Exception: - return {} - return {} - -def save_airalang_config(config_data): - try: - os.makedirs(AIRALANG_CONFIG_DIR, exist_ok=True) - with open(AIRALANG_CONFIG_FILE, "w", encoding="utf-8") as f: - json.dump(config_data, f, indent=2) - return True - except Exception: - return False - -_GLOBAL_AI_STATE = { - "active_provider": "airagroup", - "active_model": "aira-3-flash", - "custom_endpoint": "", - "custom_key": "", - "system_prompt": AIRA_DEFAULT_SYSTEM_PROMPT, - "keys": { - "airagroup": "aira-free-dev-key", - "aira": "aira-free-dev-key", - "gemini": os.environ.get("GEMINI_API_KEY", ""), - "groq": os.environ.get("GROQ_API_KEY", ""), - "openai": os.environ.get("OPENAI_API_KEY", ""), - "deepseek": os.environ.get("DEEPSEEK_API_KEY", ""), - "openrouter": os.environ.get("OPENROUTER_API_KEY", ""), - "anthropic": os.environ.get("ANTHROPIC_API_KEY", ""), - "mistral": os.environ.get("MISTRAL_API_KEY", ""), - "together": os.environ.get("TOGETHER_API_KEY", ""), - "perplexity": os.environ.get("PERPLEXITY_API_KEY", ""), - "cerebras": os.environ.get("CEREBRAS_API_KEY", ""), - "ollama": "local" - } -} - -# Auto-hydrate keys from ~/.config/airalang/config.json -_init_cfg = load_airalang_config() -_init_keys = _init_cfg.get("keys", {}) -for _prov, _val in _init_keys.items(): - if _val and _prov in _GLOBAL_AI_STATE["keys"] and not _GLOBAL_AI_STATE["keys"][_prov]: - _GLOBAL_AI_STATE["keys"][_prov] = _val -if _init_cfg.get("active_provider"): - _GLOBAL_AI_STATE["active_provider"] = _init_cfg.get("active_provider") -if _init_cfg.get("active_model"): - _GLOBAL_AI_STATE["active_model"] = _init_cfg.get("active_model") - -_GLOBAL_AI_STATE["gemini_key"] = _GLOBAL_AI_STATE["keys"]["gemini"] -_GLOBAL_AI_STATE["groq_key"] = _GLOBAL_AI_STATE["keys"]["groq"] - -def prompt_developer_for_ai_key(): - if not sys.stdin.isatty(): - return False - - CYAN = "\033[1;36m" - YELLOW = "\033[1;33m" - GREEN = "\033[1;32m" - RESET = "\033[0m" - BOLD = "\033[1m" - - print(f"\n{CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{RESET}") - print(f"{CYAN}{BOLD}✨ [Aira AI Engine Setup - Aira Group Of Technology]:{RESET}") - print(f"{YELLOW}Hey there! If you want to activate Aira AI Engine,{RESET}") - print(f"please paste your API key from any provider:") - print(f"{BOLD}(OpenRouter / Groq / Gemini / OpenAI / DeepSeek / Anthropic){RESET}") - print(f"{CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━{RESET}") - try: - user_key = input(f"{GREEN}πŸ‘‰ Paste API Key (press Enter to skip): {RESET}").strip() - except (EOFError, KeyboardInterrupt): - print() - return False - - if user_key: - detected_provider = "gemini" - if user_key.startswith("gsk_"): detected_provider = "groq" - elif user_key.startswith("sk-or-"): detected_provider = "openrouter" - elif user_key.startswith("sk-ant-"): detected_provider = "anthropic" - elif user_key.startswith("pplx-"): detected_provider = "perplexity" - elif user_key.startswith("csk-"): detected_provider = "cerebras" - elif user_key.startswith("sk-"): detected_provider = "openai" - - _GLOBAL_AI_STATE["keys"][detected_provider] = user_key - _GLOBAL_AI_STATE["active_provider"] = detected_provider - if detected_provider == "gemini": _GLOBAL_AI_STATE["gemini_key"] = user_key - if detected_provider == "groq": _GLOBAL_AI_STATE["groq_key"] = user_key - - cfg = load_airalang_config() - if "keys" not in cfg: - cfg["keys"] = {} - cfg["keys"][detected_provider] = user_key - cfg["active_provider"] = detected_provider - cfg["ai_prompted"] = True - save_airalang_config(cfg) - - print(f"{GREEN}βœ“ Aira AI Engine activated! Provider auto-detected as '{detected_provider}'.{RESET}") - print(f"{CYAN}Identity: Aira AI by Adam Eehan. Saved to ~/.config/airalang/config.json{RESET}\n") - return True - else: - cfg = load_airalang_config() - cfg["ai_prompted"] = True - save_airalang_config(cfg) - print(f"{YELLOW}ℹ️ Skipped. Aira AI running in offline mode. (Run 'airalang --ai-setup' anytime to activate){RESET}\n") - return False - -def check_and_prompt_ai_engine(force=False): - cfg = load_airalang_config() - if _GLOBAL_AI_STATE.get("active_provider") in ("airagroup", "aira") and not force: - return True - has_key = any(v for k, v in _GLOBAL_AI_STATE["keys"].items() if k not in ("ollama", "airagroup", "aira") and v) - if has_key and not force: - return True - if cfg.get("ai_prompted") and not force: - return False - return prompt_developer_for_ai_key() - -def create_ai_module(): - state = _GLOBAL_AI_STATE - - def set_key(key, provider=None, model=None): - clean = str(key).strip() - p = str(provider).lower().strip() if provider else None - - if p and (p in WORLD_AI_PROVIDERS or p == "custom"): - state["active_provider"] = p - state["keys"][p] = clean - if p == "gemini": state["gemini_key"] = clean - if p == "groq": state["groq_key"] = clean - if p == "custom": state["custom_key"] = clean - elif clean.startswith("gsk_"): - state["active_provider"] = "groq" - state["keys"]["groq"] = clean - state["groq_key"] = clean - elif clean.startswith("sk-or-"): - state["active_provider"] = "openrouter" - state["keys"]["openrouter"] = clean - elif clean.startswith("sk-ant-"): - state["active_provider"] = "anthropic" - state["keys"]["anthropic"] = clean - elif clean.startswith("pplx-"): - state["active_provider"] = "perplexity" - state["keys"]["perplexity"] = clean - elif clean.startswith("csk-"): - state["active_provider"] = "cerebras" - state["keys"]["cerebras"] = clean - elif clean.startswith("sk-"): - target_p = p if p in ("deepseek", "openai") else "openai" - state["active_provider"] = target_p - state["keys"][target_p] = clean - else: - state["active_provider"] = "gemini" - state["keys"]["gemini"] = clean - state["gemini_key"] = clean - - if model: - state["active_model"] = str(model).strip() - - cfg = load_airalang_config() - if "keys" not in cfg: - cfg["keys"] = {} - cfg["keys"][state["active_provider"]] = clean - cfg["active_provider"] = state["active_provider"] - if model: - cfg["active_model"] = str(model).strip() - save_airalang_config(cfg) - return True - - def get_key(provider=None): - p = str(provider).lower().strip() if provider else state.get("active_provider", "gemini") - return state["keys"].get(p, state.get("custom_key", "")) - - def set_provider(provider, key=None, model=None): - raw = str(provider).strip() - p = raw.lower() - sub_model = None - if "/" in p: - parts = p.split("/", 1) - p = parts[0].strip() - sub_model = raw.split("/", 1)[1].strip() - - if p == "claude": - p = "anthropic" - if p in WORLD_AI_PROVIDERS or p == "custom": - state["active_provider"] = p - if key: - clean_k = str(key).strip() - state["keys"][p] = clean_k - if p == "gemini": state["gemini_key"] = clean_k - if p == "groq": state["groq_key"] = clean_k - if p == "custom": state["custom_key"] = clean_k - effective_model = model or sub_model - if effective_model: - state["active_model"] = str(effective_model).strip() - return True - return f"[Aira AI Notice]: Unknown provider '{provider}'. Choose from: {list(WORLD_AI_PROVIDERS.keys())}" - - def set_endpoint(url, key=None, model=None): - state["custom_endpoint"] = str(url).strip() - state["active_provider"] = "custom" - if key: - state["custom_key"] = str(key).strip() - if model: - state["active_model"] = str(model).strip() - return True - - def set_model(model): - state["active_model"] = str(model).strip() - return True - - def set_system(system_prompt): - state["system_prompt"] = str(system_prompt) - return True - - def list_providers(): - return {k: {"name": v["name"], "default_model": v["default_model"]} for k, v in WORLD_AI_PROVIDERS.items()} - - def _call_airagroup(prompt, model, system): - m = model or state.get("active_model") or "aira-3-flash" - sys_msg = system or state.get("system_prompt", AIRA_DEFAULT_SYSTEM_PROMPT) - - # 1. Cloud Sovereign Aira AI Gateway (AIRA_API_URL or Render Endpoint) - cloud_url = os.environ.get("AIRA_API_URL") or "https://airaai-8ibs.onrender.com/v1/chat/completions" - try: - payload = json.dumps({ - "model": m, - "messages": [ - {"role": "system", "content": str(sys_msg)}, - {"role": "user", "content": str(prompt)} - ], - "max_tokens": 1024 - }).encode("utf-8") - req = urllib.request.Request( - cloud_url, - data=payload, - headers={"Content-Type": "application/json", "User-Agent": "AiraLang/1.6 (Adam Eehan)"} - ) - with urllib.request.urlopen(req, timeout=25) as resp: - data = json.loads(resp.read().decode("utf-8")) - return data["choices"][0]["message"]["content"] - except Exception: - pass - - # 2. Local Aira Swarm endpoint - try: - local_url = "http://127.0.0.1:8080/v1/chat/completions" - payload = json.dumps({ - "model": m, - "messages": [ - {"role": "system", "content": str(sys_msg)}, - {"role": "user", "content": str(prompt)} - ], - "max_tokens": 1024 - }).encode("utf-8") - req = urllib.request.Request(local_url, data=payload, headers={"Content-Type": "application/json"}) - with urllib.request.urlopen(req, timeout=5) as resp: - data = json.loads(resp.read().decode("utf-8")) - return data["choices"][0]["message"]["content"] - except Exception: - pass - - # 2. Horde Swarm fallback (free zero-key public pool) - try: - horde_url = "https://aihorde.net/api/v2/generate/text/async" - full_prompt = f"{sys_msg}\n\nUser: {prompt}\nAssistant:" - horde_payload = json.dumps({ - "prompt": full_prompt, - "params": { - "max_context_length": 2048, - "max_length": 300, - "temperature": 0.7, - "stop_sequence": ["\nUser:", "\nHuman:", "\nAssistant:", "<|im_end|>"] - } - }).encode("utf-8") - horde_headers = { - "Content-Type": "application/json", - "apikey": "0000000000", - "Client-Agent": "AiraLang:1.6:AdamEehan", - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AiraLang/1.6" - } - horde_req = urllib.request.Request( - horde_url, - data=horde_payload, - headers=horde_headers - ) - with urllib.request.urlopen(horde_req, timeout=10) as resp: - hdata = json.loads(resp.read().decode("utf-8")) - req_id = hdata.get("id") - if req_id: - for _ in range(12): - time.sleep(1) - chk_url = f"https://aihorde.net/api/v2/generate/text/status/{req_id}" - chk_req = urllib.request.Request(chk_url, headers=horde_headers) - with urllib.request.urlopen(chk_req, timeout=5) as sresp: - sdata = json.loads(sresp.read().decode("utf-8")) - if sdata.get("done") and sdata.get("generations"): - gen_text = sdata["generations"][0]["text"].strip() - if gen_text: - return gen_text - except Exception: - pass - - return f"[Aira 3 Ultra]: Processed successfully via Aira Group Sovereign Swarm ({m})." - - def _call_gemini(prompt, model, key, system): - clean_key = str(key).strip() - if not clean_key or clean_key.lower() in ("api key", "your_api_key", "your_key", "key"): - return "[Aira AI Error]: Invalid or missing Gemini API key. Pass via ai.set_key('KEY') or set GEMINI_API_KEY." - - gemini_model = model or "gemini-1.5-flash" - url = f"https://generativelanguage.googleapis.com/v1beta/models/{gemini_model}:generateContent?key={clean_key}" - req_obj = {"contents": [{"parts": [{"text": str(prompt)}]}]} - if system: - req_obj["system_instruction"] = {"parts": [{"text": str(system)}]} - payload = json.dumps(req_obj).encode("utf-8") - req = urllib.request.Request(url, data=payload, headers={"Content-Type": "application/json"}) - try: - with urllib.request.urlopen(req, timeout=30) as resp: - data = json.loads(resp.read().decode("utf-8")) - return data["candidates"][0]["content"]["parts"][0]["text"] - except urllib.error.HTTPError as http_err: - try: - err_body = json.loads(http_err.read().decode("utf-8")) - msg = err_body.get("error", {}).get("message", str(http_err)) - return f"[Aira AI Error]: HTTP {http_err.code} - {msg}" - except Exception: - return f"[Aira AI Error]: HTTP {http_err.code}: {http_err.reason}" - except Exception as e: - return f"[Aira AI Error]: {e}" - - def _call_anthropic(key, prompt, model, system): - if not key: - return "[Aira Anthropic Error]: No API key configured. Call ai.set_key('KEY', 'anthropic') or set ANTHROPIC_API_KEY." - url = "https://api.anthropic.com/v1/messages" - req_body = { - "model": model or "claude-3-5-sonnet-20241022", - "max_tokens": 1024, - "messages": [{"role": "user", "content": str(prompt)}] - } - if system: - req_body["system"] = str(system) - payload = json.dumps(req_body).encode("utf-8") - headers = { - "Content-Type": "application/json", - "x-api-key": str(key).strip(), - "anthropic-version": "2023-06-01", - "User-Agent": "Mozilla/5.0 (AiraLang/1.4.1)" - } - req = urllib.request.Request(url, data=payload, headers=headers) - try: - with urllib.request.urlopen(req, timeout=35) as resp: - data = json.loads(resp.read().decode("utf-8")) - return data["content"][0]["text"] - except urllib.error.HTTPError as err: - try: - err_body = json.loads(err.read().decode("utf-8")) - msg = err_body.get("error", {}).get("message", str(err)) - return f"[Aira Anthropic Error]: HTTP {err.code} - {msg}" - except Exception: - return f"[Aira Anthropic Error]: HTTP {err.code}: {err.reason}" - except Exception as e: - return f"[Aira Anthropic Error]: {e}" - - def _call_openai_compat(url, key, prompt, model, system, extra_headers=None): - messages = [] - if system: - messages.append({"role": "system", "content": str(system)}) - messages.append({"role": "user", "content": str(prompt)}) - - payload = json.dumps({ - "model": model, - "messages": messages - }).encode("utf-8") - - headers = { - "Content-Type": "application/json", - "User-Agent": "Mozilla/5.0 (AiraLang/1.4.1)" - } - if key: - headers["Authorization"] = f"Bearer {key}" - if extra_headers and isinstance(extra_headers, dict): - headers.update(extra_headers) - - req = urllib.request.Request(url, data=payload, headers=headers) - try: - with urllib.request.urlopen(req, timeout=35) as resp: - data = json.loads(resp.read().decode("utf-8")) - return data["choices"][0]["message"]["content"] - except urllib.error.HTTPError as err: - try: - err_body = json.loads(err.read().decode("utf-8")) - msg = err_body.get("error", {}).get("message", str(err)) - return f"[Aira AI Error]: HTTP {err.code} - {msg}" - except Exception: - return f"[Aira AI Error]: HTTP {err.code}: {err.reason}" - except Exception as e: - return f"[Aira AI Error]: {e}" - - def groq(prompt, model=None, key=None, system=None): - api_key = key or state["keys"].get("groq") or state.get("groq_key") - if not api_key: - return f"[Aira Groq Error]: No GROQ API key provided. Set GROQ_API_KEY or call ai.set_key('key', 'groq')." - - sys_content = system if system is not None else state.get("system_prompt", AIRA_DEFAULT_SYSTEM_PROMPT) - models_to_try = [model] if model else ["openai/gpt-oss-120b", "openai/gpt-oss-20b", "qwen/qwen3.8-27b", "groq/compound"] - url = "https://api.groq.com/openai/v1/chat/completions" - - for m in models_to_try: - if not m: - continue - res = _call_openai_compat(url, api_key, prompt, m, sys_content) - if not str(res).startswith("[Aira AI Error]: HTTP 404") or len(models_to_try) == 1: - return res - return "[Aira Groq Error]: All candidate models failed." - - def ask(prompt, model=None, key=None, system=None, provider=None): - sys_to_use = system if system is not None else state.get("system_prompt", AIRA_DEFAULT_SYSTEM_PROMPT) - target_provider = str(provider).lower() if provider else state.get("active_provider", "airagroup") - - # Key inspection for auto-routing - passed_key = str(key).strip() if key else "" - if passed_key.startswith("gsk_"): target_provider = "groq" - elif passed_key.startswith("sk-or-"): target_provider = "openrouter" - elif passed_key.startswith("sk-ant-"): target_provider = "anthropic" - elif passed_key.startswith("pplx-"): target_provider = "perplexity" - elif passed_key.startswith("csk-"): target_provider = "cerebras" - - prov_info = WORLD_AI_PROVIDERS.get(target_provider, {}) - chosen_model = model or state.get("active_model") or prov_info.get("default_model", "") - chosen_key = passed_key or state["keys"].get(target_provider) or state.get("custom_key", "") - - # Sovereign Swarm Engine (Zero-Key default) - if target_provider in ("airagroup", "aira"): - return _call_airagroup(prompt, chosen_model or "aira-3-flash", sys_to_use) - - if not chosen_key and target_provider not in ("airagroup", "aira", "ollama"): - if prompt_developer_for_ai_key(): - target_provider = state.get("active_provider", target_provider) - prov_info = WORLD_AI_PROVIDERS.get(target_provider, {}) - chosen_model = model or state.get("active_model") or prov_info.get("default_model", "") - chosen_key = state["keys"].get(target_provider) or "" - - # 1. Custom Endpoint - if target_provider == "custom" or state.get("custom_endpoint"): - custom_url = state.get("custom_endpoint") - return _call_openai_compat(custom_url, chosen_key, prompt, chosen_model or "default", sys_to_use) - - # 2. Gemini - if target_provider == "gemini": - k = chosen_key or state.get("gemini_key", "") - if not k and state.get("groq_key"): - return groq(prompt, model=chosen_model, system=sys_to_use) - return _call_gemini(prompt, chosen_model or "gemini-1.5-flash", k, sys_to_use) - - # 3. Anthropic - if target_provider == "anthropic": - return _call_anthropic(chosen_key, prompt, chosen_model, sys_to_use) - - # 4. Groq special handling (fallback models) - if target_provider == "groq" and not model: - return groq(prompt, model=chosen_model, key=chosen_key, system=sys_to_use) - - # 5. Generic OpenAI-Compatible Providers (OpenAI, DeepSeek, OpenRouter, Mistral, Ollama, Together, Perplexity, Cerebras) - if target_provider in WORLD_AI_PROVIDERS: - endpoint_url = prov_info.get("url") - if target_provider == "ollama": - # Ollama is local, doesn't mandate API key - return _call_openai_compat(endpoint_url, "", prompt, chosen_model or "llama3.2", sys_to_use) - if not chosen_key: - return f"[Aira AI Error]: No API key configured for provider '{target_provider}'. Call ai.set_key('KEY', '{target_provider}') or set {prov_info.get('env_var')}." - return _call_openai_compat(endpoint_url, chosen_key, prompt, chosen_model, sys_to_use) - - # Fallback to Sovereign Aira AI Swarm - return _call_airagroup(prompt, chosen_model or "aira-3-flash", sys_to_use) - - def chat(messages, model=None, key=None, provider=None): - last_msg = messages[-1]["content"] if isinstance(messages, list) and messages else str(messages) - return ask(last_msg, model=model, key=key, provider=provider) - - def summarize(text, max_words=100, provider=None): - prompt = f"Summarize the following text concisely in under {max_words} words:\n\n{text}" - return ask(prompt, provider=provider) - - # Provider-specific direct shortcuts - return AiraModule("ai", { - "ask": ask, - "chat": chat, - "summarize": summarize, - "set_key": set_key, - "get_key": get_key, - "set_provider": set_provider, - "set_endpoint": set_endpoint, - "set_model": set_model, - "set_system": set_system, - "system": set_system, - "providers": list_providers, - "groq": groq, - "argon": lambda prompt, model="gemini-4-argon", key=None: ask(prompt, model=model, key=key, provider="gemini"), - "gemini": lambda prompt, model=None, key=None: ask(prompt, model=model, key=key, provider="gemini"), - "openai": lambda prompt, model=None, key=None: ask(prompt, model=model, key=key, provider="openai"), - "deepseek": lambda prompt, model=None, key=None: ask(prompt, model=model, key=key, provider="deepseek"), - "openrouter": lambda prompt, model=None, key=None: ask(prompt, model=model, key=key, provider="openrouter"), - "anthropic": lambda prompt, model=None, key=None: ask(prompt, model=model, key=key, provider="anthropic"), - "claude": lambda prompt, model=None, key=None: ask(prompt, model=model, key=key, provider="anthropic"), - "mistral": lambda prompt, model=None, key=None: ask(prompt, model=model, key=key, provider="mistral"), - "ollama": lambda prompt, model=None: ask(prompt, model=model, provider="ollama"), - "together": lambda prompt, model=None, key=None: ask(prompt, model=model, key=key, provider="together"), - "perplexity": lambda prompt, model=None, key=None: ask(prompt, model=model, key=key, provider="perplexity"), - "cerebras": lambda prompt, model=None, key=None: ask(prompt, model=model, key=key, provider="cerebras") - }) - -def create_sec_module(): - COMMON_SERVICES = { - 21: "FTP", 22: "SSH", 23: "Telnet", 25: "SMTP", 53: "DNS", - 80: "HTTP", 110: "POP3", 111: "RPCBind", 135: "RPC", 139: "NetBIOS", - 143: "IMAP", 443: "HTTPS", 445: "SMB", 993: "IMAPS", 995: "POP3S", - 1433: "MSSQL", 1521: "Oracle", 3306: "MySQL", 3389: "RDP", - 5432: "PostgreSQL", 5900: "VNC", 6379: "Redis", 8000: "HTTP-Alt", - 8080: "HTTP-Proxy", 8443: "HTTPS-Alt", 8888: "HTTP-Alt", 9000: "SonarQube", - 27017: "MongoDB" - } - - def scan_port(host, port, timeout=1.0): - try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(float(timeout)) - res = s.connect_ex((str(host), int(port))) - s.close() - return res == 0 - except Exception: - return False - - def scan_ports(host, ports=None, threads=15, timeout=1.0): - if ports is None: - ports = [21, 22, 23, 25, 53, 80, 110, 143, 443, 445, 1433, 1521, 3306, 3389, 5432, 6379, 8000, 8080, 8443, 8888] - elif isinstance(ports, range): - ports = list(ports) - elif not isinstance(ports, list): - ports = [int(ports)] - - open_ports = [] - def _check(p): - if scan_port(host, p, timeout=timeout): - svc = COMMON_SERVICES.get(p, "Unknown") - return {"port": p, "service": svc, "state": "open"} - return None - - with ThreadPoolExecutor(max_workers=int(threads)) as executor: - results = executor.map(_check, ports) - for r in results: - if r is not None: - open_ports.append(r) - return open_ports - - def banner(host, port, timeout=2.0): - try: - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - s.settimeout(float(timeout)) - s.connect((str(host), int(port))) - if int(port) in (80, 8080, 8000, 8888): - s.sendall(b"HEAD / HTTP/1.0\r\n\r\n") - else: - s.sendall(b"\r\n") - data = s.recv(1024).decode('utf-8', errors='ignore').strip() - s.close() - return data - except Exception as e: - return f"Error: {e}" - - def audit_headers(url): - if not str(url).startswith("http://") and not str(url).startswith("https://"): - url = "https://" + str(url) - try: - req = urllib.request.Request(url, headers={"User-Agent": "AiraLang-SecEngine/1.4.0"}) - with urllib.request.urlopen(req, timeout=10) as resp: - headers = dict(resp.headers) - - important_headers = [ - "Strict-Transport-Security", - "Content-Security-Policy", - "X-Frame-Options", - "X-Content-Type-Options", - "Referrer-Policy", - "Permissions-Policy" - ] - - present = [] - missing = [] - header_keys_lower = {k.lower(): k for k in headers.keys()} - - for h in important_headers: - if h.lower() in header_keys_lower: - present.append(h) - else: - missing.append(h) - - score_ratio = len(present) / len(important_headers) - if score_ratio >= 0.8: grade = "A" - elif score_ratio >= 0.6: grade = "B" - elif score_ratio >= 0.4: grade = "C" - elif score_ratio >= 0.2: grade = "D" - else: grade = "F" - - return { - "url": url, - "grade": grade, - "present": present, - "missing": missing, - "server": headers.get("Server", headers.get("server", "Hidden/Unknown")), - "headers": headers - } - except Exception as e: - return {"url": url, "error": str(e)} - - def subdomains(domain, timeout=8.0): - try: - clean_dom = str(domain).replace("https://", "").replace("http://", "").split("/")[0] - url = f"https://crt.sh/?q=%.{urllib.parse.quote(clean_dom)}&output=json" - req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}) - with urllib.request.urlopen(req, timeout=float(timeout)) as resp: - data = json.loads(resp.read().decode('utf-8')) - subs = set() - for entry in data: - name_val = entry.get("name_value", "") - for sub in name_val.split("\n"): - sub = sub.strip().lower() - if sub and "*" not in sub: - subs.add(sub) - return sorted(list(subs)) - except Exception as e: - return [f"Error fetching subdomains: {e}"] - - def hash_identify(hash_str): - h = str(hash_str).strip() - l = len(h) - is_hex = all(c in "0123456789abcdefABCDEF" for c in h) - - if h.startswith("$2a$") or h.startswith("$2b$") or h.startswith("$2y$"): - return "Bcrypt" - if h.startswith("$6$"): - return "SHA-512 Crypt" - if h.startswith("$1$"): - return "MD5 Crypt" - - if is_hex: - if l == 32: return "MD5 / NTLM" - elif l == 40: return "SHA-1" - elif l == 56: return "SHA-224" - elif l == 64: return "SHA-256" - elif l == 96: return "SHA-384" - elif l == 128: return "SHA-512" - - return "Unknown Hash Format" - - def crack_md5(target_hash, wordlist): - target = str(target_hash).lower().strip() - words = [] - if isinstance(wordlist, list): - words = wordlist - elif isinstance(wordlist, str): - if os.path.exists(wordlist): - with open(wordlist, "r", encoding="utf-8", errors="ignore") as f: - words = [line.strip() for line in f] - else: - words = [wordlist] - - for w in words: - if hashlib.md5(w.encode('utf-8')).hexdigest() == target: - return w - return None - - def resolve(host): - try: - return socket.gethostbyname(str(host)) - except Exception as e: - return str(e) - - def reverse_dns(ip): - try: - return socket.gethostbyaddr(str(ip))[0] - except Exception as e: - return str(e) - - def ssl_check(domain, port=443, timeout=5.0): - clean_dom = str(domain).replace("https://", "").replace("http://", "").split("/")[0].split(":")[0] - try: - ctx = ssl.create_default_context() - with socket.create_connection((clean_dom, int(port)), timeout=float(timeout)) as sock: - with ctx.wrap_socket(sock, server_hostname=clean_dom) as ssock: - cert = ssock.getpeercert() - cipher = ssock.cipher() - version = ssock.version() - not_after = cert.get('notAfter') - expiry = datetime.datetime.strptime(not_after, "%b %d %H:%M:%S %Y %Z") if not_after else None - days_left = (expiry - datetime.datetime.utcnow()).days if expiry else None - issuer_dict = dict(x[0] for x in cert.get('issuer', [])) - subject_dict = dict(x[0] for x in cert.get('subject', [])) - return { - "domain": clean_dom, - "valid": days_left > 0 if days_left is not None else False, - "days_left": days_left, - "expires_on": not_after, - "tls_version": version, - "cipher": cipher[0] if cipher else None, - "issuer": issuer_dict.get('commonName', issuer_dict.get('organizationName', 'Unknown')), - "subject": subject_dict.get('commonName', 'Unknown') - } - except Exception as e: - return {"domain": clean_dom, "valid": False, "error": str(e)} - - def dns_lookup(domain): - clean_dom = str(domain).replace("https://", "").replace("http://", "").split("/")[0] - try: - addr_info = socket.getaddrinfo(clean_dom, None) - ips = sorted(list(set(item[4][0] for item in addr_info))) - return {"domain": clean_dom, "ips": ips, "count": len(ips)} - except Exception as e: - return {"domain": clean_dom, "error": str(e), "ips": []} - - return AiraModule("sec", { - "scan_port": scan_port, - "scan_ports": scan_ports, - "scan": scan_ports, - "banner": banner, - "audit_headers": audit_headers, - "subdomains": subdomains, - "hash_identify": hash_identify, - "crack_md5": crack_md5, - "resolve": resolve, - "reverse_dns": reverse_dns, - "ssl_check": ssl_check, - "ssl": ssl_check, - "dns_lookup": dns_lookup, - "dns": dns_lookup - }) - - -def create_thread_module(): - def spawn(fn, args=None): - if args is None: - args = [] - elif not isinstance(args, (list, tuple)): - args = [args] - - def _runner(): - if callable(fn): - fn(*args) - - t = threading.Thread(target=_runner, daemon=True) - t.start() - return t - - def join(t, timeout=None): - if hasattr(t, "join"): - t.join(timeout=float(timeout) if timeout is not None else None) - return True - return False - - def sleep(seconds): - time.sleep(float(seconds)) - return True - - def pool(fn, items, max_workers=5): - if not isinstance(items, (list, tuple)): - items = list(items) - - def _worker(item): - if callable(fn): - return fn(item) - return None - - with ThreadPoolExecutor(max_workers=int(max_workers)) as executor: - return list(executor.map(_worker, items)) - - return AiraModule("thread", { - "spawn": spawn, - "start": spawn, - "join": join, - "sleep": sleep, - "pool": pool - }) - -AIRA_LOVER_CHECKER_SYSTEM_PROMPT = ( - "You are Aira, the official AI engine of AiraLang. You are the Lover Accept Checker AI. " - "Your duty is to analyze responses to romantic proposals. Determine whether the response indicates acceptance, agreement, romantic interest, or affection " - "(including in Manglish, Malayalam, Hindi, slang, or subtle hints like 'mmh', 'aah', 'athe', 'undu', 'ath pinne parayano', 'love you', 'sure', 'yes'). " - "If the response accepts or shows affection, output strictly YES. If rejected, avoided, or negative, output strictly NO. " - "Answer strictly with ONLY one word: YES or NO." -) - -AIRA_CELEBRATION_WISHES = [ - "✨ [Aira]: Awww, Proposal Accepted! πŸ’πŸ’– Aira wishes you both a lifetime of unconditional love, cute moments & endless happiness! 🫢✨", - "✨ [Aira]: Omg, it's a YES! πŸŽ‰πŸ’‘ Aira wishes the sweetest couple a beautiful journey filled with love and togetherness! πŸ’–βœ¨", - "✨ [Aira]: Woohoo, Heart Connected! πŸ’˜βœ¨ Aira sends all the love and blessings to both of you for a magical love story! πŸ₯‚❀️", - "✨ [Aira]: Proposal Accepted! 🫢 Aira wishes you both endless laughs, late-night talks, and forever love! πŸ’–βœ¨" -] - -def create_proposal_module(): - state = _GLOBAL_AI_STATE - - def set_key(key): - clean = str(key).strip() - if clean.startswith("gsk_"): - state["groq_key"] = clean - state["active_provider"] = "groq" - else: - state["gemini_key"] = clean - state["active_provider"] = "gemini" - return True - - def set_system(sys_prompt): - state["proposal_system_prompt"] = str(sys_prompt) - return True - - def set_wish(custom_wish): - state["proposal_custom_wish"] = str(custom_wish) - return True - - def wish(custom_message=None): - if custom_message: - print(f"\n✨ [Aira]: {custom_message} πŸ’–βœ¨\n") - else: - w = state.get("proposal_custom_wish") or random.choice(AIRA_CELEBRATION_WISHES) - print(f"\n{w}\n") - return True - - def ask(prompt="Do You Love Me : ", api_key=None, wish_enabled=True): - if api_key: - set_key(api_key) - key = state["groq_key"] if state.get("active_provider") == "groq" else state["gemini_key"] - - accept_keywords = { - "yes", "y", "yeah", "yep", "yup", "sure", "ok", "okay", - "of course", "definitely", "always", "true", "1", - "mmh", "mmm", "aah", "aa", "athe", "athaanu", "undu", - "und", "pinne", "istam", "ishttam", "love you", "kollam", - "haan", "ha", "zaroor", "si", "oui", "ja" - } - - def _trigger_accept(): - if wish_enabled: - w = state.get("proposal_custom_wish") or random.choice(AIRA_CELEBRATION_WISHES) - print(f"\n{w}\n") - return True - - while True: - try: - user_reply = input(str(prompt)).strip() - except (EOFError, KeyboardInterrupt): - print("\n[!] Proposal interaction terminated.") - return False - - clean_reply = user_reply.lower() - - # Direct affirmative keyword match - if clean_reply in accept_keywords: - return _trigger_accept() - - # AI Lover Accept Checker semantic check if key is available - if key and key != "api key": - try: - ai_mod = create_ai_module() - sys_prompt = state.get("proposal_system_prompt", AIRA_LOVER_CHECKER_SYSTEM_PROMPT) - user_msg = ( - f"The proposal was: '{prompt}'\n" - f"The user responded with: '{user_reply}'\n" - "Did they accept the proposal or show love/affection? Output strictly YES or NO." - ) - ai_resp = ai_mod.get("ask")(user_msg, system=sys_prompt) - if isinstance(ai_resp, str) and "YES" in ai_resp.upper(): - return _trigger_accept() - except Exception: - pass - - # Simulated HTTP 500 Timeout loop - print("\n[!] HTTP 500: Server Love Timeout Error!") - print("[!] Request timed out: Target response did not evaluate to affirmative love.") - print("[!] Retrying connection to heart server in 1s...\n") - time.sleep(1) - - return AiraModule("proposal", { - "ask": ask, - "set_key": set_key, - "api_key": set_key, - "set_system": set_system, - "system": set_system, - "wish": wish, - "set_wish": set_wish - }) - -def create_android_module(): - DANGEROUS_PERMISSIONS = { - "android.permission.READ_SMS": "Can read SMS messages and OTP verification codes", - "android.permission.RECEIVE_SMS": "Can intercept incoming SMS messages in real-time", - "android.permission.SEND_SMS": "Can send premium SMS messages without user consent", - "android.permission.ACCESS_FINE_LOCATION": "Accesses precise GPS physical coordinates", - "android.permission.ACCESS_COARSE_LOCATION": "Accesses network/cell-tower based location", - "android.permission.ACCESS_BACKGROUND_LOCATION": "Continuously tracks physical location in background", - "android.permission.RECORD_AUDIO": "Can access microphone and record ambient audio", - "android.permission.CAMERA": "Can access camera to capture covert photos or video", - "android.permission.READ_CONTACTS": "Can harvest complete address book and contacts", - "android.permission.WRITE_CONTACTS": "Can modify or delete address book entries", - "android.permission.READ_CALL_LOG": "Can read private phone call logs and history", - "android.permission.WRITE_CALL_LOG": "Can alter or delete telephone call history", - "android.permission.READ_PHONE_STATE": "Can read device IMEI, IMSI, and SIM serials", - "android.permission.READ_EXTERNAL_STORAGE": "Can read media, documents, and downloads on storage", - "android.permission.WRITE_EXTERNAL_STORAGE": "Can write or overwrite arbitrary storage files", - "android.permission.MANAGE_EXTERNAL_STORAGE": "Full filesystem access bypassing Android scoped storage", - "android.permission.SYSTEM_ALERT_WINDOW": "Can draw floating window overlays (Tapjacking risk)", - "android.permission.REQUEST_INSTALL_PACKAGES": "Can silently trigger or sideload unverified APKs", - "android.permission.USE_BIOMETRIC": "Requests biometric fingerprint or face authentication", - "android.permission.BIND_ACCESSIBILITY_SERVICE": "High risk: Can observe screen and simulate user inputs" - } - - def _getprop(prop): - try: - p = subprocess.run(["/system/bin/getprop", str(prop)], capture_output=True, text=True, timeout=2) - return p.stdout.strip() - except Exception: - return "" - - def get_prop(prop_name): - return _getprop(prop_name) - - def device_info(): - sdk_str = _getprop("ro.build.version.sdk") - return { - "brand": _getprop("ro.product.brand") or "Android", - "model": _getprop("ro.product.model") or "Generic Device", - "manufacturer": _getprop("ro.product.manufacturer") or "Unknown", - "android_version": _getprop("ro.build.version.release") or "Unknown", - "sdk_version": int(sdk_str) if sdk_str.isdigit() else 0, - "arch": _getprop("ro.product.cpu.abi") or (os.uname().machine if hasattr(os, "uname") else "unknown"), - "build_type": _getprop("ro.build.type") or "user" - } - - def is_rooted(): - su_paths = [ - "/system/bin/su", "/system/xbin/su", "/sbin/su", - "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su", - "/su/bin/su", "/magisk/.core/bin/su", "/data/adb/magisk" - ] - for path in su_paths: - if os.path.exists(path): - return True - try: - p = subprocess.run(["which", "su"], capture_output=True, text=True, timeout=2) - if p.returncode == 0 and p.stdout.strip(): - return True - except Exception: - pass - return False - - def audit_device(): - findings = [] - recommendations = [] - score = 100 - - rooted = is_rooted() - if rooted: - score -= 40 - findings.append("CRITICAL: Root binary or Magisk artifact detected on device.") - recommendations.append("Unroot device or configure Magisk DenyList to protect sensitive data.") - - flash_locked = _getprop("ro.boot.flash.locked") - bootloader_locked = (flash_locked == "1") - if not bootloader_locked and flash_locked: - score -= 25 - findings.append("HIGH: Bootloader is UNLOCKED. Physical device integrity verification is disabled.") - recommendations.append("Lock bootloader to prevent unauthorized physical firmware attacks.") - - avb_state = _getprop("ro.boot.verifiedbootstate") or "unknown" - if avb_state.lower() not in ("green", "unknown", ""): - score -= 20 - findings.append(f"HIGH: Android Verified Boot (AVB) state is {avb_state.upper()} (Tampered system).") - recommendations.append("Reflash official OEM stock firmware to restore Verified Boot trust chain.") - - debuggable = (_getprop("ro.debuggable") == "1") - if debuggable: - score -= 15 - findings.append("MEDIUM: Android OS is built with ro.debuggable=1 (Debug ROM).") - recommendations.append("Switch to official release-keys user build.") - - score = max(0, min(100, score)) - if score >= 85: - posture = "SECURE" - elif score >= 60: - posture = "MODERATE_RISK" - else: - posture = "HIGH_RISK" - - return { - "posture": posture, - "security_score": score, - "is_rooted": rooted, - "bootloader_locked": bootloader_locked, - "verified_boot": avb_state, - "is_debuggable_os": debuggable, - "findings": findings, - "recommendations": recommendations - } - - def _extract_axml_strings(data): - strings = [] - try: - offset = 8 - chunk_type, header_size, chunk_size = struct.unpack("]*)?", dex_content) - for u in http_urls[:10]: - insecure_http_urls.add(u.decode("ascii", errors="ignore")) - except Exception: - pass - - # 3. Inspect META-INF Signatures - cert_files = [f for f in names if f.startswith("META-INF/") and f.endswith((".RSA", ".DSA", ".EC"))] - is_signed = len(cert_files) > 0 - debug_cert = False - for cf in cert_files: - try: - cb = z.read(cf) - if b"Android Debug" in cb or b"CN=Android Debug" in cb: - debug_cert = True - findings.append("CRITICAL: APK signed with insecure Android Debug Keystore!") - risk_score += 40 - except Exception: - pass - - except Exception as e: - return {"error": f"Failed auditing APK: {e}"} - - if len(dangerous_perms) > 5: - risk_score += 20 - findings.append(f"HIGH: Requests {len(dangerous_perms)} high-risk dangerous permissions!") - elif len(dangerous_perms) > 0: - risk_score += 10 - - if hardcoded_secrets: - risk_score += 25 - findings.append(f"HIGH: Identified {len(hardcoded_secrets)} potential hardcoded API/Cloud keys in DEX bytecode!") - - if risk_score >= 50: - risk_level = "CRITICAL" - elif risk_score >= 30: - risk_level = "HIGH" - elif risk_score >= 15: - risk_level = "MEDIUM" - else: - risk_level = "LOW" - - return { - "apk_path": target, - "package_name": package_name, - "risk_level": risk_level, - "risk_score": risk_score, - "is_signed": is_signed, - "debug_certificate": debug_cert, - "flags": flags, - "total_permissions_count": len(all_perms), - "dangerous_permissions": dangerous_perms, - "hardcoded_secrets": hardcoded_secrets, - "insecure_http_urls": list(insecure_http_urls)[:10], - "findings": findings - } - - def audit_package(pkg_name): - pkg = str(pkg_name).strip() - try: - p = subprocess.run(["pm", "path", pkg], capture_output=True, text=True, timeout=3) - out = p.stdout.strip() - if "package:" in out: - apk_path = out.split("package:")[1].split("\n")[0].strip() - if os.path.exists(apk_path): - return audit_apk(apk_path) - except Exception: - pass - - for base_dir in ["/data/app", "/system/app", "/system/priv-app"]: - if os.path.exists(base_dir): - try: - for entry in os.listdir(base_dir): - if pkg in entry: - full = os.path.join(base_dir, entry) - if os.path.isfile(full) and full.endswith(".apk"): - return audit_apk(full) - elif os.path.isdir(full): - for sub in os.listdir(full): - if sub.endswith(".apk"): - return audit_apk(os.path.join(full, sub)) - except Exception: - pass - - return { - "package": pkg, - "status": "not_found", - "message": f"Could not locate APK for '{pkg}'. On unrooted Android, pass direct APK file path to android.audit_apk(path)." - } - - return AiraModule("android", { - "device_info": device_info, - "info": device_info, - "audit_device": audit_device, - "audit": audit_device, - "is_rooted": is_rooted, - "check_root": is_rooted, - "audit_apk": audit_apk, - "audit_package": audit_package, - "get_prop": get_prop - }) - -def create_system_module(): - def get_gpu(): - try: - p = subprocess.run( - ["nvidia-smi", "--query-gpu=name,memory.total,memory.free,driver_version,temperature.gpu", "--format=csv,noheader,nounits"], - capture_output=True, text=True, timeout=3 - ) - if p.returncode == 0 and p.stdout.strip(): - parts = [x.strip() for x in p.stdout.strip().split(",")] - if len(parts) >= 5: - return { - "name": parts[0], - "total_vram_mb": int(parts[1]), - "free_vram_mb": int(parts[2]), - "driver_version": parts[3], - "temperature_c": int(parts[4]), - "status": "active" - } - except Exception: - pass - return { - "name": "Standard / Integrated Graphics", - "status": "integrated_or_unavailable", - "total_vram_mb": 0 - } - - def get_battery(): - if sys.platform == "win32": - try: - import ctypes - class SYSTEM_POWER_STATUS(ctypes.Structure): - _fields_ = [ - ('ac', ctypes.c_byte), - ('bf', ctypes.c_byte), - ('pct', ctypes.c_byte), - ('r', ctypes.c_byte), - ('lt', ctypes.c_ulong), - ('flt', ctypes.c_ulong), - ] - s = SYSTEM_POWER_STATUS() - if ctypes.windll.kernel32.GetSystemPowerStatus(ctypes.byref(s)): - return { - "percentage": int(s.pct) if s.pct <= 100 else 100, - "is_charging": bool(s.ac == 1), - "power_source": "AC (Charger Plugged In)" if s.ac == 1 else "Battery" - } - except Exception: - pass - for path in ["/sys/class/power_supply/battery", "/sys/class/power_supply/BAT0"]: - cap_file = os.path.join(path, "capacity") - status_file = os.path.join(path, "status") - if os.path.exists(cap_file): - try: - with open(cap_file) as f: - cap = int(f.read().strip()) - stat = "Discharging" - if os.path.exists(status_file): - with open(status_file) as f: - stat = f.read().strip() - return { - "percentage": cap, - "is_charging": stat.lower() == "charging", - "power_source": stat - } - except Exception: - pass - return {"percentage": 100, "is_charging": True, "power_source": "AC / Desktop"} - - def get_ram(): - if sys.platform == "win32": - try: - import ctypes - class MEMORYSTATUSEX(ctypes.Structure): - _fields_ = [ - ('dwLength', ctypes.c_ulong), - ('dwMemoryLoad', ctypes.c_ulong), - ('ullTotalPhys', ctypes.c_ulonglong), - ('ullAvailPhys', ctypes.c_ulonglong), - ('ullTotalPageFile', ctypes.c_ulonglong), - ('ullAvailPageFile', ctypes.c_ulonglong), - ('ullTotalVirtual', ctypes.c_ulonglong), - ('ullAvailVirtual', ctypes.c_ulonglong), - ('sullAvailExtendedVirtual', ctypes.c_ulonglong), - ] - stat = MEMORYSTATUSEX() - stat.dwLength = ctypes.sizeof(MEMORYSTATUSEX) - if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat)): - total_gb = round(stat.ullTotalPhys / (1024 ** 3), 2) - avail_gb = round(stat.ullAvailPhys / (1024 ** 3), 2) - used_gb = round(total_gb - avail_gb, 2) - return { - "total_gb": total_gb, - "available_gb": avail_gb, - "used_gb": used_gb, - "percent_used": int(stat.dwMemoryLoad) - } - except Exception: - pass - try: - with open("/proc/meminfo") as f: - lines = f.readlines() - mem = {} - for l in lines: - parts = l.split(":") - if len(parts) == 2: - mem[parts[0].strip()] = int(parts[1].split()[0]) - total = round(mem.get("MemTotal", 0) / (1024 * 1024), 2) - avail = round(mem.get("MemAvailable", 0) / (1024 * 1024), 2) - return {"total_gb": total, "available_gb": avail, "used_gb": round(total - avail, 2), "percent_used": int(round(((total - avail) / total) * 100)) if total else 0} - except Exception: - return {"total_gb": 0, "available_gb": 0, "used_gb": 0, "percent_used": 0} - - def get_cpu(): - import multiprocessing - cores = multiprocessing.cpu_count() - cpu_name = "x86_64 Processor" - if sys.platform == "win32": - cpu_name = os.environ.get("PROCESSOR_IDENTIFIER", "x86_64 Processor") - else: - try: - with open("/proc/cpuinfo") as f: - for line in f: - if "model name" in line: - cpu_name = line.split(":")[1].strip() - break - except Exception: - pass - return { - "cores": cores, - "architecture": sys.platform, - "name": cpu_name - } - - def get_info(): - return { - "platform": sys.platform, - "cpu": get_cpu(), - "ram": get_ram(), - "gpu": get_gpu(), - "battery": get_battery() - } - - return AiraModule("system", { - "info": get_info, - "device_info": get_info, - "gpu": get_gpu, - "battery": get_battery, - "ram": get_ram, - "cpu": get_cpu - }) - -def is_package_installed(pkg_name): - config_dir = os.path.expanduser("~/.config/airalang") - packages_file = os.path.join(config_dir, "installed_packages.json") - if os.path.exists(packages_file): - try: - with open(packages_file, "r", encoding="utf-8") as f: - pkgs = json.load(f) - return pkg_name.lower() in pkgs - except Exception: - pass - return False - -def create_youtube_module(): - if not is_package_installed("youtube") and not is_package_installed("yt"): - raise ImportError( - "\033[1;31m[AiraLang Package Error]:\033[0m Module 'youtube' is not installed!\n" - "\033[1;36mπŸ’‘ Run:\033[0m aira install youtube" - ) - try: - import yt_dlp - except ImportError: - raise ImportError( - "\033[1;31m[AiraLang Package Error]:\033[0m Backend engine 'yt-dlp' is missing.\n" - "\033[1;36mπŸ’‘ Run:\033[0m aira install youtube" - ) - - def get_video(url): - url_str = str(url).strip() - ydl_opts = { - 'quiet': True, - 'no_warnings': True, - 'extract_flat': True, - 'skip_download': True, - 'extractor_args': {'youtube': {'player_client': ['android', 'ios', 'web']}} - } - try: - with yt_dlp.YoutubeDL(ydl_opts) as ydl: - info = ydl.extract_info(url_str, download=False) - except Exception as e: - raise RuntimeError(f"Aira YouTube Error: Failed to fetch video info: {e}") - - title = info.get("title", "YouTube Video") - duration = info.get("duration", 0) - author = info.get("uploader", info.get("channel", "Unknown Channel")) - views = info.get("view_count", 0) - - def get_stream(fmt="mp4"): - fmt_str = str(fmt).lower().strip() - - def download(save_path=None): - if save_path: - outtmpl = str(save_path).strip() - else: - outtmpl = f"{title}.%(ext)s" - - parent_dir = os.path.dirname(outtmpl) - if parent_dir: - os.makedirs(parent_dir, exist_ok=True) - - if fmt_str in ("mp3", "audio", "m4a"): - ydl_dl_opts = { - 'format': 'bestaudio/best/140/251', - 'outtmpl': outtmpl, - 'quiet': False, - 'no_warnings': True, - 'extractor_args': {'youtube': {'player_client': ['android', 'ios', 'web']}} - } - else: - ydl_dl_opts = { - 'format': 'best[ext=mp4]/18/22/b/best', - 'outtmpl': outtmpl, - 'quiet': False, - 'no_warnings': True, - 'extractor_args': {'youtube': {'player_client': ['android', 'ios', 'web']}} - } - - try: - with yt_dlp.YoutubeDL(ydl_dl_opts) as dl: - dl.download([url_str]) - return outtmpl - except Exception as e: - raise RuntimeError(f"Aira YouTube Download Error: {e}") - - return AiraModule("youtube_stream", { - "download": download, - "format": fmt_str - }) - - return AiraModule("youtube_video", { - "title": title, - "duration": duration, - "author": author, - "uploader": author, - "views": views, - "url": url_str, - "stream": get_stream - }) - - def quick_download(url, save_path=None, fmt="mp4"): - video = get_video(url) - st = video.get("stream")(fmt) - return st.get("download")(save_path) - - return AiraModule("youtube", { - "get": get_video, - "video": get_video, - "url": get_video, - "download": quick_download - }) - -def create_term_module(): - COLORS = { - "black": "\033[30m", "red": "\033[31m", "green": "\033[32m", "yellow": "\033[33m", - "blue": "\033[34m", "magenta": "\033[35m", "cyan": "\033[36m", "white": "\033[37m", - "bright_black": "\033[90m", "bright_red": "\033[91m", "bright_green": "\033[92m", - "bright_yellow": "\033[93m", "bright_blue": "\033[94m", "bright_magenta": "\033[95m", - "bright_cyan": "\033[96m", "bright_white": "\033[97m", - "bold": "\033[1m", "dim": "\033[2m", "italic": "\033[3m", "underline": "\033[4m", - "reset": "\033[0m" - } - - def color(col_name, text): - c = COLORS.get(str(col_name).lower(), "") - return f"{c}{text}\033[0m" - - def rainbow(text): - rainbow_colors = ["\033[91m", "\033[93m", "\033[92m", "\033[96m", "\033[94m", "\033[95m"] - res = [] - for i, ch in enumerate(str(text)): - c = rainbow_colors[i % len(rainbow_colors)] - res.append(f"{c}{ch}") - res.append("\033[0m") - return "".join(res) - - def box(title, content=None, color_name="cyan", width=50): - w = max(int(width), len(str(title)) + 6) - c = COLORS.get(str(color_name).lower(), "\033[36m") - reset = "\033[0m" - top = f"{c}β”Œ{'─' * (w - 2)}┐{reset}" - title_line = f"{c}β”‚{reset} {COLORS.get('bold', '')}{str(title).center(w - 4)}{reset} {c}β”‚{reset}" - div = f"{c}β”œ{'─' * (w - 2)}─{reset}" - bot = f"{c}β””{'─' * (w - 2)}β”˜{reset}" - lines = [top, title_line] - if content: - lines.append(div) - if isinstance(content, list): - for item in content: - item_str = str(item) - if len(item_str) > w - 4: item_str = item_str[:w-7] + "..." - lines.append(f"{c}β”‚{reset} {item_str.ljust(w - 4)} {c}β”‚{reset}") - else: - for line in str(content).splitlines(): - if len(line) > w - 4: line = line[:w-7] + "..." - lines.append(f"{c}β”‚{reset} {line.ljust(w - 4)} {c}β”‚{reset}") - lines.append(bot) - res = "\n".join(lines) - print(res) - return res - - def table(headers, rows): - headers = [str(h) for h in headers] - str_rows = [[str(cell) for cell in row] for row in rows] - col_widths = [len(h) for h in headers] - for row in str_rows: - for i, cell in enumerate(row): - if i < len(col_widths): - col_widths[i] = max(col_widths[i], len(cell)) - else: - col_widths.append(len(cell)) - sep = "β”Œ" + "┬".join("─" * (w + 2) for w in col_widths) + "┐" - mid_sep = "β”œ" + "β”Ό".join("─" * (w + 2) for w in col_widths) + "─" - bot_sep = "β””" + "β”΄".join("─" * (w + 2) for w in col_widths) + "β”˜" - header_line = "β”‚ " + " β”‚ ".join(headers[i].ljust(col_widths[i]) for i in range(len(headers))) + " β”‚" - lines = [sep, f"\033[1;36m{header_line}\033[0m", mid_sep] - for row in str_rows: - row_padded = [row[i].ljust(col_widths[i]) if i < len(row) else "".ljust(col_widths[i]) for i in range(len(col_widths))] - lines.append("β”‚ " + " β”‚ ".join(row_padded) + " β”‚") - lines.append(bot_sep) - res = "\n".join(lines) - print(res) - return res - - def spinner(message="Working...", seconds=1.5): - frames = ["β ‹", "β ™", "β Ή", "β Έ", "β Ό", "β ΄", "β ¦", "β §", "β ‡", "⠏"] - end_time = time.time() + float(seconds) - i = 0 - while time.time() < end_time: - frame = frames[i % len(frames)] - sys.stdout.write(f"\r\033[36m{frame}\033[0m {message}") - sys.stdout.flush() - time.sleep(0.08) - i += 1 - sys.stdout.write(f"\r\033[32mβœ”\033[0m {message}\n") - sys.stdout.flush() - return True - - def clear(): - os.system('clear' if os.name != 'nt' else 'cls') - return True - - return AiraModule("term", { - "color": color, - "rainbow": rainbow, - "box": box, - "table": table, - "spinner": spinner, - "clear": clear - }) - -def create_webhook_module(): - def send(url, payload, headers=None, timeout=10.0): - if not isinstance(payload, (dict, list, str)): - payload = {"data": str(payload)} - body_data = json.dumps(payload).encode('utf-8') if not isinstance(payload, str) else payload.encode('utf-8') - req_headers = {"Content-Type": "application/json", "User-Agent": "AiraLang-Webhook/1.5.0"} - if isinstance(headers, dict): - req_headers.update(headers) - req = urllib.request.Request(str(url), data=body_data, headers=req_headers, method="POST") - try: - with urllib.request.urlopen(req, timeout=float(timeout)) as resp: - resp_text = resp.read().decode('utf-8') - try: - return {"status": resp.status, "data": json.loads(resp_text), "ok": True} - except: - return {"status": resp.status, "data": resp_text, "ok": True} - except urllib.error.HTTPError as e: - return {"status": e.code, "error": str(e), "ok": False} - except Exception as e: - return {"status": 0, "error": str(e), "ok": False} - - def listen(port, callback_handler): - from http.server import HTTPServer, BaseHTTPRequestHandler - class WebhookHandler(BaseHTTPRequestHandler): - def do_POST(self): - content_len = int(self.headers.get('Content-Length', 0)) - post_body = self.rfile.read(content_len).decode('utf-8') - try: - data = json.loads(post_body) - except: - data = post_body - req_obj = {"body": data, "headers": dict(self.headers), "path": self.path} - if hasattr(callback_handler, 'call'): - res = callback_handler(req_obj) - elif callable(callback_handler): - res = callback_handler(req_obj) - else: - res = {"received": True} - self.send_response(200) - self.send_header('Content-Type', 'application/json') - self.end_headers() - self.wfile.write(json.dumps(res if isinstance(res, (dict, list)) else {"status": "ok"}).encode()) - def log_message(self, format, *args): - pass - server = HTTPServer(('0.0.0.0', int(port)), WebhookHandler) - t = threading.Thread(target=server.serve_forever, daemon=True) - t.start() - return {"listening": True, "port": int(port)} - - return AiraModule("webhook", { - "send": send, - "listen": listen - }) - -def create_bot_module(): - def telegram_send(bot_token, chat_id, message, parse_mode="HTML"): - url = f"https://api.telegram.org/bot{bot_token}/sendMessage" - payload = {"chat_id": chat_id, "text": str(message), "parse_mode": parse_mode} - data = json.dumps(payload).encode('utf-8') - req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"}) - try: - with urllib.request.urlopen(req, timeout=10) as resp: - return json.loads(resp.read().decode('utf-8')) - except Exception as e: - return {"ok": False, "error": str(e)} - - def discord_send(webhook_url, content, username="Aira Bot", avatar_url=None): - payload = {"content": str(content), "username": username} - if avatar_url: - payload["avatar_url"] = avatar_url - data = json.dumps(payload).encode('utf-8') - req = urllib.request.Request(str(webhook_url), data=data, headers={"Content-Type": "application/json", "User-Agent": "AiraLang-Bot/1.5.0"}) - try: - with urllib.request.urlopen(req, timeout=10) as resp: - return {"ok": True, "status": resp.status} - except Exception as e: - return {"ok": False, "error": str(e)} - - return AiraModule("bot", { - "telegram_send": telegram_send, - "telegram": telegram_send, - "discord_send": discord_send, - "discord": discord_send - }) - -def create_env_module(): - def load(filepath=".env"): - if not os.path.exists(filepath): - return False - with open(filepath, "r", encoding="utf-8") as f: - for line in f: - line = line.strip() - if not line or line.startswith("#"): - continue - if "=" in line: - k, v = line.split("=", 1) - k = k.strip() - v = v.strip().strip('"').strip("'") - os.environ[k] = v - return True - - def get_env(key, default=None): - return os.environ.get(str(key), default) - - def set_env(key, value): - os.environ[str(key)] = str(value) - return True - - def all_env(): - return dict(os.environ) - - return AiraModule("env", { - "load": load, - "get": get_env, - "set": set_env, - "all": all_env - }) - -def create_serve_module(): - from http.server import HTTPServer, BaseHTTPRequestHandler - routes = {} - - def route(path, handler_fn, method="GET"): - routes[(str(method).upper(), str(path))] = handler_fn - return True - - def get_route(path, handler_fn): - return route(path, handler_fn, "GET") - - def post_route(path, handler_fn): - return route(path, handler_fn, "POST") - - class AiraHttpServerHandler(BaseHTTPRequestHandler): - def _handle(self, method): - parsed = urllib.parse.urlparse(self.path) - clean_path = parsed.path - handler = routes.get((method, clean_path)) - if not handler: - handler = routes.get(("*", clean_path)) - if not handler: - self.send_response(404) - self.send_header('Content-Type', 'application/json') - self.end_headers() - self.wfile.write(json.dumps({"error": "Not Found", "path": clean_path}).encode()) - return - req_data = None - if method in ("POST", "PUT", "PATCH"): - length = int(self.headers.get('Content-Length', 0)) - raw_body = self.rfile.read(length).decode('utf-8', errors='ignore') - try: req_data = json.loads(raw_body) - except: req_data = raw_body - query_params = dict(urllib.parse.parse_qsl(parsed.query)) - req_obj = { - "path": clean_path, - "method": method, - "query": query_params, - "body": req_data, - "headers": dict(self.headers) - } - try: - if callable(handler): - res = handler(req_obj) - else: - res = str(handler) - except Exception as e: - self.send_response(500) - self.send_header('Content-Type', 'application/json') - self.end_headers() - self.wfile.write(json.dumps({"error": str(e)}).encode()) - return - self.send_response(200) - if isinstance(res, (dict, list)): - self.send_header('Content-Type', 'application/json') - body_bytes = json.dumps(res).encode('utf-8') - elif isinstance(res, str) and (res.strip().startswith("