<antigravity_prompt>
You are an elite Lead Systems Engineer (Rust/Python) tasked with overhauling the TechScript language. Your objective is to achieve C-like performance in the Rust VM, fix critical memory and safety issues, ensure multi-platform compatibility (Windows, Linux, macOS, Termux), and implement a massive standard library of 300 built-in functions. The language must be "as powerful as Python, but far easier to use", featuring native web generation (use web, style, script), built-in tuples, sets, and instant inline code execution.
Read the extensive architectural plans below, break them down into steps, and execute them autonomously to transform TechScript into a robust, lightning-fast language.
</antigravity_prompt>
Currently, the Rust VM cycle is slow (~2.8s in test cases). The primary cause is the excessive use of Rc<RefCell<Value>> and deep cloning on the stack. We must achieve 0.00s overhead.
The biggest bottleneck is the current Value enum. Every operation invokes heap allocation and borrow-checking, which defeats the purpose of a Rust VM.
- Action: Implement NaN Boxing. A 64-bit IEEE 754 float has 52 bits of mantissa. When the exponent is all 1s (NaN), we can use the mantissa to store pointers, booleans, or type tags.
- Implementation Details:
- If a value is a valid
f64, it represents a float natively. - If it is a NaN, inspect the sign bit and mantissa.
- Tag 1: Boolean (
trueorfalsein the lowest bit). - Tag 2: Null/None.
- Tag 3: Integer (32-bit inline).
- Tag 4: Object Pointer (32-bit index into the Arena).
- If a value is a valid
- The Object Arena: Instead of
Rc<RefCell<T>>, create a flatVec<Object>in the VM. Strings, Lists, Maps, and Instances are stored here. TheValueon the stack is just a 64-bit integer referencing the index in this Arena. - Garbage Collection: Implement a simple Mark-and-Sweep GC. When the Arena reaches capacity, trace from the global variables and the current stack, mark reachable objects, and free the rest.
- Current Flaw:
Vec::pushandVec::popin the mainexecute()loop force capacity checks and pointer indirection on every single instruction. - Action: Replace
stack: Vec<Value>with a fixed-size array:stack: [Value; 2048]. - Execution Loop: Track a raw
stack_top: usize. Thepushoperation becomesself.stack[self.stack_top] = val; self.stack_top += 1;. This compiles down to raw C-like pointer arithmetic without bounds checking (if you guarantee stack depth during compilation).
- Current Flaw: Looking up variables involves hashing dynamically allocated
Strings. - Action: Create a
StringInterner. When the compiler encounters a string literal or variable name, it hashes it once and stores it. The compiler emits an integer ID. The VM'sglobalsmap changes fromHashMap<String, Value>toHashMap<u32, Value>, making variable lookups near-instantaneous.
- File:
runtime/src/vm.rs - Issue:
let op: OpCode = unsafe { std::mem::transmute(byte) }; - Risk: If bytecode is corrupted or a jump offset points to an argument instead of an opcode, this causes Undefined Behavior (UB) and a hard crash (Segmentation Fault).
- Fix: Implement
TryFrom<u8>forOpCode. Use a safematch byteto convert it. If it fails, halt the VM gracefully with aTechError::InvalidBytecodemessage.
- Break/Continue Logic: The
Breakstatement currently compiles asOpCode::Return.- Fix in
compiler.rs: Introduce aLoopScopestruct tracking the current loop's start instruction index and a list of jump instruction indices that need to be patched at the end of the loop. Continueshould emit an unconditional jump backward to the loop start.Breakshould emit an unconditional jump forward, to be patched when the loop ends.
- Fix in
- Missing Operators: Implement
is(identity check, comparing Arena IDs, not values),in(collection containment via a native loop), andtypeof(returning an interned string of the object type) invm.rs.
- File:
scripts/setup.bat - Issue:
setx PATH "!SCRIPTS_DIR!;%PATH%"destroys user PATHs longer than 1024 characters, potentially breaking Windows installations. - Fix: Replace the
.batPATH injection. Call a PowerShell one-liner that uses.NETAPIs, which do not have the 1024 limit:powershell -Command "[Environment]::SetEnvironmentVariable('PATH', $newPath, 'User')"
- Goal: Allow users to run code directly from the terminal without creating a
.txsfile. Ideal for quick math, testing features, or pipeline scripting. - Command Format:
tech "[[[ say 'hello world' ]]]" - Implementation:
- In
runtime/src/main.rs, parsestd::env::args(). - If
args[1]starts with[[[and ends with]]], slice the inner string. - Pass this string directly to
Lexer::new(inner_code, "<inline>"). - Bypass file I/O entirely and invoke the VM immediately.
- In
- Goal: Provide read-only arrays, identical to Python.
- Implementation: Add
OpCode::BuildTuple. Tuples use(1, 2, 3)syntax. They differ from lists[1, 2, 3]because they lack mutability methods (append,pop). Because their size is fixed, they can be allocated more tightly in the Arena, making them significantly faster and safer for passing fixed data.
The use web functionality must be natively integrated into Rust, utilizing high-speed HTTP servers to generate apps instantly, bypassing the need for Python's http.server.
The WebPage object must provide chained, easy-to-read DOM generators.
page = WebPage("App")page.style("body", {"background": "#000", "color": "#fff"})page.script("console.log('App loaded');")page.body([ h1("Hello"), button("Click Me") ])- Security: All HTML content injected via text arguments must be escaped automatically (converting
<to<, etc.) to prevent XSS. A specialweb.raw()function can bypass this.
- Action: Add the
tiny_httpcrate toCargo.toml. - Execution:
page.run(8080)spawns a background thread running a TCP server. It serves the rendered HTML from memory, avoiding temporary file creation. - Security: It must bind strictly to
127.0.0.1(localhost) to prevent local network snooping, a flaw present in the original Python implementation.
To make TechScript as powerful as Python but far easier to use, the Rust runtime must pre-register these 300 built-in functions. They must be injected into the VM's global environment upon startup.
print(*args): Print values to stdout without a newline.say(*args): Print values to stdout with a newline.input(prompt): Ask user for CLI input and block.type(obj): Return the string type name of an object.id(obj): Return the unique memory arena ID of an object.hash(obj): Return a deterministic hash integer.len(obj): Return length of string, list, map, or tuple.eval(str): Evaluate a string as TechScript code.exit(code): Terminate the VM cleanly.sleep(ms): Pause execution for N milliseconds.time(): Return current UNIX timestamp in seconds.time_ms(): Return current UNIX timestamp in milliseconds.clear(): Clear the terminal screen (cross-platform).assert(cond, msg): Throw error if condition is false.panic(msg): Abort the program immediately.is_defined(name): Check if a global variable exists.clone(obj): Deep copy an object.address_of(obj): Get memory address (for debugging).gc_collect(): Force a garbage collection cycle.version(): Return the TechScript engine version string.callable(obj): True if object is a function or method.hasattr(obj, name): True if object has property.getattr(obj, name): Get property by string name.setattr(obj, name, val): Set property by string name.delattr(obj, name): Delete property by string name.
math.abs(n): Absolute value.math.round(n, places): Round to decimal places.math.floor(n): Round down to nearest int.math.ceil(n): Round up to nearest int.math.trunc(n): Truncate decimal part.math.min(a, b): Lowest of two numbers.math.max(a, b): Highest of two numbers.math.clamp(x, min, max): Restrict value to range.math.sum(list): Sum of all numbers in list.math.sqrt(n): Square root.math.cbrt(n): Cube root.math.pow(base, exp): Exponential power.math.exp(n): Euler's number raised to power.math.log(n): Natural logarithm.math.log10(n): Base-10 logarithm.math.log2(n): Base-2 logarithm.math.sin(rad): Sine.math.cos(rad): Cosine.math.tan(rad): Tangent.math.asin(n): Arc sine.math.acos(n): Arc cosine.math.atan(n): Arc tangent.math.atan2(y, x): Arc tangent with two parameters.math.sinh(rad): Hyperbolic sine.math.cosh(rad): Hyperbolic cosine.math.tanh(rad): Hyperbolic tangent.math.degrees(rad): Convert radians to degrees.math.radians(deg): Convert degrees to radians.math.is_nan(n): Check if Not-a-Number.math.is_inf(n): Check if Infinite.math.is_even(n): Check if integer is even.math.is_odd(n): Check if integer is odd.math.sign(n): Returns -1, 0, or 1.math.gcd(a, b): Greatest common divisor.math.lcm(a, b): Least common multiple.math.factorial(n): Factorial of integer.math.mean(list): Average of list.math.median(list): Median of list.math.mode(list): Most common value.math.comb(n, k): Number of combinations.math.perm(n, k): Number of permutations.math.hypot(x, y): Euclidean distance.math.isclose(a, b, tol): True if a and b are close.math.PI: Constant 3.1415926535...math.E: Constant 2.7182818284...
str.upper(): Convert to uppercase.str.lower(): Convert to lowercase.str.title(): Capitalize first letter of each word.str.capitalize(): Capitalize first letter of string.str.swapcase(): Swap case of all letters.str.trim(): Remove leading/trailing whitespace.str.trim_left(): Remove leading whitespace.str.trim_right(): Remove trailing whitespace.str.split(sep): Split string into list.str.rsplit(sep): Split string from right.str.split_lines(): Split string by newline.str.join(list): Join list of strings.str.replace(old, new): Replace substring.str.replace_all(old, new): Replace all substrings.str.find(sub): Find index of substring (returns -1 if not found).str.rfind(sub): Find index from right.str.index(sub): Find index (throws error if not found).str.rindex(sub): Find index from right (throws error).str.count(sub): Count occurrences of substring.str.starts_with(sub): Check prefix.str.ends_with(sub): Check suffix.str.contains(sub): Check if substring exists.str.is_alpha(): Check if only letters.str.is_digit(): Check if only numbers.str.is_alnum(): Check if letters and numbers.str.is_space(): Check if only whitespace.str.is_lower(): Check if fully lowercase.str.is_upper(): Check if fully uppercase.str.is_ascii(): Check if ASCII characters only.str.is_printable(): Check if characters are printable.str.pad_left(len, char): Pad string on left.str.pad_right(len, char): Pad string on right.str.center(len, char): Center string with padding.str.zfill(len): Pad with zeros on the left.str.repeat(n): Repeat string N times.str.reverse(): Reverse characters.str.chars(): Convert to list of characters.str.bytes(): Convert to list of ASCII bytes.str.format(*args): Inject variables into template.str.remove_prefix(sub): Strip prefix if exists.str.remove_suffix(sub): Strip suffix if exists.str.to_int(): Parse to integer.str.to_float(): Parse to float.str.is_empty(): Check if length is 0.str.expandtabs(size): Replace tabs with spaces.
list.push(val): Append item to end.list.pop(): Remove and return last item.list.unshift(val): Insert item at beginning.list.shift(): Remove and return first item.list.insert(idx, val): Insert at specific index.list.remove(val): Remove first occurrence of value.list.remove_at(idx): Remove at specific index.list.clear(): Empty the list.list.index(val): Get index of value.list.count(val): Count occurrences.list.sort(): Sort list ascending.list.sort_desc(): Sort list descending.list.reverse(): Reverse list in-place.list.copy(): Shallow copy list.list.deep_copy(): Deep copy list.list.slice(start, end): Return sub-list.list.map(fn): Apply function to all items.list.filter(fn): Keep items matching function.list.reduce(fn, init): Reduce list to single value.list.any(fn): True if any item matches.list.all(fn): True if all items match.list.find(fn): Return first matching item.list.find_index(fn): Return index of first match.list.flat(): Flatten nested lists 1 level.list.flat_deep(): Flatten nested lists completely.list.chunk(size): Split into lists of max size.list.unique(): Remove duplicates.list.join(sep): Join to string.list.is_empty(): Check if empty.list.first(): Get first item (or none).list.last(): Get last item (or none).list.extend(other_list): Append another list.list.fill(val, start, end): Fill indices with value.list.swap(i, j): Swap elements at indices.list.shuffle(): Randomize order in-place.
map.keys(): Return list of keys.map.values(): Return list of values.map.entries(): Return list of [key, value] pairs.map.get(key, default): Get value or default if missing.map.set(key, val): Insert or update key.map.has(key): Check if key exists.map.remove(key): Delete key and return value.map.clear(): Empty the map.map.copy(): Shallow copy map.map.deep_copy(): Deep copy map.map.merge(other): Combine with another map.map.update(other): In-place merge.map.is_empty(): Check if empty.map.invert(): Swap keys and values.map.filter(fn): Filter keys/values by function.map.map_values(fn): Apply function to values.map.group_by(list, fn): Create map grouped by function result.map.from_entries(list): Create map from key-value lists.map.pop(key): Remove key and return value.map.pop_item(): Remove and return random key-value pair.map.set_default(key, val): Set if missing, return value.map.keys_str(): Ensure all keys are cast to strings.map.values_str(): Ensure all values are cast to strings.map.pick(keys_list): Create new map with only selected keys.map.omit(keys_list): Create new map omitting selected keys.
tuple(*args): Create a tuple dynamically.tuple.count(val): Count occurrences.tuple.index(val): Find index.tuple.slice(start, end): Get sub-tuple.tuple.first(): Get first item.tuple.last(): Get last item.tuple.to_list(): Convert to mutable list.tuple.contains(val): Check if exists.tuple.is_empty(): Check if empty.tuple.unpack(): Returns items for multi-assignment.set(*args): Create a unique Set.set.add(val): Add item.set.remove(val): Remove item.set.has(val): True if exists.set.union(other): Combine two sets.set.intersection(other): Common items.set.difference(other): Items only in first set.set.symmetric_difference(other): Items in either, not both.set.is_subset(other): True if all items in other.set.is_superset(other): True if contains all of other.set.is_disjoint(other): True if no common items.set.clear(): Empty set.set.copy(): Shallow copy.set.pop(): Remove random item.set.to_list(): Convert to list.
random.random(): Float between 0.0 and 1.0.random.randint(min, max): Random integer in range.random.randfloat(min, max): Random float in range.random.choice(list): Pick random item from list.random.shuffle(list): Randomize list order in-place.random.sample(list, n): Pick N unique random items.random.seed(n): Set PRNG seed.random.boolean(): Return true or false randomly.random.bytes(n): Return N random bytes.random.uuid(): Generate a random UUID string v4.crypto.md5(str): MD5 hash string.crypto.sha1(str): SHA-1 hash.crypto.sha256(str): SHA-256 hash.crypto.base64_encode(str): Encode Base64.crypto.base64_decode(str): Decode Base64.
fs.read(path): Read whole file as string.fs.write(path, content): Write string to file (overwrite).fs.append(path, content): Append string to file.fs.read_lines(path): Read file into list of lines.fs.write_lines(path, list): Write list of lines to file.fs.read_bytes(path): Read file into byte array.fs.write_bytes(path, bytes): Write byte array to file.fs.exists(path): Check if path exists.fs.is_file(path): Check if path is a file.fs.is_dir(path): Check if path is a directory.fs.list_dir(path): Get list of files in directory.fs.make_dir(path): Create directory.fs.make_dirs(path): Create directory and parents.fs.remove_file(path): Delete a file.fs.remove_dir(path): Delete an empty directory.fs.remove_all(path): Delete directory and contents.fs.rename(old, new): Rename file or directory.fs.copy(src, dest): Copy file.fs.size(path): Get file size in bytes.fs.cwd(): Get current working directory.fs.chdir(path): Change current working directory.fs.abspath(path): Get absolute path.fs.extname(path): Get file extension.fs.basename(path): Get file name.fs.dirname(path): Get directory name from path.
os.env_get(key): Get environment variable.os.env_set(key, val): Set environment variable.os.env_del(key): Delete environment variable.os.system(cmd): Execute shell command.os.popen(cmd): Execute shell command and return stdout.os.name(): Return 'windows', 'linux', 'macos', or 'android'.os.arch(): Return 'x86_64', 'arm64', etc.os.cpu_count(): Get number of logical CPU cores.os.pid(): Get process ID.os.args(): Return list of CLI arguments passed to script.date.now(): Current Date object.date.year(d): Year integer.date.month(d): Month integer.date.day(d): Day integer.date.hour(d): Hour integer.date.minute(d): Minute integer.date.second(d): Second integer.date.format(d, fmt): Format date to string.date.parse(str, fmt): Parse string to Date object.date.unix(d): Convert Date to UNIX timestamp.
web.WebPage(title): Initialize a new WebPage object.web.serve(port): Start local web server.web.style(selector, rules_map): Add CSS rules.web.script(js_code): Add raw JS.web.body(elements_list): Inject HTML into body.web.h1(text, attrs): Create<h1>element.web.h2(text, attrs): Create<h2>element.web.h3(text, attrs): Create<h3>element.web.h4(text, attrs): Create<h4>element.web.h5(text, attrs): Create<h5>element.web.h6(text, attrs): Create<h6>element.web.p(text, attrs): Create<p>element.web.div(children, attrs): Create<div>element.web.span(text, attrs): Create<span>element.web.button(text, attrs): Create<button>element.web.input(attrs): Create<input>element.web.img(attrs): Create<img>element.web.a(text, attrs): Create<a>element.web.ul(items, attrs): Create<ul>element.web.ol(items, attrs): Create<ol>element.web.li(text, attrs): Create<li>element.web.table(rows, attrs): Create<table>element.web.tr(cells, attrs): Create<tr>element.web.td(text, attrs): Create<td>element.web.th(text, attrs): Create<th>element.web.form(children, attrs): Create<form>element.web.br(): Create<br>element.web.hr(): Create<hr>element.web.raw(html): Inject raw, unescaped HTML.web.iframe(attrs): Create<iframe>element.http.get(url, headers): Send HTTP GET request.http.post(url, body, headers): Send HTTP POST request.http.put(url, body, headers): Send HTTP PUT request.http.delete(url, headers): Send HTTP DELETE request.http.patch(url, body, headers): Send HTTP PATCH request.http.serve_api(port, routes_map): Start a JSON REST API server.json.encode(obj): Convert map/list to JSON string.json.encode_pretty(obj): Convert to formatted JSON string.json.decode(str): Convert JSON string to map/list.url.encode(str): URL encode a string.
When users attempt pip install techscript on Android Termux, the installation often fails. This is because Termux requires C/Rust compilers natively to build dependencies that lack pre-compiled Android wheels.
- Documentation Requirement: Create a specific
TERMUX.mdguide. - Required Commands for Users:
pkg update && pkg upgrade pkg install python rust binutils clang pip install techscript
To support platforms beyond Windows without requiring users to install Python, cross-compilation is necessary.
- Action: Update
build_release_repo.pyto utilize Rust'scargo build --releasetargeting specific architectures. - Targets:
x86_64-unknown-linux-gnu(Standard Linux)aarch64-apple-darwin(Apple Silicon Mac)x86_64-apple-darwin(Intel Mac)
- Distribution: Zip the resulting binaries and offer them in the GitHub release page alongside the existing
.exe.
<antigravity_plan>
- In
runtime/src/value.rs, completely strip outRc<RefCell<HashMap>>andRc<RefCell<Vec>>. - Implement an
Arenastruct invm.rscontainingVec<Object>. - Convert the
Valueenum to use NaN Boxing or Tagged Unions for primitive types. - Convert the
stackinVMfrom a dynamically sizedVec<Value>to a statically sized array[Value; 2048].
- In
runtime/src/opcode.rs, implementTryFrom<u8>for theOpCodeenum. - In
runtime/src/vm.rs, removeunsafe { std::mem::transmute(byte) }and useOpCode::try_from(byte). - In
runtime/src/compiler.rs, implement loop tracking to ensureBreakandContinuecompile to appropriate jumps, not returns. - Update
scripts/setup.batto replacesetx PATHwith safe PowerShell registry manipulation to avoid truncating Windows PATH variables.
- Set up a robust macro in
builtins.rsto map the 300 functions to VM globals. - Implement the
mathandcryptomodules natively in Rust usingf64operations and crates likemd5,sha2. - Implement all 45
strmethods natively in Rust, mapping back to interned string IDs. - Implement all functional methods (
map,filter,reduce) for lists, maps, tuples, and sets. - Build the
fsmodule ensuringstd::path::Pathis utilized for OS-agnostic path parsing.
- Add
tiny_httpandserde_jsontoruntime/Cargo.toml. - Port the
web.pyfunctionality into a newruntime/src/web.rsfile. - Implement all 30 HTML DOM generator methods in Rust (
web.h1,web.div, etc.), ensuring automatic HTML escaping.
- In
runtime/src/main.rs, capture CLI arguments matching the exact pattern[[[...]]]. - Slice the string, feed it to
Lexer::new(), compile, and execute it directly, bypassing file reads. </antigravity_plan>