ConstLang v7.0 Terminal

Interactive CLI Commands Reference

📋 Available Commands

1. Version & Info

Constlang >> constlang version
version: v7.0

Displays the installed ConstLang version.

2. Terminal Control

Constlang >> clear
// Clears all terminal output

Constlang >> cls
// Same as clear (Windows style)

Clear terminal history and start fresh.

3. Project Management

Constlang >> cpm new --app
// Creates new console application project

Constlang >> cpm new --go
// Creates Windows GUI project

Constlang >> cpm new --web
// Creates ASP.NET Core web project

Constlang >> cpm new --bat
// Creates Linux application

Constlang >> cpm new --sh
// Creates macOS application

Create new projects with different platform targets. A project compiler is dynamically loaded from compilers/[type]compiler.js.

4. Building & Compilation

Constlang >> constlang build
Compiling source files...
// [Waits 700ms for compilation simulation]
Build completed.


Constlang >> constlang build --app
// Builds and initializes app compiler

Compile your ConstLang source files to C#. The --app flag triggers compiler.start().

5. Package Management (CPM)

Constlang >> cpm install -url:https://example.com/package.clg
// Installs package from URL

Constlang >> cpm install -github:user/repo
// Installs from GitHub repository
// URL becomes: https://raw.githubusercontent.com/user/repo


Constlang >> cpm install -tool:formatter
// Installs development tool from tools/ directory

Install packages and dependencies using the ConstLang Package Manager.

6. Platform Commands

Constlang >> linux ls -la
Pocket-Forward: Linux ls -la
// Executes bash command on Linux


Constlang >> windows dir /s
Pocket-Forward: Windows dir /s
// Executes batch command on Windows


Constlang >> macos ls -la
Pocket-Forward: Macos ls -la
// Executes shell command on macOS

Run platform-specific system commands. Routes to system.run.sh(), system.run.bat(), or system.run.command().

7. Folder Information

Constlang >> folder
folder: /path/to/project
// Shows current working directory

Display the current project folder path. Uses window.dirHandle or global dirHandle.

8. Script Files (.csdf)

Constlang >> // Script execution via IPC
[Shell] .csdf file (5 lines)...
Constlang (Script) >> command 1
Constlang (Script) >> command 2
Constlang (Script) >> command 3
[Shell] Script loadend

Execute .csdf script files. Lines starting with // or # are ignored. Scripts are executed with 150ms delay between commands.

📊 Command Structure Reference

Command Format Purpose Handler
constlang version Simple Show version Direct output
clear / cls Simple Clear history Clear HTML
cpm new --[type] Type-based Create project Load compiler JS
constlang build Optional flags Compile code Simulation + compiler
[linux/windows/macos] [cmd] Prefix + args System commands system.run.*
cpm install -[type]:[value] Flag-based Install package cpm.install()
folder Simple Show path Direct output

🔧 Terminal Features

Input Display System

How Input Works:
• Real input: #cmd-input (transparent, z-index: 5)
• Display helper: #input-helper (mirrors input, z-index: 1)
• Cursor: blinking animation (z-index: 2)
• This creates seamless overlay effect

Command Processing Flow

1. User types and presses Enter
2. executeCommand(raw) is called
3. Command is matched against conditions
4. Appropriate handler executes (system call, compiler load, etc.)
5. Output is printed to history
6. Terminal scrolls to bottom

Color Scheme

Element Color Usage
Prompt #65e459 (Green) Command prefix
Text #cccccc (Gray) Default output
Library Calls #3b82f6 (Blue) System operations
Success #22a559 (Green) Successful operations
Error #f85149 (Red) Error messages

💡 Advanced Usage Examples

Example 1: Create and Build a Project

Constlang >> cpm new --app
// Project created

Constlang >> constlang build --app
Compiling source files...
Build completed.

Example 2: Install Package from GitHub

Constlang >> cpm install -github:exemple/exemple-lib/lib.nat
// Fetches from: https://raw.githubusercontent.com/ilkin/constlang-math

Example 3: Execute System Commands

Constlang >> linux npm install
Pocket-Forward: Linux npm install

Constlang >> windows pip install numpy
Pocket-Forward: Windows pip install numpy

Example 4: Run Script File

[Shell] .csdf file (8 lines)...
Constlang (Script) >> cpm new --app TestProject
Constlang (Script) >> constlang build
Constlang (Script) >> linux ls -la
[Shell] Script loadend

⚙️ Technical Details

Electron Integration

The terminal uses Electron's ipcRenderer for IPC communication:

// Listen for script execution from main process
ipcRenderer.on('run-csdf-script', async (event, content) => { ... })

Dynamic Compiler Loading

When cpm new --[type] is executed:

const s = document.body.appendChild(document.createElement('script'));
s.src = `compilers/${type}compiler.js`;
s.onload = () => { if(typeof compiler !== 'undefined') compiler.add(); };

Command Router Logic

Commands are processed in this order:

  1. Platform commands (linux/windows/macos)
  2. Package manager (cpm install)
  3. Terminal control (clear/cls)
  4. Build commands
  5. Project creation (cpm new)
  6. Version/info
  7. Fallback: Send to system
🎯 Tips for Effective Usage:
• Use clear to reset terminal state
• Check folder to verify working directory
• Platform commands work on installed tools only
• Script files can chain multiple commands
• Terminal focuses automatically on click

ConstLang v7.0 v7.0

Comprehensive Technical Reference & Implementation Guide

⚠️ v7.0 Update: This documentation covers the complete v7.0 compiler architecture including advanced bundling algorithms, multi-pass transpilation, macro system, integer type handling (int256/int512/int1024), and full command reference.

📑 Table of Contents

1. System Overview

ConstLang v7.0 is a transpiler-based language that compiles to C# (target: .NET 7.0+). The compilation pipeline consists of 6 distinct phases:

Compilation Pipeline:
Phase 1: Directory Traversal → Phase 2: Bundling → Phase 3-4: Multi-pass Macro Processing → Phase 5: Command Transpilation → Phase 6: Validation

Key Statistics (v7.0)

2. Compiler Architecture

2.1 Directory Traversal (_traverseDirectory)

Recursively scans project directories for ConstLang source files using the File System Access API.

Algorithm: for each entry in directory: if entry is file: if entry.name ends with .clg or .nat: content = await entry.getFile().text() sessionStorage[entry.name] = content else if entry is directory: recursively traverse(entry)

2.2 Entry Point Detection

The compiler automatically looks for main.clg as the entry point. All imports are resolved relative to this file.

2.3 Session Storage

All loaded .clg and .nat files are stored in sessionStorage for fast access during compilation. This allows multi-pass compilation without file system I/O.

3. Bundling Algorithm (PHASE 2)

3.1 Import Resolution Order

  1. #install [URL] - Fetches external code from URL (async)
  2. #import nat: [file] mod: [module] - Imports from .nat modules
  3. #import clg: [file] - Imports from .clg files
  4. #import [file] - Direct import (auto-detects .clg/.nat)
  5. #compiled [file] - Pre-compiled module import

3.2 Bundling Process

Pseudocode: bundleFile(startFile): fileCache = {} processedFiles = Set() for each file in sessionStorage: if file.endswith(.clg) or file.endswith(.nat): fileCache[file] = sessionStorage[file] if not fileCache[startFile]: throw ERROR: "ENTRY FILE NOT FOUND" return processFile(startFile, fileCache, processedFiles) processFile(filename, fileCache, processedFiles): if filename in processedFiles: return "" // Prevent circular imports processedFiles.add(filename) content = fileCache[filename] bundledDeps = "" // Process all import types for match in findAllImports(content): bundledDeps += processFile(match.file, ...) return bundledDeps + content

3.3 Native Module Processing (.nat)

.nat files use XML-style module containers:

<module="moduleName"> // Code here </module>

When importing with mod: [name], only the matching module is extracted.

4. Transpilation Engine (PHASE 3-6)

4.1 Multi-Pass Compilation

If special commands are detected, the compiler enters a loop (max 249 passes):

Loop Logic: passCount = 0 while passCount < MAX_PASSES and hasSpecialCommands(code): passCount++ beforeCode = code // Extract and process macros code = processMacros(code) // Process special commands code = processSpecialCommands(code) if not hasSpecialCommands(code): break // Exit loop early if code == beforeCode: ERROR: "No progress, loop infinite" if hasSpecialCommands(code) after loop: ERROR: "Special commands remain after max passes"

4.2 Special Commands

4.3 Macro System (cmd.fn)

The macro system uses regex-based pattern matching and substitution:

Syntax: cmd.fn() [ PATTERN command() TEMPLATE ] Example: cmd.fn() [ greet ${cmd^name} command() console.print("Hello, ${name}!") ] // Usage: greet John // Expands to: console.print("Hello, John!")

4.4 Macro Processing Algorithm

  1. Extract all cmd.fn() definitions using regex
  2. For each pattern, find ${cmd^varName} placeholders
  3. Convert to regex capturing groups: ([\\s\\S]*?)
  4. Replace ${varName} in template with captured groups
  5. Apply regex replacement to code
  6. Repeat until no special commands remain

5. Type System

5.1 Primitive Types

ConstLang C# Type Bit Width Example
int int 32-bit int x = 42;
int16 Int16 16-bit int16 x = 42;
int32 Int32 32-bit int32 x = 42;
int64 Int64 64-bit int64 x = 9223372036854775807;
int128 Int128 128-bit int128 x = 170141183460469231731687303715884105727;
int256 struct Int256 256-bit int256 x = 999...;
int512 struct Int512 512-bit int512 x = 999...;
int1024 struct Int1024 1024-bit int1024 x = 999...;
intx double 64-bit float intx pi = 3.14159;
string string Variable string name = "ConstLang";
ft bool 8-bit ft active = true;
byte byte[]/char[] 8-bit array byte data = "test";

5.2 Static Variables

static keyword converts to const in C#:

static int MAX = 100; → const int MAX = 100; static string VERSION = "7.0"; → const string VERSION = "7.0"; static ft DEBUG = true; → const bool DEBUG = true;

5.3 Big Integer Handling (int256/int512/int1024)

Large integers are split into UInt128 chunks:

int256 structure: struct Int256 { public UInt128 High; // Upper 128 bits public UInt128 Low; // Lower 128 bits } int512 structure: struct Int512 { public UInt128 W0; // Word 0 (bits 0-127) public UInt128 W1; // Word 1 (bits 128-255) public UInt128 W2; // Word 2 (bits 256-383) public UInt128 W3; // Word 3 (bits 384-511) } int1024 structure: struct Int1024 { public UInt128 W0; ... W7; // 8 x 128-bit words }

6. Complete Command Reference (200+ Commands)

6.1 Console I/O Commands

console.print(x)
Output to console with newline
console.print("Hello, World!");
read.data()
Read raw string from user input
string input = read.data();
read.int32() / read.int64() / read.intx()
Read and convert input to specific type
int32 age = read.int32();
read.title(x)
Output without newline (prompt)
read.title("Enter name: ");
console.status()
Get process uptime and thread count
console.status();
console.error(x)
Write to error output
console.error("Error occurred!");
console.color(colorName)
Set console foreground color
console.color("Green");
alert.data(x)
Display alert message
alert.data("Compilation successful!");

6.2 Type Conversion Commands

to.int32(x) / to.int64(x) / to.int128(x)
Convert to integer types
int32 num = to.int32("42");
to.string(x)
Convert to string
string str = to.string(42);
to.intx(x)
Convert to double
intx d = to.intx("3.14");
to.ft(x)
Convert to boolean
ft b = to.ft("true");
to.base64(x)
Encode to Base64
string encoded = to.base64("data");
converter.utf8.byte(x)
Convert string to UTF-8 bytes
byte[] bytes = converter.utf8.byte("hello");

6.3 File Management Commands

file.add(filename, content)
Write content to file
file.add("log.txt", "Application started");
file.load(filename)
Read entire file content
string content = file.load("config.txt");
file.redata(filename)
Stream write to file
file.redata("output.txt");
file.move(source, dest)
Move file to new location
file.move("old.txt", "new.txt");
file.copy(source, dest)
Copy file
file.copy("original.txt", "backup.txt");
folder.add(path)
Create directory
folder.add("data");
folder.fileinfo(path)
List all files in directory
folder.fileinfo("./src");
folder.folderinfo(path)
List all subdirectories
folder.folderinfo("./data");

6.4 String & Character Commands

.char.letter(c) / .char.i09(c)
Check if character is letter/digit
ft is_letter = .char.letter('A');
.char.upper(c) / .char.lower(c)
Check if character is upper/lowercase
ft is_upper = .char.upper('Z');
.char.isc(c)
Check if character is alphanumeric
ft is_alnum = .char.isc('A');
.char.space(c) / .char.symbol(c)
Check if whitespace/symbol
ft is_space = .char.space(' ');
.char.string.length(s)
Get string length
int len = .char.string.length("hello");
.char.string.concat(s1, s2)
Concatenate strings
string result = .char.string.concat("Hello", " World");
.char.string.replace(s, old, new)
Replace substring
string new_s = .char.string.replace("hello", "l", "L");
.char.string.join(separator, parts)
Join array of strings
string joined = .char.string.join(",", arr);
.caracters.token(s, delimiter)
Split string by delimiter
string[] parts = .caracters.token("a,b,c", ",");

6.5 Regex Commands

regex.parse(pattern, text)
Split by regex pattern
regex.parse("\\s+", "hello world");
regex.mainsearch(pattern, text)
Find first match
regex.mainsearch("\\d+", "abc123def");
regex.search(pattern, text)
Find all matches
regex.search("\\w+", "hello world");
regex.control(pattern, text)
Check if pattern matches
ft matches = regex.control("^test$", "test");
regex.replace(pattern, text, replacement)
Replace by pattern
regex.replace("\\d", "a1b2c3", "X");

6.6 List/Collection Commands

.list.string() / .list.int32()
Create new list of type
var names = .list.string();
.list.add(item)
Add item to list
names.list.add("Alice");
.list.new(index, item)
Insert at index
names.list.new(0, "Bob");
.list.delete(index)
Remove at index
names.list.delete(0);
.list.all()
Sort list
numbers.list.all();
.list.redata()
Reverse list
items.list.redata();
.list.clr()
Clear all items
items.list.clr();
.list.count()
Get item count
int size = items.list.count();

6.7 System & Control Commands

system.beep(frequency, duration)
Play system beep sound
system.beep(1000, 500);
system.stop(milliseconds)
Sleep thread
system.stop(5000);
system.stop.seconds(s) / .minutes(m) / .hours(h)
Sleep with time unit
system.stop.seconds(10);
system.time(ms)
Async delay (Task.Delay)
system.time(1000);
system.os()
Get OS identifier
string os = system.os();
open.window(program)
Start external process
open.window("notepad.exe");
cmd.save(value)
Output and save value
cmd.save("Result");

6.8 Network Commands

get(url)
Async fetch JSON from URL
var data = get("https://api.example.com/data");
ip.parse(ipString)
Parse IP address
ip.parse("192.168.1.1");
ip.endpoint(ip, port)
Create IP endpoint
ip.endpoint("127.0.0.1", 8080);
.ip.streamr()
Get network stream
.ip.streamr();

6.9 Control Flow Commands

if (condition) { }
Conditional execution
if (x > 10) { console.print("Big"); }
else if (condition) { }
Alternative condition
else if (x < 5) { ... }
else { }
Default case
else { ... }
while (condition) { }
Loop while true
while (count < 10) { count++; }
for (init; condition; increment) { }
C-style for loop
for (int i = 0; i < 10; i++) { ... }

6.10 Class Definition Commands

pub.class() { }
Define public class
pub.class() { ... }
pwr.class() { }
Define private class
pwr.class() { ... }
func.void name(params) { }
Define void function
func.void greet(string name) { ... }
async.void / async.task name() { }
Define async function
async.task fetchData() { ... }

6.11 GUI/Config Commands

config() { ... }
Extract to config.csproj file
config() { /* HTML/Config */ }
addon.app() { ... }
App configuration block
addon.app() { ... }
create.ctfile(filename, variable) { content }
Create file with content
create.ctfile("data.txt", content) { ... }
create.ctfolder(path)
Create directory structure
create.ctfolder("src/data");

6.12 Library/Import Commands

lib.cs(namespace)
Import C# namespace
lib.cs(System.Net);
system.control(resource) { }
Create using statement
system.control(fileStream) { ... }
#import [file]
Import source file
#import helpers.clg;
#import nat: [file] mod: [name]
Import from native module
#import nat: math.nat mod: vectors;
#install [url]
Install external dependency
#install https://example.com/lib.clg;
#compiled [file]
Mark as pre-compiled
#compiled binary.clg;

7. Macro System (Advanced)

7.1 Macro Fundamentals

Macros are compile-time template substitutions using regex-based pattern matching:

Syntax: cmd.fn() [ PATTERN command() TEMPLATE ] Components: - PATTERN: Text pattern with capture variables: ${cmd^varName} - command(): Marks the boundary (required) - TEMPLATE: Replacement template with placeholders: ${varName} or ${cmd^varName}

7.2 Macro Examples

Example 1: Simple Substitution
cmd.fn() [ LOG ${cmd^message} command() console.print("[LOG] ${message}") ] // Usage: LOG "Application started" // Compiles to: console.print("[LOG] Application started")
Example 2: Multiple Parameters
cmd.fn() [ ASSERT ${cmd^condition} REASON ${cmd^reason} command() if (!(${condition})) { throw new Exception("${reason}"); } ] // Usage: ASSERT value > 0 REASON "Value must be positive" // Compiles to: if (!(value > 0)) { throw new Exception("Value must be positive"); }

7.3 Macro Processing Order

Macros are processed in the order they are defined, with multiple passes until convergence.

8. File System Architecture

8.1 Project Structure

project-root/ ├── main.clg // Entry point (required) ├── helpers.clg // Additional modules ├── math.nat // Native modules └── config.csproj // Generated (output)

8.2 File Types

Extension Purpose Description
.clg Source File ConstLang source code, automatically detected and loaded
.nat Native Module XML-wrapped modules with selective imports
.cs Output (Generated) C# transpilation output
.csproj Config (Generated) Project configuration extracted from config() blocks

8.3 Import Resolution Algorithm

Resolution Order: 1. Check sessionStorage for filename 2. If not found, check with .clg extension 3. If still not found, throw ERROR 4. Prevent circular imports with processedFiles Set 5. Extract modules from .nat files if specified 6. Return processed content

9. Advanced Features & Compilation Strategies

9.1 Multi-Pass Compilation

When special commands are detected, compilation enters a loop that can run up to 249 passes:

Use Cases: 1. Nested macros (macros that generate other macros) 2. Conditional compilation 3. Code generation patterns 4. Template metaprogramming Termination Conditions: 1. No special commands remain in code 2. Code is unchanged in a pass (infinite loop detection) 3. Maximum passes (249) exceeded

9.2 Circular Import Protection

The compiler uses a Set to track processed files and prevent infinite recursion:

How it works: processFile(filename): if filename in processedFiles: return "" // Already imported, skip processedFiles.add(filename) // Process file

9.3 Validation & Error Handling

The compiler performs comprehensive validation:

9.4 Output Generation

The compiler can generate two files:

  1. main.cs - Compiled C# code
  2. config.csproj - Configuration extracted from config() blocks

9.5 Big Integer Operations

For int256/int512/int1024, the compiler handles large numbers by:

  1. Converting decimal to hexadecimal (arbitrary precision)
  2. Splitting into 128-bit chunks (UInt128 words)
  3. Creating struct instances with chunked values
ConstLang v7.0 Complete: This documentation covers all 200+ commands, the complete compilation pipeline, macro system, type system, and advanced features. For hands-on learning, use the interactive compiler or AI assistant.