# CSSL - C-Style Scripting Language

> Version 3.7.2 | A modern scripting language with C++-style syntax and unique features like CodeInfusion and BruteInjection.

---

## Table of Contents

1. [Quick Start](#quick-start)
2. [Basics](#basics)
3. [Data Types](#data-types)
4. [Container Types](#container-types)
5. [Variables & Globals](#variables--globals)
6. [Control Structures](#control-structures)
7. [Functions](#functions)
8. [Function Keywords](#function-keywords)
9. [String Methods](#string-methods)
10. [File I/O](#file-io)
11. [JSON Functions](#json-functions)
12. [Instance Management](#instance-management)
13. [Live Object Sharing](#live-object-sharing)
14. [CodeInfusion](#codeinfusion)
15. [Value Capture](#value-capture)
16. [BruteInjection](#bruteinjection)
17. [Filter Syntax](#filter-syntax)
18. [Module System](#module-system)
19. [Parameter Bridge](#parameter-bridge)
20. [Classes & OOP](#classes--oop)
21. [Map Container](#map-container)
22. [Structures](#structures)
23. [Error Handling](#error-handling)
24. [CLI Commands](#cli-commands)
25. [Examples](#examples)

---

## Quick Start

### Installation & Usage

```python
from includecpp import CSSL

# Initialize CSSL
CSSL.CsslLang()

# Execute code
CSSL.exec("""
    printl("Hello CSSL!");
""")

# With parameters and return value
result = CSSL.exec("""
    string name = parameter.get(0);
    printl("Hello " + name);
    parameter.return(true);
""", "World")

print(result)  # True
```

### CLI Execution

```bash
# Execute CSSL file
python -m includecpp cssl exec myfile.cssl

# Create module
python -m includecpp cssl makemodule mylib.py -o mylib.cssl-mod
```

### First Steps

```cssl
// Declare variables
string name = "CSSL";
int version = 3;

// Output
printl("Welcome to " + name);
printl(version);

// Define function
void greet(string msg) {
    printl(msg);
}
greet("Hello World!");
```

---

## Basics

### Comments

```cssl
// Single-line comment

/*
   Multi-line
   comment
*/
```

### Output

```cssl
printl("Text");              // With newline
printl(variable);            // Print variable
printl("Value: " + var);     // String concatenation
printl("Number: " + 42);     // String + Int works!
```

### Operators

#### Arithmetic Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `+` | Addition / String concatenation | `a + b` |
| `-` | Subtraction | `a - b` |
| `*` | Multiplication | `a * b` |
| `/` | Division | `a / b` |
| `%` | Modulo (remainder) | `a % b` |

#### Comparison Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `==` | Equality | `a == b` |
| `!=` | Inequality | `a != b` |
| `<` | Less than | `a < b` |
| `>` | Greater than | `a > b` |
| `<=` | Less than or equal | `a <= b` |
| `>=` | Greater than or equal | `a >= b` |

#### Logical Operators

| Operator | Description | Example |
|----------|-------------|---------|
| `&&` | Logical AND | `a && b` |
| `\|\|` | Logical OR | `a \|\| b` |
| `!` | Logical NOT | `!condition` |
| `not` | Logical NOT (alternative) | `not condition` |

#### Increment/Decrement (only in C-style for-loops)

| Operator | Description | Example |
|----------|-------------|---------|
| `++` | Increment | `i++` |
| `--` | Decrement | `i--` |
| `+=` | Addition assignment | `i += 1` |
| `-=` | Subtraction assignment | `i -= 1` |

---

## Data Types

### Primitive Types

| Type | Description | Example |
|------|-------------|---------|
| `string` | Text string | `string s = "Hello";` |
| `int` | Integer | `int i = 42;` |
| `float` | Floating point | `float f = 3.14;` |
| `bool` | Boolean | `bool b = true;` |
| `json` | JSON object | `json j;` |
| `dynamic` | Dynamic type | `dynamic x = "anything";` |

### Examples

```cssl
// String
string greeting = "Hello";
string name = "World";
string combined = greeting + " " + name;
printl(combined);  // "Hello World"

// Integer
int count = 10;
int doubled = count * 2;
printl(doubled);  // 20

// Float
float price = 19.99;
printl(price);

// Boolean
bool active = true;
bool disabled = false;

// Dynamic (flexible, but slower)
dynamic anything = "first string";
anything = 123;  // now int
anything = 3.14; // now float
```

---

## Container Types

### stack\<T\>

LIFO data structure (Last In, First Out).

```cssl
stack<string> names;
names.push("Alice");
names.push("Bob");
names.push("Charlie");

printl(names);           // ['Alice', 'Bob', 'Charlie']
printl(names[0]);        // "Alice" (index access)
printl(len(names));      // 3

string last = names.pop();
printl(last);            // "Charlie"
```

**Methods:**

| Method | Description |
|--------|-------------|
| `.push(value)` | Add element |
| `.pop()` | Remove and return last element |
| `[index]` | Get element at index |
| `len(stack)` | Number of elements |

---

### vector\<T\>

Dynamic array.

```cssl
vector<int> numbers;
numbers.push(10);
numbers.push(20);
numbers.push(30);

printl(numbers);      // [10, 20, 30]
printl(numbers[1]);   // 20
```

**Methods:**

| Method | Description |
|--------|-------------|
| `.push(value)` | Add element |
| `.pop()` | Remove last element |
| `[index]` | Element at index |

---

### array\<T\>

Static array.

```cssl
array<string> items;
items.push("A");
items.push("B");
printl(items);
```

---

### datastruct\<T\>

Universal container for BruteInjection operations.

```cssl
datastruct<string> data;
data +<== someStack;  // Copy data into it
```

---

### dataspace\<T\>

Extended data space for complex operations.

```cssl
dataspace<dynamic> storage;
```

---

### combo\<T\>

Combo space for filtered searches.

```cssl
combo<string> searchSpace;
combo<open&string> filter = combo<open&string>::like="Hannes";
```

---

### iterator\<T\>

For iterations over data structures.

```cssl
iterator<int> it;

// 2D iterator with 16 fields
iterator<iterator<int, 16>> Map;
Map.insert(3, 12);
Map.fill(0);
int value = Map.at(3);
```

---

### shuffled\<T\>

Container for multiple return values.

```cssl
shuffled<string> results;

shuffled string getMultiple() {
    return "first", "second", "third";
}
```

---

## Variables & Globals

### Local Variables

```cssl
string local = "only visible here";
int number = 42;
```

### Global Variables

```cssl
// Declaration with 'global'
global myGlobal = "visible everywhere";

// Access with '@' prefix
printl(@myGlobal);

// Or access directly without '@' (since v3.5.9)
printl(myGlobal);  // Works the same!

// Alternative: r@ syntax for declaration
r@anotherGlobal = "also global";
printl(@anotherGlobal);
printl(anotherGlobal);  // Also works
```

### Lookup Order

When accessing a variable, CSSL checks in order:
1. Local scope
2. Global scope
3. Promoted globals
4. Built-in functions

### Usage in Functions

```cssl
global counter = 0;

void increment() {
    @counter = @counter + 1;
    printl(@counter);
}

increment();  // 1
increment();  // 2
increment();  // 3
```

---

## Control Structures

### If / Else If / Else

```cssl
int x = 10;

if (x < 5) {
    printl("Small");
} else if (x < 15) {
    printl("Medium");
} else {
    printl("Large");
}

// With logical operators
if (x > 0 && x < 100) {
    printl("In range");
}

// Negation
if (!active) {
    printl("Not active");
}

// Alternative negation
if (not active) {
    printl("Not active");
}
```

---

### Switch / Case

```cssl
int day = 3;

switch (day) {
    case 1:
        printl("Monday");
        break;
    case 2:
        printl("Tuesday");
        break;
    case 3:
        printl("Wednesday");
        break;
    default:
        printl("Other day");
}
```

---

### While Loop

```cssl
int i = 0;
while (i < 5) {
    printl(i);
    i = i + 1;
}
```

---

### For Loop (Python-Style)

```cssl
// Range-based
for (i in range(0, 5)) {
    printl(i);  // 0, 1, 2, 3, 4
}

// With start and end
for (x in range(10, 15)) {
    printl(x);  // 10, 11, 12, 13, 14
}

// With step
for (i in range(0, 10, 2)) {
    printl(i);  // 0, 2, 4, 6, 8
}
```

---

### For Loop (C-Style)

```cssl
// Classic C-style syntax
for (int i = 0; i < 10; i++) {
    printl(i);
}

// With decrement
for (int i = 10; i > 0; i--) {
    printl(i);
}

// With +=
for (int i = 0; i < 100; i += 10) {
    printl(i);  // 0, 10, 20, ...
}
```

---

### Foreach

```cssl
stack<string> names;
names.push("Alice");
names.push("Bob");
names.push("Charlie");

// Syntax 1: foreach (item in collection)
foreach (name in names) {
    printl(name);
}

// Syntax 2: foreach collection as item
foreach names as name {
    printl(name);
}
```

---

### Break & Continue

```cssl
// Break - exit loop early
for (i in range(0, 10)) {
    if (i == 5) {
        break;  // Stops at 5
    }
    printl(i);
}

// Continue - skip iteration
for (i in range(0, 10)) {
    if (i == 3) {
        continue;  // Skips 3
    }
    printl(i);
}
```

---

## Functions

### Basic Syntax

```cssl
// Without return
void sayHello() {
    printl("Hello!");
}

// With return
string getName() {
    return "CSSL";
}

// With parameters
int add(int a, int b) {
    return a + b;
}

// Call
sayHello();
string n = getName();
int sum = add(5, 3);
```

### Named Parameters

Functions can be called with named parameters for clarity.

```cssl
// Define function
int calculate(int base, int multiplier, int offset) {
    return base * multiplier + offset;
}

// Call with positional arguments
int r1 = calculate(10, 5, 3);  // 53

// Call with named parameters
int r2 = calculate(base=10, multiplier=5, offset=3);  // 53

// Mix positional and named (positional must come first)
int r3 = calculate(10, multiplier=5, offset=3);  // 53

// Named parameters can be in any order
int r4 = calculate(offset=3, base=10, multiplier=5);  // 53
```

### Nested Functions

```cssl
void inner() {
    printl("Inner function");
}

void outer() {
    printl("Outer function");
    inner();
}

outer();
```

---

## Function Keywords

### undefined

Function silently ignores errors.

```cssl
undefined void mayFail() {
    riskyOperation();  // Errors are ignored
}
mayFail();  // No crash
```

---

### dynamic

No type declaration needed.

```cssl
dynamic x = "string";
x = 123;        // now int
x = 3.14;       // now float
```

---

### define

Constant function without type and return.

```cssl
define LOG_MESSAGE() {
    printl("Log message");
}
LOG_MESSAGE();
```

---

### closed

Protects from external code injection.

```cssl
closed void protectedFunc() {
    printl("Protected from external injections");
}
// This injection will be BLOCKED:
protectedFunc() <<== { printl("Blocked!"); }
```

---

### private

Blocks ALL injections.

```cssl
private void superSecure() {
    printl("Absolutely protected");
}
```

---

### virtual

Allows import cycles.

```cssl
virtual void safeForImport() {
    printl("Import-cycle-safe");
}
```

---

### meta

Declares function as source (must return).

```cssl
meta string getSource() {
    return "Meta source";
}
```

---

### super

Forces execution without exceptions.

```cssl
super void forceRun() {
    printl("Will ALWAYS execute");
}
```

---

### shuffled

Allows multiple return values.

```cssl
shuffled string getNames() {
    return "Alice", "Bob", "Charlie";
}
```

---

### open

Accepts any parameters.

```cssl
open define flexibleFunc(open Params) {
    string name = OpenFind<string>(0);
    int num = OpenFind<int>(0);
    printl(name);
    printl(num);
}

flexibleFunc("Hello", 123, true, "World");
```

---

## String Methods

CSSL offers 40+ string methods:

### Search & Check

```cssl
string s = "Hello World";

// Contains
bool has = s.contains("World");     // true

// Find position
int pos = s.indexOf("o");           // 4
int last = s.lastIndexOf("o");      // 7

// Start/end check
bool start = s.startsWith("Hello"); // true
bool end = s.endsWith("World");     // true
```

### Manipulation

```cssl
string s = "Hello World";

// Replace
string r1 = s.replace("World", "CSSL");     // "Hello CSSL"
string r2 = s.replaceAll("l", "L");         // "HeLLo WorLd"

// Case
string upper = s.toUpperCase();   // "HELLO WORLD"
string lower = s.toLowerCase();   // "hello world"

// Trim
string padded = "  text  ";
string trimmed = padded.trim();   // "text"

// Repeat
string rep = "ab".repeat(3);      // "ababab"

// Reverse
string rev = s.reverse();         // "dlroW olleH"
```

### Split & Join

```cssl
string csv = "a,b,c,d";

// Split
stack<string> parts = csv.split(",");  // ["a", "b", "c", "d"]

// Join
string joined = parts.join("-");       // "a-b-c-d"
```

### Extract

```cssl
string s = "Hello World";

// Substring
string sub = s.substring(0, 5);   // "Hello"
string slc = s.slice(6, 11);      // "World"

// Character
string ch = s.charAt(0);          // "H"
int code = s.charCodeAt(0);       // 72
```

### Padding

```cssl
string num = "42";

string padded1 = num.padStart(5, "0");  // "00042"
string padded2 = num.padEnd(5, ".");    // "42..."
```

### All String Methods

| Method | Description |
|--------|-------------|
| `.contains(str)` | Check if string contains |
| `.indexOf(str)` | First position of str |
| `.lastIndexOf(str)` | Last position of str |
| `.startsWith(str)` | Starts with str? |
| `.endsWith(str)` | Ends with str? |
| `.find(str)` | Find position (-1 if not found) |
| `.split(delimiter)` | Split into array |
| `.join(delimiter)` | Join array to string |
| `.replace(old, new)` | Replace first occurrence |
| `.replaceAll(old, new)` | Replace all occurrences |
| `.substring(start, end)` | Extract substring |
| `.slice(start, end)` | Substring (like substring) |
| `.substr(start, length)` | Substring with length |
| `.toLowerCase()` | To lowercase |
| `.toUpperCase()` | To uppercase |
| `.trim()` | Remove whitespace |
| `.charAt(index)` | Character at position |
| `.charCodeAt(index)` | ASCII code at position |
| `.padStart(len, char)` | Pad left |
| `.padEnd(len, char)` | Pad right |
| `.repeat(n)` | Repeat n times |
| `.reverse()` | Reverse |
| `.count(str)` | Count occurrences |
| `len(string)` | String length |

---

## File I/O

CSSL provides built-in functions for file operations.

### Basic File Operations

```cssl
// Read entire file
string content = read("/path/to/file.txt");
printl(content);

// Read specific line (1-indexed)
string line5 = readline(5, "/path/to/file.txt");
printl(line5);

// Write to file (overwrites)
write("/path/to/file.txt", "Hello World");

// Write/replace specific line
writeline(3, "New line content", "/path/to/file.txt");
```

### Extended File Functions

```cssl
// Read all lines as array
stack<string> lines = readlines("/path/to/file.txt");

// Append to file
appendfile("/path/to/file.txt", "\nNew content");

// File checks
bool exists = pathexists("/path/to/file.txt");
bool isFile = isfile("/path/to/file.txt");
bool isDir = isdir("/path/to/folder");

// File size
int size = filesize("/path/to/file.txt");

// Directory listing
stack<string> files = listdir("/path/to/folder");
```

### Path Functions

```cssl
// Path manipulation
string base = basename("/path/to/file.txt");    // "file.txt"
string dir = dirname("/path/to/file.txt");       // "/path/to"
string full = joinpath("/path", "to", "file.txt"); // "/path/to/file.txt"
string abs = abspath("./file.txt");              // "/current/dir/file.txt"
```

### All File I/O Functions

| Function | Description |
|----------|-------------|
| `read(path)` | Read entire file content |
| `readline(line, path)` | Read specific line (1-indexed) |
| `write(path, content)` | Write content to file |
| `writeline(line, content, path)` | Write/replace specific line |
| `readfile(path)` | Read file (alias for read) |
| `writefile(path, content)` | Write file (alias for write) |
| `readlines(path)` | Read all lines as array |
| `appendfile(path, content)` | Append to file |
| `pathexists(path)` | Check if path exists |
| `isfile(path)` | Check if is file |
| `isdir(path)` | Check if is directory |
| `filesize(path)` | Get file size in bytes |
| `listdir(path)` | List directory contents |
| `makedirs(path)` | Create directories |
| `removefile(path)` | Delete file |
| `removedir(path)` | Delete empty directory |
| `copyfile(src, dst)` | Copy file |
| `movefile(src, dst)` | Move file |

---

## JSON Functions

CSSL provides namespace-style JSON functions with the `json::` prefix.

### Reading & Writing JSON Files

```cssl
// Read and parse JSON file
json data = json::read("/path/to/config.json");
printl(data.name);

// Write data to JSON file
json::write("/path/to/output.json", data);
```

### JSON Parsing & Stringifying

```cssl
// Parse JSON string
string jsonStr = '{"name": "Alice", "age": 30}';
json obj = json::parse(jsonStr);

// Convert to JSON string
string str = json::stringify(obj);

// Pretty print with indentation
string pretty = json::pretty(obj);
printl(pretty);
```

### JSON Path Operations

```cssl
json data = json::read("config.json");

// Get value by dot-path
string name = json::get(data, "user.name");
int age = json::get(data, "user.profile.age");
string city = json::get(data, "address.city", "Unknown");  // with default

// Set value by dot-path
data = json::set(data, "user.name", "Bob");
data = json::set(data, "settings.theme", "dark");

// Check if path exists
if (json::has(data, "user.email")) {
    printl("Email exists");
}
```

### JSON Object Operations

```cssl
json obj = json::read("data.json");

// Get all keys
stack<string> keys = json::keys(obj);
foreach (key in keys) {
    printl(key);
}

// Get all values
stack<dynamic> values = json::values(obj);

// Deep merge objects
json merged = json::merge(obj1, obj2, obj3);
```

### All JSON Functions

| Function | Description |
|----------|-------------|
| `json::read(path)` | Read and parse JSON file |
| `json::write(path, data)` | Write data to JSON file |
| `json::parse(str)` | Parse JSON string to object |
| `json::stringify(data)` | Convert to JSON string |
| `json::pretty(data)` | Pretty print JSON |
| `json::get(data, path, default)` | Get value by dot-path |
| `json::set(data, path, value)` | Set value by dot-path |
| `json::has(data, path)` | Check if path exists |
| `json::keys(data)` | Get all keys |
| `json::values(data)` | Get all values |
| `json::merge(obj1, obj2, ...)` | Deep merge objects |

---

## Instance Management

CSSL provides `instance<"name">` syntax and `instance::` namespace for working with shared instances.

### Instance Declaration

```cssl
// Get/create shared instance by name
instance<"MyApp"> app;

// With initialization
instance<"tk"> tk = include("tkinter.cssl-mod");

// Register object as shared instance
myModule ==> $AppModule
// Or using instance syntax:
myModule ==> instance<"AppModule">
```

### Instance Introspection

```cssl
@tk = include("tk.cssl-mod");

// Get all methods from module
stack<string> methods = instance::getMethods(@tk);
foreach (m in methods) {
    printl("Method: " + m);
}

// Get all classes
stack<string> classes = instance::getClasses(@tk);

// Get all variables
stack<string> vars = instance::getVars(@tk);

// Get everything categorized
json all = instance::getAll(@tk);
printl(all.methods);   // ["method1", "method2", ...]
printl(all.classes);   // ["Class1", "Class2", ...]
printl(all.vars);      // ["var1", "var2", ...]
```

### Dynamic Method Calls

```cssl
// Call method dynamically by name
result = instance::call(@module, "methodName", arg1, arg2);

// Check if method/attribute exists
if (instance::has(@module, "initialize")) {
    instance::call(@module, "initialize");
}

// Get type name
string typeName = instance::type(@module);
printl(typeName);  // "module"
```

### All Instance Functions

| Function | Description |
|----------|-------------|
| `instance<"name"> var` | Declare instance variable |
| `obj ==> instance<"name">` | Register as shared instance |
| `instance::getMethods(obj)` | Get all method names |
| `instance::getClasses(obj)` | Get all class names |
| `instance::getVars(obj)` | Get all variable names |
| `instance::getAll(obj)` | Get categorized dict |
| `instance::call(obj, 'name', ...)` | Call method dynamically |
| `instance::has(obj, 'name')` | Check if attribute exists |
| `instance::type(obj)` | Get type name |
| `isavailable("name")` | Check if shared instance exists |
| `instance::exists("name")` | Alias for isavailable |

---

## Live Object Sharing

Share Python objects with CSSL. Changes in CSSL reflect back to Python.

### Python Side

```python
from includecpp import CSSL

class Counter:
    def __init__(self):
        self.value = 100

counter = Counter()
cssl = CSSL.CsslLang()
cssl.share(counter, "cnt")

# Changes in CSSL will reflect in Python!
cssl.exec('''
    $cnt.value = $cnt.value - 10;
    printl($cnt.value);  // 90
''')

print(counter.value)  # 90 - Changed!
```

### CSSL Syntax

| Syntax | Description |
|--------|-------------|
| `$name` | Access shared object |
| `$name.property` | Access/modify properties |
| `$name.method()` | Call methods |
| `delete("name")` | Remove shared object |

### Loop Modifications

```python
# Python
class Stats:
    def __init__(self):
        self.total = 100

stats = Stats()
cssl = CSSL.CsslLang()
cssl.share(stats, "s")

cssl.exec('''
    for (i in range(0, 5)) {
        $s.total = $s.total - 10;
    }
    printl($s.total);  // 50
''')

print(stats.total)  # 50 - Persisted!
```

---

## CodeInfusion

CodeInfusion enables modifying functions at runtime.

### <<== (Replace)

Replaces function content.

```cssl
void original() {
    printl("Original");
}

original() <<== {
    printl("Replaced");
}

original();  // "Replaced"
```

---

### +<<== (Add)

Adds code to function (executes BEFORE original).

```cssl
void base() {
    printl("Base");
}

base() +<<== {
    printl("Added");
}

base();
// Output:
// Added
// Base
```

---

### -<<== (Remove)

Removes code from function.

```cssl
void withExtra() {
    printl("Important");
    printl("Unimportant");
}

withExtra() -<<== {
    printl("Unimportant");
}

withExtra();  // Only "Important"
```

---

### exit() Injection

Special injection for program end.

```cssl
exit() <<== {
    printl("Cleanup before exit...");
}

// Later:
exit();  // Executes injection
```

---

## Value Capture

The `%identifier` syntax captures values at registration time, useful for saving original functions before replacement.

### Capturing Variables

```cssl
string version = "1.0.0";

// Capture current value
v <== { %version; }
printl(v);  // "1.0.0"

// Even if version changes later, v keeps captured value
version = "2.0.0";
printl(v);  // Still "1.0.0"
```

### Capturing Functions

```cssl
// Save original exit function before replacing
originalExit <<== { %exit(); }

// Replace exit with custom behavior
exit() <<== {
    printl("Custom cleanup...");
    originalExit();  // Call saved original
}

exit();
// Output:
// Custom cleanup...
// (original exit behavior)
```

### Use Cases

```cssl
// 1. Preserving original behavior
void myFunc() {
    printl("Original");
}

savedFunc <<== { %myFunc(); }

myFunc() <<== {
    printl("Modified");
}

myFunc();      // "Modified"
savedFunc();   // "Original"

// 2. Capturing configuration at startup
global config = loadConfig();
startupConfig <== { %config; }

// 3. Snapshot values for later comparison
int counter = 0;
initial <== { %counter; }
// ... operations ...
if (counter != initial) {
    printl("Counter changed!");
}
```

---

## BruteInjection

BruteInjection copies/moves data between containers.

### +<== (Copy)

Copies data to target (source unchanged).

```cssl
stack<string> source;
source.push("A");
source.push("B");

datastruct<string> target;
target +<== source;  // Copies A, B
```

---

### -<== (Move)

Moves data (removes from source).

```cssl
stack<string> src;
src.push("Data");

datastruct<string> dst;
dst -<== src;  // src is empty after
```

---

### ==> (Replace)

Replaces target data completely.

```cssl
stack<string> data;
data.push("New");

datastruct<string> container;
container ==> data;
```

---

### ==>- (Receive Minus)

Removes matching items from target.

```cssl
stack<string> names;
names.push("Alice");
names.push("Bob");
names.push("Alice");

stack<string> toRemove;
toRemove.push("Alice");

// Remove all "Alice" from names
names ==>- toRemove;
printl(names);  // ["Bob"]
```

---

## Filter Syntax

Filters enable targeted data operations in BruteInjection.

### Syntax

```cssl
target +<== [type::filter=value] source;
```

### String Filters

```cssl
stack<string> fruits;
fruits.push("Apple");
fruits.push("Banana");
fruits.push("Apricot");

datastruct<string> result;

// Exact match
result +<== [string::where="Apple"] fruits;

// Everything except
result +<== [string::not="Banana"] fruits;

// Contains substring
result +<== [string::contains="App"] fruits;  // Apple, Apricot

// String length
result +<== [string::length=5] fruits;  // Apple
```

### String Cutting Filters

Cut strings at specific positions or substrings.

```cssl
string version = "1.0.0-beta";

// Cut at position (integer index)
x = <==[string::cut=3] version;
printl(x);  // "1.0" (first 3 chars)

// Cut at substring position
x = <==[string::cut="0-"] version;
printl(x);  // "1.0." (before "0-")

// Get everything after substring
x = <==[string::cutAfter=".0."] version;
printl(x);  // "0-beta" (after ".0.")

// Cut after at position
x = <==[string::cutAfter=4] version;
printl(x);  // ".0-beta" (after index 4)
```

### All Filters

| Filter | Description |
|--------|-------------|
| `string::where=VALUE` | Exact string match |
| `string::not=VALUE` | Everything except this value |
| `string::contains=VALUE` | Contains substring |
| `string::length=LENGTH` | Exact string length |
| `string::cut=INDEX` | Cut at index (returns first N chars) |
| `string::cut="SUBSTR"` | Cut at substring position |
| `string::cutAfter=INDEX` | Get everything after index |
| `string::cutAfter="SUBSTR"` | Get everything after substring |
| `integer::where=VALUE` | Exact int match |
| `json::key=KEYNAME` | Filter by JSON key |
| `json::value=VALUE` | Filter by JSON value |
| `array::index=INDEX` | By array index |
| `vector::where=VALUE` | Exact vector match |
| `combo::filterdb` | Combo FilterDB |

---

## Module System

### Create Module

Create CSSL module from Python file:

```bash
python -m includecpp cssl makemodule mylib.py -o mylib.cssl-mod
```

### Import Module

```cssl
// Import Python module
@Math = include("mymath.cssl-mod");

// Import CSSL file
@Utils = include("utils.cssl");

// Call module functions
int result = @Math.add(5, 3);
string text = @Utils.format("Hello");
```

### Example: Python Module

**mathlib.py:**
```python
def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

def square(x):
    return x * x
```

**Create module:**
```bash
python -m includecpp cssl makemodule mathlib.py -o mathlib.cssl-mod
```

**Use in CSSL:**
```cssl
@Math = include("mathlib.cssl-mod");

int sum = @Math.add(10, 20);      // 30
int product = @Math.multiply(5, 6); // 30
int sq = @Math.square(8);          // 64

printl(sum);
printl(product);
printl(sq);
```

---

## Parameter Bridge

Communication between Python and CSSL.

### parameter.get()

Receive parameters from Python:

```cssl
// In CSSL
string name = parameter.get(0);    // First parameter
int count = parameter.get(1);      // Second parameter
printl(name);
printl(count);
```

```python
# In Python
CSSL.exec(code, "Alice", 42)
```

### parameter.return()

Return value to Python:

```cssl
// In CSSL
int result = 10 + 20;
parameter.return(result);
```

```python
# In Python
result = CSSL.exec(code)
print(result)  # 30
```

### Complete Example

```python
from includecpp import CSSL

CSSL.CsslLang()

code = """
    int a = parameter.get(0);
    int b = parameter.get(1);
    int sum = a + b;
    parameter.return(sum);
"""

result = CSSL.exec(code, 15, 27)
print(f"Result: {result}")  # Result: 42
```

### Supported Return Types

```cssl
parameter.return(true);           // bool
parameter.return(42);             // int
parameter.return(3.14);           // float
parameter.return("Hello");        // string
parameter.return(myStack);        // stack/array
parameter.return(myObject);       // JSON/dict
```

---

## Classes & OOP

CSSL supports object-oriented programming with classes, constructors, and the `this->` keyword for member access.

### Defining a Class

```cssl
class Person {
    // Member variables
    string name;
    int age;

    // Constructor (same name as class)
    void Person(string n, int a) {
        this->name = n;
        this->age = a;
    }

    // Methods
    void greet() {
        printl("Hello, I'm " + this->name);
    }

    string getName() {
        return this->name;
    }

    void setAge(int a) {
        this->age = a;
    }
}
```

### Creating Instances

```cssl
// Use 'new' keyword to instantiate
Person p = new Person("Alice", 30);

// Call methods
p.greet();                    // prints: "Hello, I'm Alice"
string name = p.getName();    // returns "Alice"

// Access members (if public)
printl(p.name);              // prints: "Alice"
p.age = 31;                  // set member directly
```

### The `this->` Keyword

Inside class methods, use `this->` to access instance members:

```cssl
class Counter {
    int count;

    void Counter() {
        this->count = 0;
    }

    void increment() {
        this->count = this->count + 1;
    }

    void add(int n) {
        this->count = this->count + n;
    }

    int get() {
        return this->count;
    }
}

Counter c = new Counter();
c.increment();
c.add(5);
printl(c.get());  // prints: 6
```

### Constructor Variations

```cssl
class MyClass {
    // Constructor with same name as class
    void MyClass(int x) {
        this->value = x;
    }
}

// Alternative: use __init__
class MyClass2 {
    void __init__(int x) {
        this->value = x;
    }
}
```

### Method Chaining

```cssl
class Builder {
    string result;

    void Builder() {
        this->result = "";
    }

    Builder add(string s) {
        this->result = this->result + s;
        return this;
    }

    string build() {
        return this->result;
    }
}

Builder b = new Builder();
string result = b.add("Hello ").add("World!").build();
printl(result);  // prints: "Hello World!"
```

---

## Map Container

The `map<>` type provides C++ style ordered key-value storage.

### Creating Maps

```cssl
map<string, int> ages;
map<string, string> config;
```

### Basic Operations

```cssl
map<string, int> ages;

// Insert values
ages.insert("Alice", 30);
ages.insert("Bob", 25);

// Find values
int age = ages.find("Alice");  // returns 30

// Check existence
if (ages.contains("Alice")) {
    printl("Found!");
}

// Erase entries
ages.erase("Bob");

// Get with exception if not found
int a = ages.at("Alice");  // throws if not found

// Size and empty check
int size = ages.size();
bool empty = ages.empty();
```

### Iteration and Bounds

```cssl
map<string, int> data;
data.insert("apple", 1);
data.insert("banana", 2);
data.insert("cherry", 3);

// Get first/last elements
tuple first = data.begin();  // ("apple", 1)
tuple last = data.end();     // ("cherry", 3)

// Find bounds (for sorted keys)
string lb = data.lower_bound("b");  // "banana" (first key >= "b")
string ub = data.upper_bound("b");  // "cherry" (first key > "b")
```

---

## Structures

Structures are user-defined data types.

```cssl
structure Person {
    string name;
    int age;
    string email;
}

// Create instance
Person user;
user.name = "Max";
user.age = 25;
user.email = "max@example.com";

printl(user.name);   // "Max"
printl(user.age);    // 25
```

### With Functions

```cssl
structure Rectangle {
    int width;
    int height;
}

int calculateArea(Rectangle rect) {
    return rect.width * rect.height;
}

Rectangle r;
r.width = 10;
r.height = 5;
int area = calculateArea(r);
printl(area);  // 50
```

---

## Error Handling

### Try / Catch

```cssl
try {
    // Risky code
    int result = riskyOperation();
    printl(result);
} catch {
    printl("An error occurred");
}
```

### With undefined

```cssl
undefined void safeOperation() {
    // Errors are silently ignored
    dangerousCode();
}

safeOperation();  // No crash
```

---

## CLI Commands

### Execute

```bash
# Execute CSSL file
python -m includecpp cssl exec script.cssl

# Execute CSSL code directly
python -m includecpp cssl exec -c "printl('Hello');"
```

### Create Module

```bash
# From Python file
python -m includecpp cssl makemodule mylib.py -o mylib.cssl-mod

# With output path
python -m includecpp cssl makemodule src/utils.py -o modules/utils.cssl-mod
```

### Help

```bash
python -m includecpp cssl --help
python -m includecpp cssl exec --help
python -m includecpp cssl makemodule --help
```

---

## Examples

### Tkinter GUI Calendar

```cssl
// Import modules
@Gui = include("modules/tkgui.cssl-mod");

// Global state
global currentMonth = 0;
global currentYear = 0;

// Initialize
void init() {
    @currentYear = @Gui.get_current_year();
    @currentMonth = @Gui.get_current_month();
}

// Build calendar
void buildCalendar() {
    stack<string> days;
    days.push("Mo");
    days.push("Tu");
    days.push("We");
    days.push("Th");
    days.push("Fr");
    days.push("Sa");
    days.push("Su");

    // Header with for-loop
    for (i in range(0, 7)) {
        @Gui.add_label(days[i], i * 40, 50);
    }

    // Days with C-style for
    int daysInMonth = @Gui.get_days_in_month(@currentYear, @currentMonth);
    for (int d = 1; d <= daysInMonth; d++) {
        @Gui.add_button("" + d, d);
    }
}

// Main
init();
@Gui.create_window("CSSL Calendar", 350, 400);
buildCalendar();
@Gui.run();
```

---

### Task Manager with CodeInfusion

```cssl
global tasks = stack<string>;

void addTask(string task) {
    @tasks.push(task);
    printl("+ " + task);
}

void showTasks() {
    printl("=== Tasks ===");
    foreach (task in @tasks) {
        printl("- " + task);
    }
}

void completeTask() {
    string done = @tasks.pop();
    printl("Completed: " + done);
}

// Add logging via CodeInfusion
addTask() +<<== {
    printl("[LOG] Adding task...");
}

// Exit handler
exit() <<== {
    printl("Shutting down Task Manager...");
}

// Application
addTask("Write code");
addTask("Run tests");
addTask("Update documentation");
showTasks();
completeTask();
exit();
```

---

### Data Pipeline with BruteInjection

```cssl
// Source data
stack<string> rawData;
rawData.push("Alice");
rawData.push("Bob");
rawData.push("Charlie");
rawData.push("Alex");
rawData.push("Anna");

// Filter: Only names containing "A"
datastruct<string> aNames;
aNames +<== [string::contains="A"] rawData;

// Output
printl("Names with A:");
foreach (name in aNames) {
    printl("  - " + name);
}
// Output: Alice, Alex, Anna
```

---

### Python-CSSL Bridge

```python
from includecpp import CSSL

CSSL.CsslLang()

# Syntax checker in CSSL
checker = """
global errors = stack<string>;

void checkLine(string line) {
    if (line.startsWith("def ") && !line.endsWith(":")) {
        @errors.push("Missing colon after def");
    }
    if (line.startsWith("if ") && !line.endsWith(":")) {
        @errors.push("Missing colon after if");
    }
}

define analyze() {
    string code = parameter.get(0);
    stack<string> lines = code.split("\\n");

    foreach (line in lines) {
        checkLine(line);
    }

    if (len(@errors) == 0) {
        parameter.return("OK");
    } else {
        parameter.return(@errors);
    }
}

analyze();
"""

# Check Python code
test_code = """def hello()
    print("world")"""

result = CSSL.exec(checker, test_code)
print(result)  # ["Missing colon after def"]
```

---

## Reference Table

### Keywords

| Keyword | Description |
|---------|-------------|
| `void` | Function without return |
| `return` | Return value |
| `global` | Declare global variable |
| `r@` | Alternative global syntax |
| `@` | Access global variable |
| `if` / `else if` / `else` | Conditions |
| `switch` / `case` / `default` | Switch statement |
| `for` / `foreach` / `while` | Loops |
| `break` / `continue` | Loop control |
| `try` / `catch` | Error handling |
| `undefined` | Ignore errors |
| `dynamic` | Dynamic type |
| `define` | Constant function |
| `closed` | Block external injection |
| `private` | Block all injections |
| `virtual` | Import-cycle-safe |
| `meta` | Source function |
| `super` | Forced execution |
| `shuffled` | Multiple returns |
| `open` | Any parameters |
| `structure` | User-defined type |
| `include` | Import module |

### Injection Operators

| Operator | Type | Description |
|----------|------|-------------|
| `<<==` | CodeInfusion | Replace function |
| `+<<==` | CodeInfusion | Add code (before) |
| `-<<==` | CodeInfusion | Remove code |
| `<==` | ValueCapture | Capture/assign value |
| `+<==` | BruteInjection | Copy data |
| `-<==` | BruteInjection | Move data |
| `==>` | BruteInjection | Replace data |
| `==>-` | BruteInjection | Remove matching items |

### Special Syntax

| Syntax | Description |
|--------|-------------|
| `%identifier` | Capture value at registration time |
| `json::func()` | Namespace function call |
| `@name` | Access global variable |
| `$name` | Access shared Python object |
| `s@name` | Self-reference to struct |
| `r@name` | Global variable declaration |

---

## Tips & Best Practices

1. **Type Safety**: Use explicit types instead of `dynamic` for better performance
2. **Global Variables**: Use sparingly, always access with `@`
3. **For Loops**: Python-style for simple iterations, C-style when `++`/`--` needed
4. **CodeInfusion**: Protect with `closed`/`private` when necessary
5. **Modules**: Python modules for complex logic, CSSL for business logic
6. **Error Handling**: `try/catch` for external calls, `undefined` for optional operations
7. **String Operations**: Use built-in methods instead of manual manipulation
8. **Live Objects**: Use `$name` syntax for bidirectional Python-CSSL data sharing

---

*CSSL v3.6.3 - Developed as part of IncludeCPP*
