feat(v1.3.0): add else-if, shorthand operators, sqlite & net modules, builtins, and custom imports

This commit is contained in:
Adam Eehan committed 2026-08-30 14:15:38 +05:30
1 parent 243b52e2cb
commit 8a1ac0b814
8 files changed
+396 -65

No files matched your search

+108 -17
View File
@@ -1,5 +1,5 @@
# 🌟 AiraLang (v1.2.0 Next-Gen Engine)
> **The High-Performance, Lightweight & Expressive Programming Language for Creators & Developers**
# 🌟 AiraLang (v1.3.0 Pro Edition)
> **The High-Performance, Expressive & Modular Scripting Language for Creators & Developers**
> **Author & Creator:** Adam Eehan (Founder & CEO, Aira Group of Technology) 👑
---
@@ -34,14 +34,37 @@ let power = 100;
say "Creator: " + name;
```
### 2. For..In Loops & Range
### 2. Shorthand Operators (`+=`, `-=`, `*=`, `/=`)
```aira
let count = 10;
count += 5; # count is now 15
count *= 2; # count is now 30
count -= 10; # count is now 20
```
### 3. Conditionals (`if`, `else if`, `else`)
```aira
let marks = 85;
if (marks >= 90) {
say "Grade: S (Master)";
} else if (marks >= 80) {
say "Grade: A (Pro)";
} else if (marks >= 50) {
say "Grade: B";
} else {
say "Grade: Pass";
}
```
### 4. For..In Loops & Range
```aira
let tools = ["Termux", "AiraLang", "CyberGuard"];
for tool in tools {
say "Tool: " + tool;
}
# Looping using range(start, end)
# Looping through numbers using range(start, end)
for i in range(1, 6) {
if (i == 3) {
continue; # skip 3
@@ -50,7 +73,17 @@ for i in range(1, 6) {
}
```
### 3. Object-Oriented Programming (OOP)
### 5. Functions & Return Values (`fn`)
```aira
fn calculate_power(base, multiplier) {
return base * multiplier;
}
let result = calculate_power(50, 2);
say "Total Power: " + result;
```
### 6. Object-Oriented Programming (OOP)
```aira
class Agent {
fn init(name, role) {
@@ -67,7 +100,7 @@ let adam = new Agent("Adam Eehan", "CEO");
say adam.introduce();
```
### 4. Exception Handling (Try / Catch / Throw)
### 7. Exception Handling (Try / Catch / Throw)
```aira
try {
throw "Security Access Denied";
@@ -76,7 +109,7 @@ try {
}
```
### 5. Native String & List Methods
### 8. Native String & List Methods
```aira
let text = " aira technology ";
say text.trim().upper(); # "AIRA TECHNOLOGY"
@@ -86,25 +119,83 @@ langs.push("AiraLang");
say langs.join(" -> "); # "C++ -> Python -> AiraLang"
```
### 6. Standard Library Modules
### 9. Built-in Utilities
```aira
# Network / HTTP
import "http";
let res = http.get("https://httpbin.org/get");
let numbers = [10, 50, 5, 90, 25];
say "Max: " + max(numbers);
say "Min: " + min(numbers);
say "Sum: " + sum(numbers);
say "Abs: " + abs(-42);
```
# Cryptography & Hashing
---
## 📦 Standard Library Modules
### 🗄️ SQLite Database Module (`sqlite`)
```aira
import "sqlite";
let db = sqlite.open("data.db");
db.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, role TEXT);");
db.insert("users", {"name": "Adam Eehan", "role": "Founder & CEO"});
let rows = db.query("SELECT * FROM users;");
for row in rows {
say "User: " + row["name"] + " | Role: " + row["role"];
}
db.close();
```
### 🔌 Networking & Sockets Module (`net`)
```aira
import "net";
say "Local Machine IP: " + net.local_ip();
say "Resolved IP: " + net.resolve("google.com");
# Port Scanner
let is_open = net.scan_port("google.com", 443);
say "Port 443 is open: " + is_open;
```
### 🔐 Cryptography & Hashing (`crypto`)
```aira
import "crypto";
let hash = crypto.sha256("admin123");
let b64 = crypto.b64encode("secret");
let b64 = crypto.b64encode("secret_token");
say "SHA-256: " + hash;
say "Base64: " + b64;
say "Decoded: " + crypto.b64decode(b64);
```
# System & OS
### 🌐 HTTP Client (`http`)
```aira
import "http";
let res = http.get("https://httpbin.org/get");
say res;
```
### 📂 OS, File, Math, Time & JSON
```aira
import "os";
let out = os.cmd("uname -a");
# Math & Time & JSON
import "file";
import "math";
import "time";
import "json";
say "OS Kernel: " + os.cmd("uname -o");
say "Sqrt: " + math.sqrt(144);
say "Current Time: " + time.now();
```
### 🧩 Custom `.aira` File Imports
```aira
# Import functions from another file (e.g., utils.aira)
import "utils.aira";
let output = utils.my_custom_function();
```
---
+11
View File
@@ -0,0 +1,11 @@
# ===============================================
# 🌟 Math Helper Library (Module Import Test)
# ===============================================
fn multiply(a, b) {
return a * b;
}
fn power_cube(x) {
return x * x * x;
}
+85
View File
@@ -0,0 +1,85 @@
# ==========================================================
# 🌟 AiraLang v1.3.0 Pro Edition Feature Suite Test
# 👑 Creator: Adam Eehan (Aira Group of Technology)
# ==========================================================
say "🔥 AiraLang v1.3.0 Feature Suite Test Running...";
say "=================================================";
# 1. Else-If Multi-branch test
say "[1] Testing Else-If Chaining:";
let score = 85;
if (score >= 90) {
say " Grade: S (Top Class)";
} else if (score >= 80) {
say " ✅ Grade: A (Pro Passed!)";
} else if (score >= 50) {
say " Grade: B";
} else {
say " Grade: Fail";
}
# 2. Shorthand Assignment Operators
say "-------------------------------------------------";
say "[2] Testing Shorthand Operators (+=, -=, *=, /=):";
let count = 10;
count += 5;
say " Count after += 5 : " + count;
count *= 2;
say " Count after *= 2 : " + count;
count -= 10;
say " Count after -= 10 : " + count;
count /= 2;
say " Count after /= 2 : " + count;
# 3. Built-in Utilities (min, max, sum, abs)
say "-------------------------------------------------";
say "[3] Testing Built-in Math & List Functions:";
let numbers = [12, 45, 7, 89, 23];
say " Max number : " + max(numbers);
say " Min number : " + min(numbers);
say " Sum of list: " + sum(numbers);
say " Abs(-99) : " + abs(-99);
# 4. SQLite Database Module Test
say "-------------------------------------------------";
say "[4] Testing SQLite Database Module:";
import "sqlite";
let db_file = "test_aira.db";
let db = sqlite.open(db_file);
db.execute("CREATE TABLE IF NOT EXISTS developers (id INTEGER PRIMARY KEY, name TEXT, role TEXT);");
db.execute("DELETE FROM developers;");
db.insert("developers", {"name": "Adam Eehan", "role": "CEO & Founder"});
db.insert("developers", {"name": "Aira AI", "role": "Autonomous Companion"});
let rows = db.query("SELECT * FROM developers;");
for row in rows {
say " 📁 DB Record -> Name: " + row["name"] + " | Role: " + row["role"];
}
db.close();
import "file";
file.delete(db_file);
say " ✅ SQLite database created, queried, and cleaned up!";
# 5. Networking (Net) Module Test
say "-------------------------------------------------";
say "[5] Testing Net / Socket Module:";
import "net";
let my_ip = net.local_ip();
say " Local Machine IP : " + my_ip;
let google_ip = net.resolve("google.com");
say " DNS Resolve (google.com) : " + google_ip;
let port_80 = net.scan_port("google.com", 80);
say " Port 80 Open on google.com : " + port_80;
# 6. Custom .aira File Import Test
say "-------------------------------------------------";
say "[6] Testing Custom .aira Module Import:";
import "examples/math_helper.aira";
let mult_res = math_helper.multiply(6, 7);
let cube_res = math_helper.power_cube(4);
say " math_helper.multiply(6, 7) : " + mult_res;
say " math_helper.power_cube(4) : " + cube_res;
say "=================================================";
say "🎉 ALL v1.3.0 FEATURES 100% OPERATIONAL & VERIFIED!";
+1 -2
View File
@@ -8,7 +8,7 @@ from lexer import Lexer
from parser import Parser
from evaluator import Evaluator
VERSION = "1.2.0 (Next-Gen Engine)"
VERSION = "1.3.0 (Pro Edition)"
AUTHOR = "Adam Eehan (Aira Group of Technology)"
ASCII_BANNER = f"""\033[1;36m
@@ -27,7 +27,6 @@ ASCII_BANNER = f"""\033[1;36m
"""
def is_balanced(code):
# Check if { }, ( ), [ ] are balanced
in_single_quote = False
in_double_quote = False
in_comment = False
+13 -4
View File
@@ -115,6 +115,10 @@ class Evaluator:
self.global_env.set("num", lambda x: float(x) if '.' in str(x) else int(x))
self.global_env.set("input", lambda prompt="": input(prompt))
self.global_env.set("range", lambda start, stop=None, step=1: list(range(int(start), int(stop), int(step))) if stop is not None else list(range(int(start))))
self.global_env.set("min", lambda *args: min(args[0]) if len(args) == 1 and isinstance(args[0], (list, tuple)) else min(*args))
self.global_env.set("max", lambda *args: max(args[0]) if len(args) == 1 and isinstance(args[0], (list, tuple)) else max(*args))
self.global_env.set("abs", lambda x: abs(x))
self.global_env.set("sum", lambda lst: sum(lst) if isinstance(lst, (list, tuple)) else lst)
self.global_env.set("append", lambda lst, item: lst.append(item) or lst)
self.global_env.set("pop", lambda lst, idx=-1: lst.pop(idx))
self.global_env.set("split", lambda s, sep=" ": str(s).split(sep))
@@ -147,8 +151,14 @@ class Evaluator:
module_instance = BUILTIN_MODULES[mod_name]()
env.set(mod_name, module_instance)
return module_instance
elif os.path.exists(mod_name):
with open(mod_name, "r", encoding="utf-8") as f:
# File import check (.aira or .py)
target_path = mod_name
if not os.path.exists(target_path) and not target_path.endswith(".aira"):
target_path = mod_name + ".aira"
if os.path.exists(target_path):
with open(target_path, "r", encoding="utf-8") as f:
code = f.read()
from lexer import Lexer
from parser import Parser
@@ -156,7 +166,7 @@ class Evaluator:
sub_ast = Parser(sub_tokens).parse()
mod_env = Environment(parent=self.global_env)
self.eval_node(sub_ast, mod_env)
base_name = os.path.splitext(os.path.basename(mod_name))[0]
base_name = os.path.splitext(os.path.basename(target_path))[0]
aira_mod = AiraModule(base_name, mod_env.values)
env.set(base_name, aira_mod)
return aira_mod
@@ -419,7 +429,6 @@ class Evaluator:
if isinstance(callee, AiraFunction):
return callee.call(self, args)
elif isinstance(callee, AiraClass):
# allow calling class directly as constructor ClassName(args)
return callee.instantiate(self, args)
elif callable(callee):
return callee(*args)
+34 -29
View File
@@ -1,35 +1,40 @@
import re
TOKEN_TYPES = [
("COMMENT", r"#.*"),
("WHITESPACE", r"[ \t\r\n]+"),
("NUMBER", r"\d+(\.\d+)?"),
("STRING", r'("([^"\\]|\\.)*"|\'([^\'\\]|\\.)*\')'),
("KEYWORD", r"\b(let|say|print|if|else|while|for|in|fn|return|import|load|use|true|false|null|and|or|not|try|catch|throw|class|new|this|break|continue)\b"),
("IDENTIFIER", r"[a-zA-Z_][a-zA-Z0-9_]*"),
("EQ_EQ", r"=="),
("NOT_EQ", r"!="),
("LTE", r"<="),
("GTE", r">="),
("ASSIGN", r"="),
("PLUS", r"\+"),
("MINUS", r"-"),
("MUL", r"\*"),
("DIV", r"/"),
("MOD", r"%"),
("LT", r"<"),
("GT", r">"),
("NOT", r"!"),
("LPAREN", r"\("),
("RPAREN", r"\)"),
("LBRACE", r"\{"),
("RBRACE", r"\}"),
("LBRACKET", r"\["),
("RBRACKET", r"\]"),
("COLON", r":"),
("SEMICOLON", r";"),
("COMMA", r","),
("DOT", r"\."),
("COMMENT", r"#.*"),
("WHITESPACE", r"[ \t\r\n]+"),
("NUMBER", r"\d+(\.\d+)?"),
("STRING", r'("([^"\\]|\\.)*"|\'([^\'\\]|\\.)*\')'),
("KEYWORD", r"\b(let|say|print|if|else|while|for|in|fn|return|import|load|use|true|false|null|and|or|not|try|catch|throw|class|new|this|break|continue)\b"),
("IDENTIFIER", r"[a-zA-Z_][a-zA-Z0-9_]*"),
("PLUS_ASSIGN", r"\+="),
("MINUS_ASSIGN", r"-="),
("MUL_ASSIGN", r"\*="),
("DIV_ASSIGN", r"/="),
("MOD_ASSIGN", r"%="),
("EQ_EQ", r"=="),
("NOT_EQ", r"!="),
("LTE", r"<="),
("GTE", r">="),
("ASSIGN", r"="),
("PLUS", r"\+"),
("MINUS", r"-"),
("MUL", r"\*"),
("DIV", r"/"),
("MOD", r"%"),
("LT", r"<"),
("GT", r">"),
("NOT", r"!"),
("LPAREN", r"\("),
("RPAREN", r"\)"),
("LBRACE", r"\{"),
("RBRACE", r"\}"),
("LBRACKET", r"\["),
("RBRACKET", r"\]"),
("COLON", r":"),
("SEMICOLON", r";"),
("COMMA", r","),
("DOT", r"\."),
]
class Token:
+22 -8
View File
@@ -41,11 +41,11 @@ class Parser:
if self.match("SEMICOLON"):
return None
# standalone block statement: `{ stmt1; stmt2; }`
# Standalone block statement: `{ stmt1; stmt2; }`
if tok.type == "LBRACE":
return self.parse_block_or_statement()
# import / load / use statement: `import os;`, `import "math";`
# import / load / use statement: `import os;`, `import "math";`, `import "helper.aira";`
if tok.type in ("IMPORT", "LOAD", "USE"):
self.pos += 1
if self.current().type in ("STRING", "IDENTIFIER"):
@@ -75,7 +75,7 @@ class Parser:
self.match("SEMICOLON")
return LetStatementNode(name_tok.value, expr, tok.line)
# if statement: `if (cond) { ... } else { ... }`
# if statement: `if (cond) { ... } else if (cond2) { ... } else { ... }`
if tok.type == "IF":
self.pos += 1
has_paren = self.match("LPAREN")
@@ -85,7 +85,10 @@ class Parser:
then_branch = self.parse_block_or_statement()
else_branch = None
if self.match("ELSE"):
else_branch = self.parse_block_or_statement()
if self.current().type == "IF":
else_branch = self.parse_statement()
else:
else_branch = self.parse_block_or_statement()
return IfStatementNode(cond, then_branch, else_branch, tok.line)
# while statement: `while (cond) { ... }`
@@ -98,7 +101,7 @@ class Parser:
body = self.parse_block_or_statement()
return WhileStatementNode(cond, body, tok.line)
# for statement: `for item in items { ... }` or `for (item in items) { ... }` or `for (let item in items) { ... }`
# for statement: `for item in items { ... }`
if tok.type == "FOR":
self.pos += 1
has_paren = self.match("LPAREN")
@@ -166,7 +169,6 @@ class Parser:
methods = {}
while self.current().type != "RBRACE" and self.current().type != "EOF":
if self.match("FN") or self.current().type == "IDENTIFIER":
# allow either `fn name()` or `name()`
if self.tokens[self.pos - 1].type != "FN":
m_name_tok = self.expect("IDENTIFIER")
else:
@@ -197,11 +199,23 @@ class Parser:
self.match("SEMICOLON")
return ReturnStatementNode(expr, tok.line)
# expression / assignment statement
# expression / assignment / shorthand assignment statement
expr = self.parse_expression()
if self.match("ASSIGN"):
assign_op = self.match("ASSIGN", "PLUS_ASSIGN", "MINUS_ASSIGN", "MUL_ASSIGN", "DIV_ASSIGN", "MOD_ASSIGN")
if assign_op:
val_expr = self.parse_expression()
self.match("SEMICOLON")
if assign_op.type != "ASSIGN":
bin_op_symbol = {
"PLUS_ASSIGN": "+",
"MINUS_ASSIGN": "-",
"MUL_ASSIGN": "*",
"DIV_ASSIGN": "/",
"MOD_ASSIGN": "%"
}[assign_op.type]
val_expr = BinaryOpNode(expr, bin_op_symbol, val_expr, assign_op.line)
if isinstance(expr, IdentifierNode):
return AssignStatementNode(expr.name, val_expr, tok.line)
elif isinstance(expr, IndexAccessNode):
+122 -5
View File
@@ -6,6 +6,8 @@ import json
import random
import hashlib
import base64
import socket
import sqlite3
import urllib.request
import urllib.parse
@@ -19,6 +21,119 @@ class AiraModule:
return self.methods[prop_name]
raise AttributeError(f"AiraLang Module '{self.name}' has no method or property '{prop_name}'")
class AiraSQLiteDB:
def __init__(self, db_path):
self.db_path = db_path
self.conn = sqlite3.connect(db_path)
self.conn.row_factory = sqlite3.Row
def execute(self, sql, params=None):
cursor = self.conn.cursor()
if params:
cursor.execute(sql, tuple(params) if isinstance(params, list) else (params,))
else:
cursor.execute(sql)
self.conn.commit()
return cursor.rowcount
def query(self, sql, params=None):
cursor = self.conn.cursor()
if params:
cursor.execute(sql, tuple(params) if isinstance(params, list) else (params,))
else:
cursor.execute(sql)
rows = cursor.fetchall()
result = []
for r in rows:
result.append({k: r[k] for k in r.keys()})
return result
def insert(self, table, data_dict):
if not isinstance(data_dict, dict):
raise TypeError("sqlite.insert requires a dictionary of column: value")
columns = ", ".join(data_dict.keys())
placeholders = ", ".join(["?"] * len(data_dict))
sql = f"INSERT INTO {table} ({columns}) VALUES ({placeholders})"
return self.execute(sql, list(data_dict.values()))
def close(self):
self.conn.close()
return True
def get(self, prop_name):
if hasattr(self, prop_name):
return getattr(self, prop_name)
raise AttributeError(f"SQLite DB object has no property '{prop_name}'")
def create_sqlite_module():
def open_db(path):
db = AiraSQLiteDB(path)
return AiraModule("sqlite_conn", {
"execute": db.execute,
"query": db.query,
"insert": db.insert,
"close": db.close
})
return AiraModule("sqlite", {
"open": open_db,
"connect": open_db
})
def create_net_module():
def scan_port(host, port, timeout=2.0):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(float(timeout))
result = s.connect_ex((str(host), int(port)))
s.close()
return result == 0
except Exception:
return False
def scan_ports(host, start_port, end_port, timeout=1.0):
open_ports = []
for p in range(int(start_port), int(end_port) + 1):
if scan_port(host, p, timeout):
open_ports.append(p)
return open_ports
def resolve(domain):
try:
return socket.gethostbyname(str(domain))
except Exception as e:
return f"Error: {e}"
def local_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
except Exception:
return "127.0.0.1"
def tcp_send(host, port, message, timeout=5.0):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(float(timeout))
s.connect((str(host), int(port)))
s.sendall(str(message).encode('utf-8'))
data = s.recv(4096)
s.close()
return data.decode('utf-8', errors='ignore')
except Exception as e:
return f"Socket Error: {e}"
return AiraModule("net", {
"scan_port": scan_port,
"scan_ports": scan_ports,
"resolve": resolve,
"local_ip": local_ip,
"tcp_send": tcp_send
})
def create_file_module():
def read_file(path):
with open(path, "r", encoding="utf-8") as f:
@@ -117,7 +232,7 @@ def create_json_module():
def create_http_module():
def get(url, headers=None):
req_headers = {"User-Agent": "AiraLang/1.1 (Termux; Android)"}
req_headers = {"User-Agent": "AiraLang/1.3 (Termux; Android)"}
if isinstance(headers, dict):
req_headers.update(headers)
req = urllib.request.Request(url, headers=req_headers)
@@ -128,7 +243,7 @@ def create_http_module():
raise RuntimeError(f"HTTP GET Error: {e}")
def post(url, data_payload=None, headers=None):
req_headers = {"User-Agent": "AiraLang/1.1 (Termux; Android)"}
req_headers = {"User-Agent": "AiraLang/1.3 (Termux; Android)"}
if isinstance(headers, dict):
req_headers.update(headers)
encoded_data = None
@@ -145,7 +260,7 @@ def create_http_module():
raise RuntimeError(f"HTTP POST Error: {e}")
def download(url, dest_path):
req = urllib.request.Request(url, headers={"User-Agent": "AiraLang/1.1"})
req = urllib.request.Request(url, headers={"User-Agent": "AiraLang/1.3"})
try:
with urllib.request.urlopen(req, timeout=30) as response, open(dest_path, "wb") as out_file:
out_file.write(response.read())
@@ -155,7 +270,7 @@ def create_http_module():
def status(url):
try:
req = urllib.request.Request(url, headers={"User-Agent": "AiraLang/1.1"})
req = urllib.request.Request(url, headers={"User-Agent": "AiraLang/1.3"})
with urllib.request.urlopen(req, timeout=10) as response:
return response.getcode()
except urllib.error.HTTPError as e:
@@ -216,5 +331,7 @@ BUILTIN_MODULES = {
"json": create_json_module,
"http": create_http_module,
"crypto": create_crypto_module,
"string": create_string_module
"string": create_string_module,
"sqlite": create_sqlite_module,
"net": create_net_module
}