# Reference - (mixed with same examples posted as a group earlier)

## Overview - ID: 663
/doc/overview/

---

## uCalc SDK - ID: 990
/doc/overview/ucalc-sdk/

**Description:** An overview of the uCalc SDK, a powerful toolkit for expression evaluation, text transformation, and high-performance string manipulation.

**Remarks:**

# 🚀 The uCalc SDK: A Unified Toolkit for Parsing and Transformation

The uCalc SDK is a suite of three powerful, integrated components designed for everything from evaluating simple math expressions to performing complex, rule-based text transformations. It provides ready-to-use tools for common tasks while offering the extensibility to build sophisticated parsers, custom Domain-Specific Languages (DSLs), and dynamic evaluation engines when you need more power.

This overview introduces the three pillars of the uCalc SDK and explains how their integration provides capabilities far beyond what each component can do alone.

---

## 1. ⚡ The Expression Parser

At its core is the [uCalc Fast Math Parser](/doc/overview/ucalc-fast-math-parser/), a high-performance engine for evaluating mathematical, logical, and string-based expressions. It's more than a simple calculator; it's a dynamic language environment that you can extend at runtime by defining new functions and operators. Its "Parse-Once, Evaluate-Many" architecture ensures near-native performance in loops.

*   **Use Case**: Financial modeling, scientific computing, game scripting, report generation.

---

## 2. 🧠 The Transformer

The [uCalc Transformer](/doc/overview/ucalc-sdk/) is an intelligent, token-aware engine for find-and-replace operations. Unlike character-based Regular Expressions, the Transformer understands the structure of your text, making it a safer and more powerful tool for tasks like code refactoring, static analysis, or transpiling one language to another. It uses a declarative, readable pattern syntax to define its rules.

*   **Use Case**: Code refactoring, building linters, data extraction, markup language conversion.

---

## 3. ✨ The String Library

The [uCalc.String](/doc/overview/ucalc-string/) class is a mutable, high-performance string object designed for fluent, chainable text manipulation. It operates on a "live view" model, where operations on substrings directly modify the parent string in-place. It combines the efficiency of a `StringBuilder` with a lightweight, token-aware search and replace API, making it ideal for concise "one-liner" transformations.

*   **Use Case**: Quick data extraction, in-place text modification, building complex strings in a loop.

---

## 🧩 The Power of Integration

The true power of the uCalc SDK comes from the seamless integration of these components. The most significant example is the ability to embed the full power of the **Expression Parser** directly inside a **Transformer** rule using the [`{@Eval}`](/doc/reference/patterns/pattern-methods/eval/) pattern method.

This allows you to perform calculations, call functions, and use conditional logic *during* a find-and-replace operation. A rule can capture text, convert it to a number, perform a calculation with it, and insert the formatted result back into the string—all in a single, declarative step. The practical and internal test examples below showcase this powerful synergy.

Likewise the expression parser syntax can be expanded using [uCalc.ExpressionTransformer](/doc/reference/classes/ucalc/expressiontransformer-transformer/).

**Examples:**

### Example ID: 1358

**Description:** Three core SDK components performing their primary functions independently.

**Code:**
```pseudocode
// 1. Expression Parser: Evaluate a simple math or string expression
wl("Parser Result: ", uc.Eval("(100 - 50) / 2"))
wl("Parser Result (string): ", uc.EvalStr("'Hello ' + 'World'"))

// 2. Transformer: Perform a basic find-and-replace
New(uCalc::Transformer, t)
t.FromTo("Hello", "Hi");
t.FromTo("World", "Planet");
t.SkipOver("/* {comment} */");
wl("Transformer Result: ", t.Transform("Hello World /* Was Hello World */"))

// 3. String Library: Use a fluent, chainable operation
var(uCalc::String, s) = "The value is: important";
s.After(":").ToUpper();
wl("String Library Result: ", s)


```

**Output:**
```
Parser Result: 25
Parser Result (string): Hello World
Transformer Result: Hi Planet /* Was Hello World */
String Library Result: The value is: IMPORTANT
```

---

### Example ID: 1359

**Description:** A practical, real-world example of integration: using the Transformer and Expression Parser together to create a simple template engine that replaces placeholders with evaluated data.

**Code:**
```pseudocode
// Define the data context for our template
uc.DefineVariable("user = 'Alice'");
uc.DefineVariable("score = 95");

// Define the template with placeholders
var myTemplate = "User: {user}, Score: {score * 10}, Status: {IIf(score > 90, 'Excellent', 'Good')}";

var t = uc.NewTransformer();
// This single rule finds placeholders like {...}
// and uses the Expression Parser ({@@Eval}) to evaluate the content inside.
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");

wl(t.Transform(myTemplate))

```

**Output:**
```
User: Alice, Score: 950, Status: Excellent
```

---

### Example ID: 574

**Description:** Using the parse-evaluate pattern for high-performance calculations in a loop with a changing variable.

**Code:**
```pseudocode
// Define a variable 'x' that will be updated in the loop.
var variableX = uc.DefineVariable("x");

// Parse the expression just once before the loop begins.
var parsedExpr = uc.Parse("x^2 * 10");

wl("Evaluating 'x^2 * 10' for x = 1 to 5:")
for(double x = 1 to 5)
   variableX.Value(x);
   // Evaluate is very fast as the parsing work is already done.
   wl("x = ", x, ", Result = ", parsedExpr.Evaluate())
end for
```

**Output:**
```
Evaluating 'x^2 * 10' for x = 1 to 5:
x = 1, Result = 10
x = 2, Result = 40
x = 3, Result = 90
x = 4, Result = 160
x = 5, Result = 250
```

---

---

## uCalc Fast Math Parser - ID: 931
/doc/overview/ucalc-fast-math-parser/

**Description:** An overview of uCalc's high-performance expression evaluation engine, highlighting its features, use cases, and dynamic capabilities.

**Remarks:**

# 🚀 uCalc Fast Math Parser: More Than Just a Calculator

The [uCalc Fast Math Parser](/doc/reference/classes/ucalc/introduction/) is a high-performance, embeddable engine that brings the power of a dynamic scripting language to your application. It allows you to parse and evaluate mathematical, logical, and string-based expressions provided as plain text at runtime. It's not just a calculator; it's a complete, sandboxed language environment that you can customize and extend on the fly.

This overview covers the core advantages that make the uCalc expression parser a superior choice for a wide range of applications, from financial modeling and scientific computing to game scripting and dynamic report generation.

---

## 1. ⚡ Blazing-Fast Performance: The Parse-Once, Evaluate-Many Pattern

The single most important architectural feature for performance is the separation of parsing and evaluation. While convenience methods like [EvalStr](/doc/reference/classes/ucalc/evalstr/) are great for one-off calculations, true performance is achieved by parsing an expression once and evaluating it many times.

*   **Parsing**: The computationally expensive step of analyzing a string and building an executable plan.
*   **Evaluation**: The extremely fast step of executing that plan.

By calling [Parse](/doc/reference/classes/ucalc/parse/) outside a loop and [Evaluate](/Reference/uCalcBase/Expression/Evaluate) inside, you can achieve execution speeds that approach native compiled code.

#### 💡 Why uCalc? (vs. .NET DataTable.Compute)

A common workaround for evaluating strings in .NET is `DataTable.Compute`. This method is notoriously slow because it must re-parse the expression string on every single call, making it completely unsuitable for performance-critical loops. uCalc's two-step model provides a C#-accessible engine with C++-level performance.

---

## 2. 🔧 Dynamic at Runtime: Build Your Own Language

Unlike compiled languages where the syntax is fixed, uCalc's grammar is fully extensible at runtime. You can teach the engine new tricks without recompiling your application.

*   **Custom Functions**: Use [DefineFunction](/doc/reference/classes/ucalc/definefunction/) to create new functions, either as simple inline expressions ([pseudocode]`"InToCm(x) = x * 2.54"`) or by binding to high-performance native code in your application.
*   **Custom Operators**: Use [DefineOperator](/doc/reference/classes/ucalc/defineoperator/) to invent new operators with custom precedence and associativity, allowing you to create expressive, human-readable Domain-Specific Languages (DSLs).

#### 💡 Why uCalc? (vs. Static Languages)

In C# or C++, the language's syntax is immutable. With uCalc, you can load new function and operator definitions from configuration files, user scripts, or a database at startup, allowing your application to adapt its own syntax on the fly.

---

## 3. 🛡️ Safe and Sandboxed Execution

Many scripting languages (like Python or JavaScript) include a built-in `eval()` function. While powerful, these functions often pose a major security risk because they can execute arbitrary code, potentially accessing the file system or network.

#### 💡 Why uCalc? (vs. Scripting `eval()`)

The uCalc engine is a secure sandbox. An expression can **only** access the functions, operators, and variables that you have explicitly defined within its instance. It has no intrinsic ability to interact with the host operating system, which prevents code injection vulnerabilities and ensures that user-provided formulas can be evaluated safely.

---

## 4. ✨ A Rich Built-in Library

Out of the box, the parser includes a comprehensive library of over 100 built-in [Functions and Operators](/doc/reference/functions-and-operators/functions/math/), including:
*   **Full suite of mathematical and trigonometric functions**.
*   **String manipulation functions** (`SubStr`, `UCase`, `Trim`, etc.).
*   **Logical and control-flow functions** like `IIf` (a lazily-evaluated ternary operator).

**Examples:**

### Example ID: 1266

**Description:** A simple calculation to convert a temperature from Celsius to Fahrenheit, demonstrating basic arithmetic and order of operations.

**Code:**
```pseudocode
wl(uc.EvalStr("(37) * (9 / 5) + 32"))
```

**Output:**
```
98.6
```

---

### Example ID: 1267

**Description:** Calculates a monthly loan payment by defining a custom function with the standard amortization formula, showcasing a practical, real-world use case.

**Code:**
```pseudocode
// Define a function for the standard loan payment formula
uc.DefineFunction("LoanPmt(rate, nper, pv) = Int((rate * pv) / (1 - (1 + rate)^-nper)*100)/100");

// Define variables for the calculation
uc.DefineVariable("monthly_rate = 0.05 / 12"); // 5% annual rate
uc.DefineVariable("periods = 30 * 12");      // 30 years
uc.DefineVariable("loan_amount = 200000");   // $200,000

wl(uc.EvalStr("LoanPmt(monthly_rate, periods, loan_amount)"))
```

**Output:**
```
1073.64
```

---

### Example ID: 31

**Description:** Illustrates the core relationship between the uCalc engine, an Item (variable), and a compiled Expression.

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");
var Expression = "x^2 * 10"; // Replace this with your expression

wl("--- Efficient: Parse() once, then Evaluate() in a loop ---")
var ParsedExpr = uc.Parse(Expression);
for(double x = 1 to 10)
   VariableX.Value(x);
   wl(ParsedExpr.Evaluate())
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
--- Efficient: Parse() once, then Evaluate() in a loop ---
10
40
90
160
250
360
490
640
810
1000
```

---

---

## uCalc String - ID: 932
/doc/overview/ucalc-string/

**Description:** An overview of the uCalc.String class, a mutable, token-aware string object designed for high-performance, chainable text manipulation.

**Remarks:**

# ✨ uCalc.String: The Smart String Builder

The [uCalc.String](/doc/reference/classes/ucalc-string/introduction) object is a powerful, mutable string class designed for high-performance text manipulation. It goes far beyond a standard string or `StringBuilder`, acting as a hybrid of three components in one:

1.  **A Mutable String Builder**: Efficiently modify, append, and replace text without the performance penalty of creating new string objects for every change.
2.  **A Lightweight Transformation Engine**: Perform token-aware find-and-replace operations using a fluent, chainable API.
3.  **A List Processor**: Treat a string's contents—or the results of a search—as a collection that can be iterated, filtered, and transformed.

Its core design philosophy is to provide a rich, fluent interface for single-string operations. For managing complex sets of reusable rules or multi-pass transformations, the more powerful [uCalc.Transformer](/doc/reference/classes/ucalc-transformer/introduction/) is the preferred tool.

---

## ⚙️ Core Concepts

### 1. ⚡ Mutability and Performance
Unlike native `string` types in C# and other languages, which are immutable, `uCalc.String` is designed to be modified **in-place**. This makes it highly efficient for building or manipulating strings in a loop.

### 2. 🧠 Token-Aware Operations
By default, all operations (like [SubString](/doc/reference/classes/ucalc-string/substring/), [After](/doc/reference/classes/ucalc-string/after/), and [Before](/doc/reference/classes/ucalc-string/before/)) are **token-based**, not character-based. The string is first broken down into tokens (words, numbers, symbols), and operations are performed on this stream. This provides structural awareness, safely handling nested brackets, quotes, and comments.

### 3. ⛓️ Chaining and Live Views
Methods that extract a portion of a string (e.g., [SubString](/doc/reference/classes/ucalc-string/substring/), [After](/doc/reference/classes/ucalc-string/after/), [Between](/doc/reference/classes/ucalc-string/between/)) do not create a disconnected copy. Instead, they return a new `uCalc.String` object that is a **live, modifiable view** into the parent.

*   Operations are chained, flowing from parent to child.
*   Modifying a child string directly modifies the content of its parent.

This architecture enables powerful, non-destructive editing pipelines.

### 4. 📜 List-like Behavior
After a [Find()](/doc/reference/classes/ucalc-string/find/) operation or by calling methods like [ListOfTokens()](/Reference/uCalcBase/String/ListOfTokens), the `uCalc.String` object begins to act like a collection of results. Subsequent chained operations are then applied to each item in that collection, enabling powerful batch processing with methods like [Map()](/doc/reference/classes/ucalc-string/map/).

---

## `uCalc.String` vs. `Transformer`

It's important to choose the right tool for the job. While both share the same underlying tokenization engine, they offer different interfaces for different tasks:

*   **[uCalc.String](/doc/reference/classes/ucalc-string/constructor/)**: Best for fluent, single-string "one-liner" transformations. Think of it as a scripting tool for quick modifications and data extraction on a single piece of text.

*   **[Transformer](/doc/reference/classes/ucalc-transformer/constructor/)**: Best for building a robust, rule-based system. It excels at managing a complex set of reusable rules or performing multi-pass transformations. Think of it as a compiler for text.

---

## uCalc Transformer - ID: 672
/doc/overview/ucalc-transformer/

**Description:** An overview of uCalc's token-aware text transformation engine, which uses declarative patterns to find, replace, and restructure text.

**Remarks:**

# 🧠 The uCalc Transformer

The uCalc Transformer is a powerful, token-aware engine for finding, replacing, and restructuring text. It serves as a more intelligent and safer alternative to traditional tools like Regular Expressions (Regex), especially when working with structured data such as source code, configuration files, or markup languages.

While the [uCalc.String](/doc/reference/classes/ucalc-string/introduction/) class is ideal for simple, fluent, "one-liner" manipulations, the [Transformer](/doc/reference/classes/ucalc-transformer/introduction/) is the tool of choice for building robust, rule-based systems. It is the engine that powers static analysis, code refactoring, transpilation, and complex data extraction tasks in uCalc.

## Core Concepts: Beyond Simple String Replacement

The Transformer's power comes from a few fundamental concepts that set it apart from character-based tools.

### 1. Token-Awareness: The Key to Safety

This is the most critical difference between the Transformer and Regex. Before any matching occurs, the Transformer's [tokenizer](/doc/reference/patterns/introduction/tokens/) (or lexer) breaks the input string into a stream of meaningful **tokens**: words, numbers, operators, string literals, and comments.

*   **Regex sees a flat stream of characters.**
*   **The Transformer sees a structured stream of tokens.**

This structural awareness prevents the most common and dangerous bugs associated with using Regex for code manipulation, such as accidentally changing text inside a string literal or a comment. For a detailed comparison, see the [Structural Awareness (Tokens vs. Regex)](/doc/tutorials/beyond-the-basics-what-makes-ucalc-special/structural-awareness-tokens-vs-regex) topic.

### 2. Declarative, Readable Patterns

Transformer rules are defined using a declarative [pattern syntax](/doc/reference/patterns/introduction/syntax-definitions/) that is designed to be human-readable. Instead of cryptic regex like `(?<=\s)\w+(?=\s)`, you use clear, token-based patterns.

*   **Anchors**: Literal text like `ID:`.
*   **Variables**: Capture dynamic content with `{name}`.
*   **Token Categories**: Match types of content, such as `{@Number}` or `{@String}`.

This approach makes rules easier to write, debug, and maintain.

### 3. Intelligent Replacements

Replacements are not limited to static text. The replacement string can include:

*   **Backreferences** to captured variables (e.g., `{name}`).
*   **Conditional logic** to include text only if an optional variable was matched.
*   **Embedded expressions** using [`{@Eval}`](/doc/reference/patterns/pattern-methods/eval/) to perform calculations or call functions during the replacement. See the [Executing Logic in Replacements](/doc/tutorials/text-transformation-the-transformer/executing-logic-in-replacements/) tutorial.

### 4. Hierarchical Parsing

For nested data formats like HTML or XML, the Transformer supports hierarchical parsing via the [LocalTransformer](/doc/reference/classes/ucalc-rule/localtransformer-transformer/) property. This allows you to define rules that apply only within the scope of a parent match, enabling you to parse nested structures with ease. See the [Hierarchical Parsing (LocalTransformer)](/doc/tutorials/beyond-the-basics-what-makes-ucalc-special/hierarchical-parsing-localtransformer/) topic.

---
Ready to get started? Head over to the [Your First Transformation](/doc/tutorials/text-transformation-the-transformer/your-first-transformation/) tutorial.

**Examples:**

### Example ID: 1263

**Description:** A simple word replacement to demonstrate the basic find-and-replace capability.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
t.FromTo("red", "blue");
wl(t.Transform("The red car and the red house."))
End Using;
```

**Output:**
```
The blue car and the blue house.
```

---

### Example ID: 1264

**Description:** Demonstrates the Transformer's token-aware safety by correctly renaming a variable without corrupting a string literal or comment.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// Turn single-line comments into whitespace tokens (to be ignored)
t.@Tokens().Add("//.*", TokenType::Whitespace);

// Define a rule to replace the alphanumeric token 'x' with 'value'
t.FromTo("x", "value");

var code = "x = 10; print('The max value is x.'); // x is 10 here";

// The Transformer correctly identifies that only the first 'x' is
// a token on its own. Imbedded occurrences of 'x' are left alone.
wl(t.Transform(code))
```

**Output:**
```
value = 10; print('The max value is x.'); // x is 10 here
```

---

### Example ID: 1265

**Description:** LIFO (Last-In, First-Out) precedence of rules with overlapping anchors.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
var text = "An apple, an apple pie, and an apple cider.";

// Rule 1 (Lowest precedence for this anchor)
t.FromTo("an apple", "[FRUIT]");

// Rule 2 (Higher precedence)
t.FromTo("an apple pie", "[DESSERT]");

// The transformer will match "an apple pie" first because it was defined last.
// For the remaining "an apple" occurrences, it will fall back to the first rule.
wl(t.Transform(text))
End Using;
```

**Output:**
```
[FRUIT], [DESSERT], and [FRUIT] cider.
```

---

---

## Tutorials - ID: 665
/doc/tutorials/

**Description:** Step-by-step guides to learning and using the uCalc library.

---

## Introduction to uCalc - ID: 888
/doc/tutorials/introduction-to-ucalc/

**Description:** Step-by-step guides to learning and using the uCalc library, from basic expressions to advanced text transformation.

**Remarks:**

# 🚀 Welcome to the uCalc Tutorials!

This series of tutorials is designed to guide you from your very first expression to building complex, custom parsing logic. Each section builds on the last, providing a clear learning path for mastering the uCalc library.

Whether you need a high-performance math evaluator, a powerful text transformation engine, or a tool to build your own domain-specific language (DSL), this is the place to start.

For a quick overview of all features, you can also visit the [Concepts](/Concepts) section.

---

## What is uCalc? - ID: 918
/doc/tutorials/introduction-to-ucalc/what-is-ucalc?/

**Description:** This page describes some of uCalc's unique advantages over traditional tools like Regex and simple evaluators through compelling, real-world examples.

**Remarks:**

# 🤔 Why uCalc? A Quick Tour

You've heard that uCalc is a parser, but what does that really mean? And why would you choose it over familiar tools like Regular Expressions or built-in language features?

This quick tour will answer that question by showing you the core advantages that make uCalc uniquely powerful.

## 1. 🚀 The Expression Parser: More Than Just Math

Many tools can evaluate a simple math string. But [uCalc's expression engine](/reference/classes/ucalc/introduction) is a full-featured, dynamic language environment.

**The uCalc Advantage: Runtime Customization**

You can define [new functions](/reference/classes/ucalc/definefunction) and [operators](/reference/classes/ucalc/defineoperator) **at runtime** without recompiling your application. This allows you to build custom, domain-specific languages (DSLs) on the fly.

For example, you can teach uCalc a new function in a single line:
```pseudocode
// Define a new function directly in the engine
uc.DefineFunction("InToCm(inches) = inches * 2.54");

// Now you can use it immediately
wl(uc.EvalStr("InToCm(10)")); // Output: 25.4
```
This dynamic nature goes far beyond simple evaluators and opens the door to creating powerful, user-configurable applications.

## 2. 🧠 The Transformer: Smarter Than Regex

This is the most important difference to understand. **Regex is character-aware; uCalc's Transformer is token-aware.**

What does that mean? It means the [Transformer](/reference/classes/ucalc-transformer/introduction) understands the *structure* of your text. It knows the difference between a variable name, a number, a string literal, and a comment. Regex just sees a stream of characters.

**The Classic Regex Problem**

Imagine you want to rename the variable `rate` to `annual_rate` in this line of code:
[pseudocode]`rate = 0.05; print("Current rate is: " + rate);`

A simple Regex find-and-replace for the word "rate" would incorrectly change it *everywhere*, including inside the string literal, corrupting your output.

**The uCalc Advantage: Structural Safety**

Because the [Transformer](reference/classes/ucalc-transformer/introduction) tokenizes the text first, it knows that `"Current rate is: "` is a single, atomic string token. A rule to replace the variable `rate` will not even look inside the string, preventing the error. The example below demonstrates this perfectly.

## 3. 🧩 The Big Picture: A Unified Engine

The Expression Parser and the [Transformer](reference/classes/ucalc-transformer/introduction) are not separate tools; they are two parts of a single, integrated engine. You can use the full power of the expression parser directly inside your transformation rules. This enables you to perform calculations, call functions, and use conditional logic during a find-and-replace operation, a capability far beyond standard tools.

---

Ready to see it in action? The next step will guide you through installing uCalc and running your first project.

**Examples:**

### Example ID: 1172

**Description:** Demonstrates the power of token-awareness by safely renaming a variable while ignoring its name inside a string literal—a common failure point for character-based Regex.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// A snippet of code where 'rate' is both a variable and part of a string
var source_code = [verbatim]rate = 0.05; // Set default rate
print("Current rate is: " + rate);[/verbatim];

wl("Original Code:")
wl(source_code)
wl("")

// Define a rule to rename the VARIABLE 'rate' to 'annual_rate'
t.FromTo("rate", "annual_rate");
t.SkipOver("// {text}");

// Run the transformation. The 'rate' inside the string is untouched.
wl("Transformed Code:")
wl(t.Transform(source_code))
```

**Output:**
```
Original Code:
rate = 0.05; // Set default rate
print("Current rate is: " + rate);

Transformed Code:
annual_rate = 0.05; // Set default rate
print("Current rate is: " + annual_rate);
```

---

---

## Why uCalc?  A Quick Tour - ID: 919
/doc/tutorials/introduction-to-ucalc/why-ucalc?--a-quick-tour/

**Description:** This page explains some of uCalc's unique advantages over conventional tools like Regex and simple expression evaluators.

**Remarks:**

# ✨ Why uCalc? A Quick Tour

Before diving into the details, let's take a quick tour of what makes uCalc special. Most developers are familiar with tools like Regular Expressions (Regex) for text processing and simple `eval()` functions for math. uCalc goes far beyond these, offering a more powerful, safer, and more flexible approach to parsing and transformation. 

This page highlights three core advantages you won't find in most conventional tools.

---

## 1. Safety Through Token-Awareness

**The Problem with Regex:** Regular expressions are powerful but 'blind'. They see a stream of characters, not a structured language. This makes them dangerous for code transformation. A simple search-and-replace can easily corrupt code by changing text inside a string literal or comment.

**The uCalc Solution:** uCalc first breaks text into meaningful [tokens](/reference/classes/ucalc-tokens/introduction) (words, numbers, strings, etc.). Its [Transformer](/reference/classes/ucalc-transformer/introduction) operates on these tokens, giving it structural awareness. By default, it knows not to look inside a string, making refactoring safe and predictable.

#### Example: Safely Renaming a Variable

Imagine you want to rename the variable `x` to `value`. A simple regex would incorrectly change the `x` inside the string literal.

*   **Input**: `if (x > 10) print("Max value is x");`
*   **Regex Replace**: `if (value > 10) print("Max value is value");` 🔴 **(Incorrect!)**
*   **uCalc Transform**: `if (value > 10) print("Max value is x");` 🟢 **(Correct!)**

This safety is a core architectural advantage, especially for building static analysis tools, linters, or code transpilers.

---

## 2. Dynamic Syntax at Runtime

**The Problem with Compiled Languages:** The syntax of languages like C# and C++ is fixed at compile time. You can't invent a new operator or keyword without modifying the compiler itself. Parser generators like ANTLR are also static; changes require regenerating code and recompiling.

**The uCalc Solution:** uCalc's grammar is fully dynamic. You can define new operators, functions, and even literal formats at **runtime**. This allows you to create your own expressive, domain-specific languages (DSLs) tailored to your application's needs.

#### Example: Creating a Custom `to` Operator

Let's create a custom `to` operator to generate a sequence of numbers, a feature common in languages like Swift or Kotlin.

```pseudocode
// Define a new operator at runtime
uc.DefineOperator("{start} to {end} = ForLoop(i, start, end, 1, print(i))", 50);

// Now you can use it directly in an expression
uc.Eval("1 to 5");
```

This runtime extensibility is impossible with static parsers and allows you to build highly adaptable and user-configurable systems.

---

## 3. Lazy Evaluation and Metaprogramming

**The Problem with Simple Evaluators:** Standard `eval()` functions and simple expression parsers typically evaluate all arguments immediately. This prevents you from creating custom control structures (like loops or conditional statements) where an argument should only be executed if a certain condition is met.

**The uCalc Solution:** uCalc supports **lazy evaluation** through the [ByExpr](/tutorials/beyond-the-basics-what-makes-ucalc-special/lazy-evaluation-byexpr) parameter modifier. When used, an argument is passed not as a value, but as an unevaluated [Expression](/reference/classes/ucalc-expression/introduction) object. The function can then decide when, or even if, to execute it.

#### Example: Creating a Custom `Repeat` Function

Let's build a function that repeats an action `N` times. The action is passed as an expression that the function will evaluate in a loop.

```pseudocode
[head]
[callback MyRepeat]
  var(int, count) = cb.ArgInt32(1);
  var(Expression, action) = cb.ArgExpr(2);

  for(int i = 1 to count)
    action.Execute();
  end for
[/callback]
[body]
// Define a variable to be modified
uc.DefineVariable("counter = 0");

// The 'action' (counter++) is passed unevaluated
uc.DefineFunction("Repeat(count, ByExpr action)", MyRepeat);

// Run the custom loop
uc.Eval("Repeat(5, counter++)");

wl(uc.Eval("counter")); // Output: 5
```

This capability elevates uCalc from a simple calculator to a lightweight scripting engine, allowing you to implement custom control flow and other advanced logic.

**Examples:**

### Example ID: 1173

**Description:** Demonstrates how uCalc's token-aware Transformer safely renames a variable without corrupting a string literal, a common failure point for Regex.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// A rule to replace the alphanumeric token 'x' with 'value'
t.FromTo("x", "value");

// The input string where 'x' appears both as a variable and inside a string
var code = [verbatim]if (x > 10) print("Max value is x");[/verbatim];

// The transformation correctly ignores the 'x' inside the quoted string
wl(t.Transform(code))
```

**Output:**
```
if (value > 10) print("Max value is x");
```

---

### Example ID: 1175

**Description:** Illustrates lazy evaluation by creating a custom 'Repeat' function that executes a code block (passed with `ByExpr`) a specified number of times.

**Code:**
```pseudocode
[head]
[callback MyRepeat]
  var count = cb.ArgInt32(1);
  var action = cb.ArgExpr(2);

  for(int i = 1 to count)
    action.Execute(); // Evaluate the passed-in expression
  end for
[/callback]

[body]
// Define a variable that our action will modify
uc.DefineVariable("counter = 0");

// Define the function. The 'action' parameter is marked with ByExpr
// to ensure it's passed as an unevaluated expression object.
uc.DefineFunction("Repeat(count As Int, ByExpr action)", MyRepeat);

// Call the custom Repeat function. The expression 'counter++' is not
// evaluated here; it's passed to the callback to be executed in a loop.
uc.Eval("Repeat(5, counter++)");

// Verify the side effect
wl("Final counter value: ", uc.Eval("counter"))
```

**Output:**
```
Final counter value: 5
```

---

---

## Installation And Your First Project - ID: 920
/doc/tutorials/introduction-to-ucalc/installation-and-your-first-project/

**Description:** This page guides you through installing the uCalc library and writing your first 'Hello, World!' expression.

**Remarks:**

# 🚀 Installation and Your First Project

Welcome to uCalc! This guide will walk you through installing the library and writing your first line of code. Whether you prefer modern package managers or a manual setup, you'll be up and running in minutes.

## 1. Installation

We recommend using a package manager for the easiest setup, but manual installation is also fully supported.

### The Easy Way: NuGet package manager

NuGet handles dependencies, toolchain integration, and updates automatically.  If you are using Visual Studio, do the following:

* From the menu, select `Project > Manage NuGet Packages ...`

* If uCalc is still in pre-release, check-mark `Include prerelease`

* Search for uCalcSoftware.  For native C++, search for uCalcSoftware.Cpp

* Install

* For C++, simply add `#include <uCalc.h>` and you're ready to go.

* For C#, simply add `using uCalcSoftware;` and you're ready to go.

* For VB, simply add `Imports uCalcSoftware` and you're ready to go.

If you are on a non-Windows platform, or you are not using Visual Studio, then you can use NuGet commands, such as `dotnet add package uCalcSoftware` (for C++ it's uCalcSoftware.Cpp).  If you are installing a prerelease, add `--prerelease` to the command.

### C++ cmake
```
find_package(uCalc REQUIRED PATHS "./uCalc_SDK/cmake")
target_link_libraries(TheirApp PRIVATE uCalc::uCalc)
```

### The Manual Way: DLLs & Headers

If you prefer a manual setup, download <br>[uCalc_SDK.%UCALC_SDK_VERSION%.zip](https://www.ucalc.com/downloads/uCalc_SDK.%UCALC_SDK_VERSION%.zip "Download the uCalc SDK")<br>or [uCalc_SDK.%UCALC_SDK_VERSION%.tar.gz](https://www.ucalc.com/downloads/uCalc_SDK.%UCALC_SDK_VERSION%.tar.gz "Download the uCalc SDK")<br> and unzip it.  Find the header for your language: 

`uCalc.h` is in `uCalc_SDK\include\`<br>
`uCalc.cs` and `uCalc.vb` are in `uCalc_SDK\wrappers\`

Depending on your platform, find library files such as uCalc.dll, uCalc.lib, libuCalc.so, libuCalc.dylib in the following folders: linux-arm64, linux-x64, osx-universal, win-arm64, win-x64, or win-x86. and copy them to the appropriate locations for your platform.  Then

* For C++, simply add `#include "uCalc.h"` and you're ready to go.

* For C#, simply add `using uCalcSoftware;` and you're ready to go.

* For VB, simply add `Imports uCalcSoftware` and you're ready to go.

 follow the steps for your platform and language.

## 2. Your First Project: "Hello, uCalc!"

Let's evaluate a simple math expression. This example uses the modern, simplified syntax for creating and evaluating expressions.

The core object is the [uCalc.Expression](/tutorials/beyond-the-basics-what-makes-ucalc-special/lazy-evaluation-byexpr). Thanks to uCalc's built-in shortcuts, you can treat it much like a native variable, assigning new formulas as strings and retrieving results just as easily. For more details, see the [Shortcut notations](/Concepts/Shortcut-notations) topic.

The following code creates an expression, reassigns it a new formula, and prints the result to the console.

**Examples:**

### Example ID: 1176

**Description:** A 'Hello, World!' example demonstrating the creation and evaluation of an expression using the modern, simplified syntax.

**Code:**
```pseudocode
// Create a new Expression object with an initial formula.
// This uses the default uCalc instance for context.
New(uCalc::Expression, expr("1 + 1"))

// Implicitly calls .EvaluateStr() when used in a string context
wl("Initial value: ", expr)

// Reassign the expression to a new formula with a simple string assignment.
// This implicitly calls .Parse() behind the scenes.
expr = "10 * (5 + 3)";

// Retrieve the result. For numeric results, you can assign it
// directly to a double. This implicitly calls .Evaluate().
var(double, result) = expr;
w("New value: ", result)
```

**Output:**
```
Initial value: 2
New value: 80
```

---

---

## Getting Started: The Expression Parser - ID: 895
/doc/tutorials/getting-started:-the-expression-parser/

---

## Your First Expression - ID: 899
/doc/tutorials/getting-started:-the-expression-parser/your-first-expression/

**Description:** Learn how to parse and evaluate your first mathematical or logical expression using uCalc's core functions.

**Remarks:**

# ✅ Your First Expression

Welcome to your first step in using uCalc! At its core, uCalc is an engine that can understand and compute expressions provided as plain text strings. This is the foundation for everything else the library can do.

## The `EvalStr` Method

The easiest way to evaluate an expression is with the `EvalStr` method. It's a powerful, one-step function that takes a string, processes it, and returns the result as a string. It's the perfect starting point because it's both versatile and safe.

Let's try it with a simple arithmetic expression. In all our examples, the `uc` object is an implicitly available instance of the main [uCalc](/reference/classes/ucalc/introduction) class.

```pseudocode
w("The result of 5 * 10 is: ");
wl(uc.EvalStr("5 * 10"));
```

When this code runs, uCalc performs three actions behind the scenes:
1.  **Parses**: It reads the string `"5 * 10"` and breaks it into tokens: the number `5`, the multiplication operator `*`, and the number `10`.
2.  **Evaluates**: It executes the parsed instruction, calculating the result `50`.
3.  **Returns String**: It converts the result to a string (`"50"`) and returns it.

Because [EvalStr](/Reference/uCalcBase/uCalc/EvalStr) can handle any data type and returns errors as plain text messages, it's the most robust method for handling dynamic or user-provided input.

## 💡 Why uCalc? (Comparative Analysis)

How would you normally evaluate a string expression without a dedicated library?

*   **In .NET (C#/VB)**: A common workaround is using the `DataTable.Compute` method. This is notoriously slow, limited to simple arithmetic, and lacks features like custom functions or advanced operators. uCalc's [EvalStr](/Reference/uCalcBase/uCalc/EvalStr) is part of a high-performance, full-featured parsing engine that is orders of magnitude more powerful.

*   **In Scripting Languages (JavaScript/Python)**: These languages have a built-in `eval()` function. While powerful, they are often a security risk because they can execute arbitrary code. uCalc's engine is a secure sandbox; it can only execute the functions and access the variables you have explicitly defined, preventing code injection vulnerabilities.

Now that you've seen the basics, let's explore a few more examples.

**Examples:**

### Example ID: 1177

**Description:** Evaluating a basic arithmetic expression with multiple operators.

**Code:**
```pseudocode
wl(uc.EvalStr("10 * 5 + 3"))
```

**Output:**
```
53
```

---

### Example ID: 1178

**Description:** Calculating a simple percentage for a real-world financial scenario.

**Code:**
```pseudocode
// Calculate a 15% discount on a price of $75
w("Discounted price: ")
wl(uc.EvalStr("75 * (1 - 0.15)"))
```

**Output:**
```
Discounted price: 63.75
```

---

### Example ID: 1179

**Description:** Internal Test: Verify correct order of operations with mixed operators and parentheses.

**Code:**
```pseudocode
// This tests the precedence of power (^), multiplication (*), and addition (+).
// The correct evaluation is 5 + (2 * (3^2)) -> 5 + (2 * 9) -> 5 + 18 -> 23.
wl(uc.EvalStr("5 + 2 * 3^2"))
```

**Output:**
```
23
```

---

---

## Working with Variables - ID: 900
/doc/tutorials/getting-started:-the-expression-parser/working-with-variables/

**Description:** Learn how to define, use, and programmatically manipulate variables within the uCalc expression engine.

**Remarks:**

# 💾 Working with Variables

Variables are named placeholders that store values for use in your expressions. They are fundamental to creating dynamic and reusable logic in uCalc. Unlike constants, the value of a variable can be changed at any time.

---

## 1. Defining and Using Variables

The easiest way to create a variable is with the [DefineVariable](/Reference/uCalcBase/uCalc/DefineVariable) method. You can define its name, data type, and initial value in a single, readable string.

```pseudocode
// Define a variable 'rate' with an initial value of 0.05
uc.DefineVariable("rate = 0.05");

// Use the variable in an expression
wl(uc.EvalStr("100 * rate")); // Output: 5
```

### Type Inference and Explicit Typing

uCalc automatically infers the data type from the initial value:
*   `x = 10` becomes a numeric type (usually `Double`).
*   `name = 'Alice'` becomes a `String`.

You can also explicitly declare a type using the `As` keyword, which is useful for ensuring type safety or optimizing memory usage.

```pseudocode
// Explicitly define an integer variable
uc.DefineVariable("counter As Int = 0");
```

---

## 2. Interacting from Host Code

For high-performance applications, especially those involving loops, repeatedly calling [EvalStr](/Reference/uCalcBase/uCalc/EvalStr) to set a variable's value is inefficient because it requires parsing a string every time. The recommended approach is to get a handle to the variable's [Item](/Reference/uCalcBase/Item) object and modify its value directly from your host code (C#, C++, etc.).

```pseudocode
// Get a handle to the variable when you define it
var myVar = uc.DefineVariable("x");

// Parse an expression that uses the variable ONCE
var expr = uc.Parse("x * 2");

// In a loop, update the value directly and evaluate the pre-parsed expression
for (i = 1 to 3) 
    myVar.Value(i); // This is a fast, direct value update
    wl("Result: ", expr.Evaluate()); // This is a fast evaluation
end for
```

This two-step pattern (parse once, update and evaluate many times) is the key to achieving high performance with uCalc.

---

## 💡 Why uCalc? (Comparative Analysis)

*   **vs. C#/C++**: Variables in compiled languages are defined at compile-time. uCalc's variables are created **at runtime**, allowing you to build dynamic systems where variables can be defined based on user input, configuration files, or other runtime conditions.

*   **vs. Dynamic Languages (Python, JavaScript)**: While also dynamic, uCalc provides a sandboxed environment with a clear distinction between the host application and the script engine. The programmatic interaction via `Item.Value()` offers a highly optimized bridge between these two worlds.

*   **Host Memory Binding**: For ultimate performance, uCalc allows you to bind a variable directly to a memory address in your host application using an optional parameter in [DefineVariable](/Reference/uCalcBase/uCalc/DefineVariable). This creates a zero-copy link, which is a powerful feature for tight integrations.

**Examples:**

### Example ID: 1180

**Description:** A basic example of defining a variable and using it in an expression.

**Code:**
```pseudocode
uc.DefineVariable("x = 10");
wl(uc.EvalStr("x * 5"))
```

**Output:**
```
50
```

---

### Example ID: 1181

**Description:** Calculates simple interest using pre-defined variables for a real-world scenario.

**Code:**
```pseudocode
uc.DefineVariable("principal = 5000");
uc.DefineVariable("rate = 0.05");
uc.DefineVariable("years = 4");
wl("Interest: ", uc.EvalStr("principal * rate * years"))
```

**Output:**
```
Interest: 1000
```

---

### Example ID: 1182

**Description:** Internal Test: Tests programmatic updates to a variable from host code in a loop, a common high-performance pattern.

**Code:**
```pseudocode
var myVar = uc.DefineVariable("x");
var expr = uc.Parse("x * 2");

var i = 0;
for (i = 1 to 5)
  myVar.Value(i);
  wl("When x is ", i, ", result is: ", expr.Evaluate())
end for
```

**Output:**
```
When x is 1, result is: 2
When x is 2, result is: 4
When x is 3, result is: 6
When x is 4, result is: 8
When x is 5, result is: 10
```

---

---

## Using Built-in Functions - ID: 901
/doc/tutorials/getting-started:-the-expression-parser/using-built-in-functions/

**Description:** Explores how to use the rich library of built-in functions for math, string manipulation, and logic within uCalc expressions.

**Remarks:**

# Built-in Functions

uCalc comes with a comprehensive library of built-in functions that will feel familiar to developers coming from C++, C#, Visual Basic, or spreadsheet applications like Excel. These functions provide the core toolkit for performing mathematical calculations, string manipulation, and logical operations directly within an expression string.

You can call any built-in function by its name, followed by its arguments in parentheses, just as you would in a standard programming language.

```pseudocode
// A simple expression combining math and string functions
uc.EvalStr("Abs(-10) + Length('hello')") // Output: 15
```

For a complete list of all functions, see the [Functions and Operators](/Reference/Functions-and-Operators/Functions/Math) reference section.

--- 

## Function Categories

Built-in functions are grouped into several logical categories:

### 📐 Math Functions
This is the largest category, providing a full suite of trigonometric, logarithmic, rounding, and power functions. It includes everything from basic `Abs()` and `Sqrt()` to advanced operations like `Tgamma()` and `Hypot()`.

[pseudocode]`wl(uc.Eval("Sin(PI/2) * Pow(2, 10)")); // Output: 1024`

### 🧵 String Functions
This category includes functions for creating, modifying, and inspecting strings. You can perform operations like concatenation (`+`), finding substrings (`IndexOf`), changing case (`UCase`), and more.

[pseudocode]`wl(uc.EvalStr("SubStr('Hello World', 6, 5)")); // Output: World`

### 🧩 Logic & Specialized Functions
This category contains functions for conditional logic, type conversion, and interacting with the engine itself. The most important of these is `IIf()`, uCalc's equivalent of the ternary operator (`condition ? true_part : false_part`). It uses lazy evaluation via `ByExpr` arguments, meaning it only evaluates the branch that is chosen.

[pseudocode]`wl(uc.EvalStr("IIf(10 > 5, 'Greater', 'Lesser')")); // Output: Greater`

--- 

## 💡 Why uCalc? (Comparative Analysis)

### vs. Statically Compiled Languages (C#, C++)
The primary advantage is **dynamism**. In C# or C++, function calls are resolved at compile time. With uCalc, an entire expression, including calls to multiple built-in functions, can be constructed as a string at **runtime**. This is fundamental for applications where the logic is not known ahead of time, such as:

*   **Report Generators**: Users can type formulas like `Avg(sales) * (1 + TAX_RATE)` into a text field.
*   **Game Scripting**: Define character behaviors or game rules in configuration files.
*   **Scientific Modeling**: Allow researchers to input complex mathematical formulas without needing to recompile the application.

### vs. Other Evaluators (Excel, SQL)
While spreadsheet and database languages also have built-in functions, uCalc provides a more complete programming environment. You are not limited to a single formula in a cell or a query. You can define variables, create custom functions, and build complex, multi-step logic that leverages the built-in function library as its foundation.

**Examples:**

### Example ID: 1183

**Description:** A simple example demonstrating a few of the most common math, logic, and string functions.

**Code:**
```pseudocode
wl("Square root of 81 is: ", uc.Eval("Sqrt(81)"))
wl("Is 10 greater than 5? ", uc.EvalStr("IIf(10 > 5, 'Yes', 'No')"))
wl("String length: ", uc.Eval("Length('uCalc rocks!')"))
```

**Output:**
```
Square root of 81 is: 9
Is 10 greater than 5? Yes
String length: 12
```

---

### Example ID: 1185

**Description:** Internal Test: Verifies that a built-in function using `ByHandle` arguments can correctly modify the state of variables passed to it.

**Code:**
```pseudocode
uc.DefineVariable("a = 10");
uc.DefineVariable("b = 20");

wl("Before - a: ", uc.Eval("a"), ", b: ", uc.Eval("b"))

// The built-in Swap() function uses ByHandle to modify variables directly.
uc.Eval("Swap(a, b)");

w("After - a: ", uc.Eval("a"), ", b: ", uc.Eval("b"))
```

**Output:**
```
Before - a: 10, b: 20
After - a: 20, b: 10
```

---

---

## Creating Custom Functions - ID: 902
/doc/tutorials/getting-started:-the-expression-parser/creating-custom-functions/

**Description:** Learn how to extend uCalc's expression engine by creating your own functions, either as simple inline expressions or by binding to powerful native code callbacks.

**Remarks:**

# 🛠️ Creating Custom Functions

One of uCalc's most powerful features is its runtime extensibility. You can teach the engine new functions on the fly, tailoring it to your application's domain without ever needing to recompile. This is fundamental for building Domain-Specific Languages (DSLs), creating reusable calculation libraries, or simplifying complex formulas for end-users.

There are two primary ways to create a custom function:

1.  **Inline Definition**: Define the entire function as a single string. This is the quickest and easiest method for simple mathematical or string-based logic.
2.  **Callback Binding**: Link a function signature to a function in your host application (C#, C++, etc.). This is the most powerful method, used for complex logic, I/O operations, or integrating with existing code.

---

## 1. Inline Definitions (The Easy Way)

For functions that can be expressed as a single line of logic, an inline definition is the best choice. You provide the entire signature and expression body to the [DefineFunction](/Reference/uCalcBase/uCalc/DefineFunction) method.

#### Syntax

The definition string follows a simple pattern: `FunctionName(param1, param2) = expression`.

```pseudocode
// Define a function to convert inches to centimeters.
uc.DefineFunction("InToCm(inches) = inches * 2.54");

// Now you can use it immediately in any expression.
wl(uc.Eval("InToCm(10)")); // Output: 25.4
```

This dynamic capability is a major advantage over compiled languages. You can load these function definitions at runtime from a configuration file or even allow end-users to define their own helpers.

---

## 2. Callback Binding (The Powerful Way)

When your function's logic is too complex for a single expression or needs to interact with the host application (e.g., to read a file, query a database, or update a UI), you bind it to a native **callback function**.

In this model, you provide a signature to [DefineFunction](/Reference/uCalcBase/uCalc/DefineFunction) and the address of a callback. When uCalc evaluates your function, it calls your native code, passing a special [Callback](/Reference/uCalcBase/Callback) object (`cb`) that you use to get arguments and set the return value.

```pseudocode
[head]
[callback LogMessage]
  // Get the first argument as a string.
  var(string, msg) = cb.ArgStr(1);

  // In a real app, this would write to a file or log service.
  wl("[LOG]: ", msg);
[/callback]
[body]
// Link the uCalc function "Log" to our native "LogMessage" callback.
uc.DefineFunction("Log(message As String)", LogMessage);

uc.Eval("Log('System initialized')");
```
This creates a seamless bridge between the flexible uCalc scripting environment and your high-performance native code.

---

## ✨ Advanced Argument Passing

uCalc's callback system goes beyond simple value passing, enabling powerful metaprogramming techniques with special argument modifiers.

*   **`ByRef`**: Passes a variable by reference, allowing your callback to modify its value in the caller's scope (creating an in-out parameter).
*   **`ByExpr`**: Passes the argument as an unevaluated [Expression](/Reference/uCalcBase/Expression) object. This is the key to **lazy evaluation**, allowing you to build custom control structures (like the built-in [IIf](/Reference/Functions-and-Operators/Functions/Specialized) function) that only execute the branches they need.
*   **`ByHandle`**: Passes the argument's underlying metadata object, allowing your callback to inspect its name, data type, or original expression text before deciding how to process it.

**Examples:**

### Example ID: 1186

**Description:** A simple inline function to convert inches to centimeters.

**Code:**
```pseudocode
uc.DefineFunction("InToCm(inches) = inches * 2.54");
wl(uc.Eval("InToCm(10)"))
```

**Output:**
```
25.4
```

---

### Example ID: 1187

**Description:** Practical: A callback-based logging function that prints a message to the console.

**Code:**
```pseudocode
[head]
[callback LogMessage]
  var(string, msg) = cb.ArgStr(1);
  // In a real app, this would write to a file or log service.
  wl("[LOG]: " + msg)
[/callback]
[body]
uc.DefineFunction("Log(message As String)", LogMessage);
uc.Eval("Log('System initialized')");
uc.Eval("Log('User logged in')");
```

**Output:**
```
[LOG]: System initialized
[LOG]: User logged in
```

---

### Example ID: 1188

**Description:** Internal Test: A custom `IIf` implementation using `ByExpr` to test lazy evaluation. The branches containing division by zero are never executed, preventing errors.

**Code:**
```pseudocode
[head]
[callback CustomIIf]
  var(bool, condition) = cb.ArgBool(1);
  var truePart = cb.ArgExpr(2);
  var falsePart = cb.ArgExpr(3);
  
  if (condition)
    cb.Return(truePart.Evaluate());
  else
    cb.Return(falsePart.Evaluate());
  end if
[/callback]
[body]
uc.DefineFunction("MyIIf(condition As Bool, ByExpr thenExpr, ByExpr elseExpr)", CustomIIf);

// The 'else' branch contains a division by zero, but it should NOT be evaluated
// because the condition (1 < 2) is true.
var result = uc.Eval("MyIIf(1 < 2, 100, 1/0)");
w("Result 1: ")
wl(result)

// Now test the false branch. The 'then' branch with the error is skipped.
result = uc.Eval("MyIIf(1 > 2, 1/0, 200)");
w("Result 2: ")
wl(result)
```

**Output:**
```
Result 1: 100
Result 2: 200
```

---

---

## Handling Errors - ID: 903
/doc/tutorials/getting-started:-the-expression-parser/handling-errors/

**Description:** Learn to detect, handle, and recover from parsing and evaluation errors using uCalc's state-based and callback-driven systems.

**Remarks:**

# 💣 Handling Errors

No parser is complete without robust error handling. uCalc offers a powerful and flexible system that differs from the traditional `try/catch` exception model. It provides two primary methods for dealing with errors: reactive state checking and proactive callback handling.

This tutorial covers the two main types of errors and how to manage them.

## 1. Types of Errors: Parse-Time vs. Evaluation-Time

Errors in uCalc fall into two categories:

*   **Parse-Time Errors**: These are syntax errors caught before any calculation happens. Examples include mismatched parentheses, unrecognized keywords, or invalid operators. When these occur, you can get detailed information about the location ([Error.Location](/Reference/uCalcBase/ErrorInfo/Location)) and symbol ([Error.Symbol](/Reference/uCalcBase/ErrorInfo/Symbol)) that caused the problem.
*   **Evaluation-Time Errors**: These occur after an expression has been successfully parsed, during the actual calculation. Examples include division by zero, invalid arguments passed to a function, or numeric overflow.

## 2. Reactive: Checking the Error State

The simplest way to handle errors is to check the engine's state after an operation. Every `uCalc` instance has an [Error](/Reference/uCalcBase/uCalc/Error) property that holds information about the last error.

After calling a method like [EvalStr](/Reference/uCalcBase/uCalc/EvalStr), you can check if an error occurred:
```pseudocode
var result = uc.EvalStr("5 * (10 +"); // Invalid syntax

// Check if an error was flagged
if (uc.Error.Code() != ErrorCode::None)
{
    wl("An error occurred: ", uc.Error.Message());
}
```
This approach is simple and effective for many use cases, but it's reactive—you only know about the error after it has already happened and aborted the operation.

## 3. Proactive: Using an Error Handler Callback

For more advanced control, you can register an error handler using [AddHandler](/Reference/uCalcBase/ErrorInfo/AddHandler). This callback function is automatically invoked the moment an error occurs, giving you the power to intercept, inspect, and even recover from it.

### Inside the Handler

Your callback receives a `uCalc` instance (implicitly via `uc` in examples), giving you access to the full suite of error-reporting methods:

*   **[Error.Code()](/Reference/uCalcBase/ErrorInfo/Code)**: The numeric [ErrorCode](/Reference/Enums/ErrorCode).
*   **[Error.Message()](/Reference/uCalcBase/ErrorInfo/Message)**: The human-readable error string.
*   **[Error.Symbol()](/Reference/uCalcBase/ErrorInfo/Symbol)**: The specific token that caused a parse-time error.
*   **[Error.Location()](/Reference/uCalcBase/ErrorInfo/Location)**: The character position of the parse-time error.

### Controlling the Outcome with `Error.Response`

The most powerful feature of an error handler is the ability to control what happens next by setting the [Error.Response](/Reference/uCalcBase/ErrorInfo/Response):

*   **`ErrorHandlerResponse::Abort` (Default)**: Halts execution immediately.
*   **`ErrorHandlerResponse::ReRaise`**: Passes the error to the next handler in the chain.
*   **`ErrorHandlerResponse::Resume`**: **Instructs the engine to continue execution as if the error never happened.**

## 4. Recovering from Errors with `Resume`

The `Resume` response is what makes uCalc's error handling truly unique. It allows you to fix a problem on the fly and continue.

A common use case is to automatically define variables that a user forgot to declare. The practical example below demonstrates this perfectly.

⚠️ **Important**: When you `Resume`, you **must** resolve the underlying cause of the error. If you don't, the engine will re-encounter the same error, leading to an infinite loop. uCalc has a built-in safety limit to prevent a true infinite loop, which will raise a `ReParseOverflow` error.

## 💡 Why uCalc? (Comparative Analysis)

*   **vs. `try/catch` Exceptions**: Traditional exception handling interrupts the program flow and unwinds the call stack, which can be computationally expensive. uCalc's callback system is lightweight and does not unwind the stack. This makes it highly suitable for parsing user input where errors are common and expected, not "exceptional."

*   **vs. C-Style Error Codes**: Simply returning an error code after a function call requires the developer to write boilerplate `if (error) { ... }` checks everywhere. uCalc centralizes this logic into a single, clean handler.

The ability to **recover** from an error with `Resume` is the most significant advantage. It elevates error handling from a simple failure-reporting mechanism to a dynamic, interactive recovery system, which is difficult to achieve with standard `try/catch` blocks.

**Examples:**

### Example ID: 1189

**Description:** How to reactively check for an error after an operation fails, and how a subsequent successful operation clears the error state.

**Code:**
```pseudocode
// Trigger a syntax error
uc.EvalStr("1 +");

// Check the error state after the fact
if (uc.@Error().@Code() != ErrorCode::None)
    wl("Error detected: ", uc.@Error().@Message())
else 
    wl("Success!")
end if

// Perform a successful operation, which clears the error state
uc.EvalStr("1 + 1");
if (uc.@Error().@Code() == ErrorCode::None)
    wl("Previous error was cleared by successful operation.")
end if
```

**Output:**
```
Error detected: Syntax error
Previous error was cleared by successful operation.
```

---

### Example ID: 1190

**Description:** A practical example of a proactive error handler that automatically defines undeclared variables on the fly, allowing the expression to successfully resume execution.

**Code:**
```pseudocode
[head]
// This handler automatically defines variables when they are first used.
[callback:u AutoDefineHandler]
  // Check if the error is specifically an undefined identifier
  if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
    wl("Handler: '", uc.@Error().@Symbol(), "' is undefined. Defining it now.")
    uc.DefineVariable(uc.@Error().@Symbol());
    
    // Tell the engine to resume the operation
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
  end if
[/callback]

[body]
uc.@Error().AddHandler(AutoDefineHandler);

// 'my_var' doesn't exist yet, but the handler will create it.
var result = uc.EvalStr("my_var = 100; my_var = my_var * 2");

wl("Final result: ", result)
```

**Output:**
```
Handler: 'my_var' is undefined. Defining it now.
Final result: 200
```

---

---

## Optimizing Performance in Loops - ID: 904
/doc/tutorials/getting-started:-the-expression-parser/optimizing-performance-in-loops/

**Description:** Explains the 'Parse-Once, Evaluate-Many' pattern for writing high-performance expressions in loops.

**Remarks:**

# ⚡ Optimizing Performance: The Parse-Once, Evaluate-Many Pattern

While uCalc's expression parser is highly optimized, the single most important factor for achieving maximum performance is understanding the difference between parsing and evaluation. For expressions that are executed repeatedly, such as inside a loop, using the **"Parse-Once, Evaluate-Many"** pattern is critical.

This guide explains why this pattern is so effective and how to implement it.

## The Problem: The High Cost of Parsing

When you call a convenience method like [Eval()](/Reference/uCalcBase/uCalc/Eval) or [EvalStr()](/Reference/uCalcBase/uCalc/EvalStr), the uCalc engine performs two major steps:

1.  **Parsing**: It analyzes the string, breaks it into tokens, and builds an executable plan (an Abstract Syntax Tree). This is the most computationally expensive part.
2.  **Evaluation**: It executes the plan to produce a result.

Calling these methods inside a loop forces the engine to re-parse the same expression string over and over again, which is highly inefficient.

### 🐌 The Inefficient Way: Evaluating in a Loop

The following code is simple but will perform poorly if the loop runs many times, as `"x * x + 2"` is parsed on every single iteration.
```pseudocode
// Inefficient: The expression string is parsed on every iteration.
for (i = 1 to 1000)
    uc.DefineVariable("x = " + i);
    wl(uc.Eval("x * x + 2"));
end for
```

## The Solution: Parse Once, Evaluate Many

The correct approach is to separate the expensive parsing step from the fast evaluation step.

1.  **Parse Once**: Before the loop, call [Parse()](/Reference/uCalcBase/uCalc/Parse) to compile the expression into a reusable [Expression](/Reference/uCalcBase/Expression/Constructor) object.
2.  **Evaluate Many**: Inside the loop, call the fast `.Evaluate()` or `.EvaluateStr()` method on the pre-parsed object.

### 🚀 The High-Performance Way

This code is significantly faster because the parsing work is done only once.
```pseudocode
// Efficient: The expression is parsed once, before the loop begins.
var x_var = uc.DefineVariable("x");
var expr = uc.Parse("x * x + 2");

for (i = 1 to 1000)
    x_var.Value(i);
    // The Evaluate() step is extremely fast.
    wl(expr.Evaluate());
end for
End Using
```

### When is `Eval()` Okay?

Convenience methods like [Eval()](/Reference/uCalcBase/uCalc/Eval) and [EvalStr()](/Reference/uCalcBase/uCalc/EvalStr) are perfectly acceptable for one-off calculations or in non-performance-critical parts of your application. The "Parse-Once" pattern is specifically designed for scenarios involving repeated evaluation of the same expression structure.

## 💡 Why uCalc? (Comparative Analysis)

uCalc's two-step evaluation model provides a significant advantage over other common methods for evaluating strings at runtime.

*   **vs. C# `DataTable.Compute`**: The common .NET workaround for evaluating strings is slow and lacks features. It must re-parse the expression on every call, making it unsuitable for performance-critical loops.

*   **vs. `eval()` in Scripting Languages**: Functions like `eval()` in Python or JavaScript are also convenient but typically re-parse on every call. They also carry the overhead of a full scripting engine.

*   **vs. C# Expression Trees**: Building a compiled delegate from a C# Expression Tree provides similar performance benefits, but constructing that tree from a raw string at runtime is a complex, multi-step process. uCalc's [Parse()](/Reference/uCalcBase/uCalc/Parse) method provides a simple, direct way to get a high-performance, pre-compiled object from a string, offering the best of both worlds: runtime flexibility and near-native execution speed.

**Examples:**

### Example ID: 1192

**Description:** A minimal example demonstrating the basic 'Parse once, Evaluate many' pattern.

**Code:**
```pseudocode
// 1. Parse the expression string once to create a reusable object.
//var expr = uc.Parse("5 * 10");
NewUsing(uCalc::Expression, expr("5 * 10"))

// 2. Evaluate the pre-parsed object as many times as needed.
wl(expr.Evaluate())
wl(expr.Evaluate())

End Using // The expression object is automatically released here.
```

**Output:**
```
50
50
```

---

### Example ID: 1460

**Description:** Using the parse-evaluate pattern for high-performance calculations in a loop with a changing variable w/ stopwatch.

**Code:**
```pseudocode
var variableX = uc.DefineVariable("x");
var userExpression = "x * 2 + 5";
var Total = 0.0;
var UpperBound = 1000000; // One million

// Parse the expression just once before the loop begins.
var parsedExpr = uc.Parse(userExpression);

[NotCpp]var stopwatch = System.Diagnostics.Stopwatch.StartNew();[/NotCpp]
for(double x = 1 to UpperBound)
   variableX.Value(x);
   Total = Total + parsedExpr.Evaluate();
end for
[NotCpp]stopwatch.Stop();
//Uncomment the following line to reveal the actual speed:
//Console.WriteLine($"Elapsed Milliseconds: {stopwatch.ElapsedMilliseconds} ms");
[/NotCpp]
w("Sum(1, ", UpperBound, ", ", userExpression, ") = ", [cpp](long long)[/cpp]Total)
```

**Output:**
```
Sum(1, 1000000, x * 2 + 5) = 1000006000000
```

---

### Example ID: 1193

**Description:** A real-world example contrasting the inefficient loop with the high-performance 'Parse-Once' pattern using a changing variable.

**Code:**
```pseudocode
var x_var = uc.DefineVariable("x");
var i = 0;

// --- Inefficient Way ---
wl("--- Inefficient: Eval() in a loop ---")
for (i = 1 to 3)
    x_var.Value(i);
    wl(uc.Eval("x * x + 2"))
end for

wl("")

// --- High-Performance Way ---
wl("--- Efficient: Parse() once, Evaluate() in a loop ---")
// Parse outside the loop
var expr = uc.Parse("x * x + 2");
for (i = 1 to 3)
    x_var.Value(i);
    // Evaluate the pre-parsed object
     wl(expr.Evaluate())
end for
```

**Output:**
```
--- Inefficient: Eval() in a loop ---
3
6
11

--- Efficient: Parse() once, Evaluate() in a loop ---
3
6
11
```

---

### Example ID: 1194

**Description:** Internal Test: Verifies correct results with multiple variables and a function call within a tight loop using a pre-parsed expression.

**Code:**
```pseudocode
uc.DefineFunction("Calc(a, b) = a * 2 - b");
var x_var = uc.DefineVariable("x");
var y_var = uc.DefineVariable("y");
var i = 0;

var expr = uc.Parse("Calc(x, y) + Sqrt(x)");
for (i = 1 to 4)
    x_var.Value(i * i); // Use squared values for x
    y_var.Value(i);     // Use linear values for y
    wl(expr.Evaluate())
end for
```

**Output:**
```
2
8
18
32
```

---

---

## Text Transformation: The Transformer - ID: 896
/doc/tutorials/text-transformation:-the-transformer/

---

## Your First Transformation - ID: 905
/doc/tutorials/text-transformation:-the-transformer/your-first-transformation/

**Description:** Learn to perform your first token-aware find-and-replace operation using the uCalc Transformer.

**Remarks:**

# 🚀 Your First Transformation

Welcome to the uCalc Transformer! This is the engine's tool for structural, token-aware find-and-replace operations. It's more powerful and safer than a standard string `Replace()` function because it understands the structure of your text, distinguishing between code, numbers, and string literals.

This guide will walk you through the essential steps to perform your first transformation.

## The 4-Step Process

Every transformation follows the same basic workflow:

1.  **Create a Transformer**: Get an instance of the transformer engine.
2.  **Define Rules**: Tell the transformer what to find and what to replace it with.
3.  **Set the Text**: Provide the source string to be transformed.
4.  **Run the Transform**: Execute the operation and get the result.

Let's break down each step.

### Step 1: Create a Transformer

First, you need an instance of the [Transformer](/Reference/uCalcBase/Transformer/Constructor). You can create one from your `uCalc` object.

```pseudocode
NewUsing(uCalc::Transformer, t);
```
*Note: The `using` block ensures the transformer's resources are automatically released when it goes out of scope.*

### Step 2: Define a Rule with `FromTo()`

Next, you define the transformation logic using the [FromTo()](/Reference/uCalcBase/Transformer/FromTo) method. It takes two arguments: the pattern to find and the text to replace it with.

Our pattern will look for the word "Hello" followed by a variable named `name`.

```pseudocode
// A rule to find "Hello {name}" and replace it with "Greetings, {name}!"
t.FromTo("Hello {name}", "Greetings, {name}!");
```
Here, `{name}` is a variable that captures the word immediately following "Hello". This captured value can be used in the replacement string.

### Step 3: Set the Text

Now, provide the source string you want to modify. You can do this by assigning a string directly to the transformer object, which is a shortcut for setting its [Text](/Reference/uCalcBase/Transformer/Text) property.

```pseudocode
t = "Hello World";
```

### Step 4: Run the Transform and Get the Result

Finally, call the [Transform()](/Reference/uCalcBase/Transformer/Transform) method to execute the rules. The result can be retrieved by using the transformer object where a string is expected.

```pseudocode
wl(t.Transform());
```

### Putting It All Together

Here is the complete code from all four steps:

```pseudocode
NewUsing(uCalc::Transformer, t)
   t.FromTo("Hello {name}", "Greetings, {name}!");
   t = "Hello World";
   wl(t.Transform()); // Output: Greetings, World!
End Using;
```

## 💡 Why uCalc? (Comparative Analysis)

You might ask, "Why not just use a standard string `Replace()` function?" The power of the [Transformer](/Reference/uCalcBase/Transformer/Constructor) lies in its **token awareness**. A standard replace is character-based and "blind" to structure. The [Transformer](/Reference/uCalcBase/Transformer/Constructor) breaks text into meaningful units (tokens) first, so it knows the difference between the number `10` and the string `"10"`.

This prevents common bugs, like accidentally changing text inside a string literal when refactoring code. The next tutorial, [Capturing Text with Variables](TODO: Broken Link), will explore this concept in more detail.

**Examples:**

### Example ID: 1195

**Description:** A basic find-and-replace operation to change one word to another using a fluent, chainable syntax.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)

// Define the rule and execute the transform in a single, chained statement.
   t.FromTo("Hello", "Greetings");
   wl(t.Transform("Hello World!"))

End Using
```

**Output:**
```
Greetings World!
```

---

### Example ID: 1196

**Description:** Safely renames a variable without corrupting a string literal, demonstrating the Transformer's token-awareness.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)

// This rule replaces the ALPHANUMERIC token 'x', not just the character 'x'.
t.FromTo("x", "value");

var code = [verbatim]if (x > 10) print("Max value is x");[/verbatim];

// The 'x' inside the string is ignored because QuoteSensitive is true by default.
wl(t.Transform(code))

End Using
```

**Output:**
```
if (value > 10) print("Max value is x");
```

---

---

## Capturing Text with Variables - ID: 906
/doc/tutorials/text-transformation:-the-transformer/capturing-text-with-variables/

**Description:** Explains how to use named placeholders (variables) in patterns to capture, reuse, and validate dynamic text.

**Remarks:**

# 🎣 Capturing Text with Variables

At the heart of any parsing task is the need to find *known* text in order to extract *unknown* text. In uCalc's [Transformer](/Reference/uCalcBase/Transformer/Constructor), this is done using two simple concepts: **Anchors** and **Variables**.

*   **Anchors** are the literal, static text in your pattern that must exist in the source string. They act as guideposts for the parser. In the pattern `User: {name}`, the text `User:` is the anchor.
*   **Variables** are named placeholders enclosed in curly braces `{...}` that capture the dynamic, unknown text. In `User: {name}`, the variable `{name}` captures whatever text follows the anchor.

## How a Capture Works

By default, a variable like `{data}` is "smart lazy." It captures all text until it encounters one of three things:
1.  The next anchor defined in your pattern.
2.  A statement separator token (like a newline or semicolon).
3.  The end of the string.

This behavior is incredibly powerful because it automatically respects the natural structure of your text without requiring complex lookaheads or non-greedy specifiers common in Regex.

## Using Captured Variables

Once a variable captures text, you can re-insert it in the [replacement string](/Reference/Patterns/Introduction/Replacement) using the same `{variableName}` syntax. This allows you to reformat, wrap, or reorder the extracted data.

```pseudocode
New(uCalc::Transformer, t)
t.FromTo("Log: {message}", "[LOG] - {message}");
wl(t.Transform("Log: System ready."))
// Output: [LOG] - System ready.
```

## Backreferences: Enforcing Equality

One of the most powerful features is **backreferencing**. If you use the same variable name multiple times within the *pattern string*, uCalc enforces that the captured text for each instance must be identical. This is the key to matching balanced structures.

For example, the pattern `<{tag}>{content}</{tag}>` will correctly match `<b>text</b>` because the `{tag}` variable captures `b` in both places. It will **not** match `<b>text</i>`, preventing a common parsing error.

## 💡 Why uCalc? (Comparative Analysis)

### vs. Regular Expressions
Regex uses capture groups `(...)` and backreferences like `$1` or `\1`. uCalc's approach is superior for several reasons:
*   **Readability**: Named variables like `{user}` are far more readable and maintainable than numeric indices like `$1`.
*   **Token Awareness**: A uCalc variable like `{word}` automatically respects word boundaries. In Regex, you must manually add boundaries (`\bword\b`) to prevent partial matches inside other words.
*   **Safe Backreferences**: As shown above, matching balanced tags is simple and intuitive in uCalc, while it is often complex and fragile in Regex.

### vs. Native String Splitting
Using native functions like `string.Split()` is common but brittle.
*   **Positional Fragility**: `Split()` gives you an array of results that you must access by a numeric index (e.g., `parts[1]`). If the input format changes slightly, your indices may be wrong, leading to runtime errors.
*   **Named Access**: uCalc variables allow you to access captured data by a meaningful name, making your code more robust and self-documenting.

**Examples:**

### Example ID: 1198

**Description:** Extracts a value from a simple key-value pair.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("ID: {value}", "Found value: {value}");
wl(t.Transform("Product ID: 12345"))
```

**Output:**
```
Product Found value: 12345
```

---

### Example ID: 1199

**Description:** Parses a structured log entry and reformats it for display using multiple variables.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Note the use of {@String} to capture the quoted text
t.FromTo("'['{level}']' Code: {code}, Msg: {@String:message}",
         "[{level}] - {message} (Code {code})");

var log = "[ERROR] Code: 404, Msg: 'Not Found'";
wl(t.Transform(log))
```

**Output:**
```
[ERROR] - Not Found (Code 404)
```

---

---

## Matching by Token Category - ID: 908
/doc/tutorials/text-transformation:-the-transformer/matching-by-token-category/

**Description:** Explains how to use token category matchers like {@Number} and {@String} to create powerful, readable, and context-aware patterns.

**Remarks:**

# 🎯 Matching by Token Category

While matching literal text (like `"Hello"`) is useful, the real power of the [Transformer](/doc/reference/classes/ucalc-transformer/introduction/) comes from matching by **token category**. Instead of looking for a specific value, you can create a [pattern](/doc/reference/patterns/introduction/syntax-definitions/) that looks for a *type* of content, such as "any number," "any string," or "any word."

This is the key feature that makes the [Transformer](/doc/reference/classes/ucalc-transformer/introduction/) structurally aware and significantly more powerful than regular expressions for parsing code and structured data.

### 💡 Why Match by Category? (The Advantage over Regex)

1.  **Readability**: A [pattern](/doc/reference/patterns/introduction/syntax-definitions/) to find a number is simply `{@Number}`. The equivalent regex can be long and cryptic, like `[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?`.

2.  **Safety & Context-Awareness**: The uCalc [tokenizer](/doc/reference/patterns/introduction/tokens/) runs first, breaking text into meaningful units. It knows that `"123"` is a single string [token](/doc/reference/patterns/introduction/tokens/). A rule to find `{@Number}` will **not** match the `123` inside the string, preventing the accidental corruption of string literals—a common and dangerous pitfall of using regex for code transformation.

3.  **Maintainability**: Token definitions are centralized. If you decide to add support for a new number format (like hexadecimal `0x...`), you only need to update the number [token](/doc/reference/patterns/introduction/tokens/) definition once using [Tokens.Add()](/doc/reference/patterns/introduction/tokens/). All existing `{@Number}` patterns across your entire application will automatically support the new format without any changes.

### Syntax

The syntax uses an `@` symbol inside curly braces `{}`.

*   **Match Only**: `{@Category}` matches any [token](/doc/reference/patterns/introduction/tokens/) of that category but does not capture it.
*   **Match & Capture**: `{@Category:variableName}` matches and captures the [token](/doc/reference/patterns/introduction/tokens/)'s text into a variable for use in a replacement string.
*   **Negation**: `{!Category:var}` captures any [token](/doc/reference/patterns/introduction/tokens/) that is **not** in the specified category.

Category names are case-insensitive, so `{@Number}` and `{@number}` are equivalent.

### Common Categories

| Category | Description | 
|:---|:---|
| [`{@Alphanumeric}`](/doc/reference/patterns/matching-by-token-category/alphanumeric/) | Matches words and identifiers (e.g., `Result`, `x1`). Shortcut: `{@Alpha}`. |
| [`{@Number}`](/doc/reference/patterns/matching-by-token-category/number/) | Matches integers or decimals (e.g., `42`, `3.14`). |
| [`{@String}`](/doc/reference/patterns/matching-by-token-category/string/) | Matches text inside quotes (e.g., `"Hello"`). Shortcut: `{@s}`. |
| [`{@Literal}`](/doc/reference/patterns/matching-by-token-category/literal/) | Matches any data value (a Number OR a String). |
| [`{@Whitespace}`](/doc/reference/patterns/matching-by-token-category/whitespace/) | Matches horizontal space or tab characters. Shortcut: `{@ws}`. |
| [`{@Newline}`](/doc/reference/patterns/matching-by-token-category/newline/) | Matches line break characters. Shortcut: `{@nl}`. |
| [`{@Bracket}`](/doc/reference/patterns/matching-by-token-category/bracket/) | Matches an opening bracket like `(`, `[`, or `{`. |

**Examples:**

### Example ID: 1201

**Description:** A simple example demonstrating how to find and wrap all numeric values in a string.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Define a rule to find any number and wrap it in 'Num(...)'
t.FromTo("{@Number:n}", "Num({n})");

wl(t.Transform("var x = 10.5; var y = 20;"))
```

**Output:**
```
var x = Num(10.5); var y = Num(20);
```

---

---

## Optional Parts - ID: 909
/doc/tutorials/text-transformation:-the-transformer/optional-parts/

**Description:** Learn how to define sections of a pattern that may or may not exist and how to create conditional replacements based on whether a match occurred.

**Remarks:**

# 🧩 Conditional Patterns: Optional Parts

In real-world data, not every piece of information is always present. A person might have a middle name, a log entry might have an optional error code, or a command might have an optional flag. **Optional Parts** are a fundamental feature of uCalc patterns that allow you to handle these variations gracefully.

The syntax is simple and intuitive: any part of a pattern enclosed in square brackets `[...]` is considered optional. For a detailed reference, see the main [Optional parts](/Reference/Patterns/Introduction/Optional-parts) topic.

```pseudocode
// This pattern will match "Report" with or without the word "Detailed"
var pattern = "Generate [Detailed] Report";
```

This tutorial will guide you through using optional parts for flexible matching and powerful conditional replacements.

---

## Capturing Optional Values

When you place a variable inside an optional block, such as `[{level}]`, the variable will only be populated if that part of the pattern is successfully matched. If the optional part is not present in the source text, the variable will be empty.

This simple mechanism is the foundation for creating conditional logic in your replacement strings.

## 💎 The Power of Conditional Replacements

This is where optional parts truly shine. uCalc provides a special replacement syntax to conditionally include or exclude text based on whether an optional variable was captured. This allows you to handle default values, add optional labels, and format output dynamically, often without needing a complex callback function.

| Syntax | Name | Behavior |
| :--- | :--- | :--- |
| `{var: ...}` | **Positive Condition** | The content after the colon is inserted **only if** `{var}` captured a value. |
| `{!var: ...}`| **Fallback Content** | The content after the colon is inserted **only if** `{var}` is empty (did not capture a value). |

#### Example: Providing a Default Value

Let's parse log entries. If a log level is not specified, we want to default to "INFO".

```pseudocode
NewUsing(uCalc::Transformer, t)
// Pattern: Match "Log:", an optional level, and the message.
// Replacement: Use `{!level:INFO}` to insert 'INFO' if {level} is empty.
t.FromTo("Log: [{level: ERROR | WARN}] {msg}",
         "Status:{!level:INFO}{level} | Msg:{msg}");

// Case 1: Level is present
wl(t.Transform("Log: ERROR File not found"))

// Case 2: Level is missing, so the fallback is used
wl(t.Transform("Log: System started successfully"))
End Using
```
This declarative approach is far cleaner than writing `if/else` logic in a callback.

---
## ⚠️ Common Pitfall: Escaping Brackets

Because square brackets `[` and `]` are reserved for defining optional parts, if you need to match a **literal** square bracket in your text (e.g., in a JSON array like `[1,2,3]`), you must escape them by enclosing them in single quotes.

*   **Incorrect**: `Read [ {content} ]` (This defines an optional part)
*   **Correct**: `Read '[' {content} ']'` (This matches the literal text `Read [ ... ]`)

---
## 💡 Why uCalc? (Comparative Analysis)

*   **vs. Regex (`?`)**:
    *   **Readability**: In Regex, making a group optional requires parentheses and a question mark, like `(optional part)?`. uCalc's `[optional part]` syntax is visually cleaner and aligns with common grammar notation forms (like EBNF).
    *   **Conditional Replacements**: Standard Regex has no simple way to say, "Insert this prefix text *only if* capture group 1 was matched." You would typically need to write a callback function in your host language (C#, C++, etc.) to handle this logic. uCalc's `{var: ...}` and `{!var: ...}` syntax handles this declaratively and directly within the replacement string, which is a major advantage in simplicity and power.

*   **vs. Native Code (If/Else)**:
    *   Manually parsing text with optional components requires procedural `if/else` logic to check for different variations. uCalc's pattern matching is **declarative**. You describe *what* the structure looks like, including its optional parts, and the engine handles the complex branching logic for you.

**Examples:**

### Example ID: 1204

**Description:** A basic pattern demonstrating how an optional word affects the match.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("Log [ERROR] entry", "MATCHED");

// This matches because the optional word is present
wl(t.Transform("Log ERROR entry found."))

// This also matches because the word is optional
wl(t.Transform("Log entry found."))
```

**Output:**
```
MATCHED found.
MATCHED found.
```

---

### Example ID: 1205

**Description:** Parses log entries to extract an optional error code, providing a default status when it's missing by using the `{!var:...}` fallback syntax.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Pattern: Match "Log:", an optional level, and the message.
// Replacement: Use `{!level:INFO}` to insert 'INFO' if {level} is empty.
t.FromTo("Log: [{level: ERROR | WARN}] {msg}", 
         "Status:{!level:INFO}{level} | Msg:{msg}");

// Case 1: Level is present
wl(t.Transform("Log: ERROR File not found"))

// Case 2: Level is missing, so the fallback is used
wl(t.Transform("Log: System started successfully"))
```

**Output:**
```
Status:ERROR | Msg:File not found
Status:INFO | Msg:System started successfully
```

---

---

## Alternation - ID: 910
/doc/tutorials/text-transformation:-the-transformer/alternation/

**Description:** Learn to match one of several alternative patterns using the '|' operator and create dynamic outputs with conditional replacements.

**Remarks:**

# 🔀 Matching Alternatives (OR Logic)

In many text processing tasks, you need to find a pattern that could be one of several possibilities. For example, a status could be "OK", "Error", or "Pending". uCalc's [Transformer](/Reference/uCalcBase/Transformer/Constructor) handles this with the **alternation** operator: the vertical bar `|`.

This tutorial will guide you through using the `|` operator to create flexible, conditional patterns.

---

## 1. The Basics of Alternation

The core syntax is simple: enclose your choices within curly braces `{}`, separated by the `|` operator. The engine will match the first choice that allows the entire pattern to succeed.

```pseudocode
// This pattern will match 'Status: OK', 'Status: Error', or 'Status: Pending'
"Status: { OK | Error | Pending }"
```

This is far more readable and maintainable than writing three separate rules.

## 2. Capturing the Choice

To make alternation useful, you often need to know *which* of the alternatives was matched. You can do this by assigning a variable name to the group.

```pseudocode
// Captures 'OK', 'Error', or 'Pending' into the variable {status_val}
"Status: {status_val: OK | Error | Pending }"
```

You can then use `{status_val}` in your replacement string to reference the specific text that was matched.

## 3. 💎 Conditional Replacements

This is where alternation becomes truly powerful. You can create different outputs based on which variable was captured within an alternation. This is done using special replacement syntax:

*   `{var: ...}`: The content after the colon is inserted **only if** `{var}` captured a value.
*   `{!var: ...}`: The content after the colon is inserted **only if** `{var}` is empty (did not capture a value).

This is perfect for normalizing data from different formats into a single, consistent output, as shown in the practical example below.

## 4. ⚠️ Ordering Matters: The Precedence Pitfall

The engine evaluates alternatives from **left to right** and stops at the first successful match that allows the rest of the pattern to succeed. This can create a common trap if your alternatives overlap.

Consider matching "Apple Pie" and "Apple".

*   **Wrong Order**: `{ Apple | Apple Pie }`. When given the text "An Apple Pie", the engine will match "Apple" first and stop, because it's a valid match. It will never get a chance to test for "Apple Pie".
*   **Correct Order**: `{ Apple Pie | Apple }`. You must always place the **longest and most specific** alternatives first. This ensures they are tested before any shorter, partial matches.

See the internal test example for a clear demonstration of this pitfall.

## 5. Why uCalc? (Comparative Analysis)

*   **vs. Regex (`(A|B|C)`)**:
    *   **Readability**: uCalc's syntax `{ Red | Blue }` is cleaner and doesn't require the often-confusing parentheses-grouping of Regex `(Red|Blue)`.
    *   **Token Awareness**: A Regex alternation like `(in|to)` can match inside words like "b**in**" or "**to**p" unless you explicitly add word boundaries (`\b`). uCalc defaults to whole-token matching, preventing these common false positives automatically.

**Examples:**

### Example ID: 1207

**Description:** How to match one of several possible status keywords.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("Status: { OK | Error | Pending }", "Found Valid Status");

wl(t.Transform("Status: OK"))
wl(t.Transform("Status: Error"))
wl(t.Transform("Status: Fail"))
```

**Output:**
```
Found Valid Status
Found Valid Status
Status: Fail
```

---

---

## Ignoring Content with SkipOver - ID: 911
/doc/tutorials/text-transformation:-the-transformer/ignoring-content-with-skipover/

**Description:** Learn how to define patterns that exclude specific text, like comments, from being processed by other transformation rules.

**Remarks:**

# 🛡️ Protecting Text: Ignoring Content with SkipOver

Sometimes, the most important part of a transformation is knowing what *not* to transform. The `SkipOver` method is uCalc's primary tool for creating "dead zones" or "no-fly zones" within your text. Any content that matches a `SkipOver` pattern is completely ignored by all other find-and-replace rules, making it essential for protecting content like code comments, string literals, or raw data blocks.

## ⚙️ How It Works: Highest Precedence

The most critical concept to understand about `SkipOver` is its precedence. `SkipOver` rules are **always** evaluated before any [FromTo](/Reference/uCalcBase/Transformer/FromTo) or [Pattern](/Reference/uCalcBase/Transformer/Pattern) rules, regardless of their definition order. If a piece of text matches a `SkipOver` pattern, it is immediately excluded from further processing for that pass.

This creates a powerful safety net. You can define a rule to skip over all comments, and you are guaranteed that no other rule will accidentally modify text inside those comments.

## `SkipOver` vs. `FromTo("pattern", "{@Self}")`

While a rule like [pseudocode]`t.FromTo("/* ... */", "{@Self}")` might seem to have the same effect, it behaves very differently in two key ways:

| Feature | `SkipOver("/* ... */")` | `FromTo("/* ... */", "{@Self}")` |
| :--- | :--- | :--- |
| **Precedence** | 🟢 **Highest**. Always runs before other rules. | 🟡 **Standard**. Competes with other rules based on LIFO order. | 
| **Match Results** | 🟢 **Invisible**. The match is not recorded in the [Matches](/Reference/uCalcBase/Transformer/Matches) collection. | 🔴 **Visible**. A `Match` object is created and added to the results. |

**Conclusion**: Use `SkipOver` when you want to make text completely invisible to the transformation engine. Use `FromTo` when you need to find text and keep it, but still want it to be part of the official match results.

## 💡 Why uCalc? (Comparative Analysis)

In standard regular expressions, achieving this "skip" behavior is complex and often error-prone. It typically requires negative lookarounds (`(?<!...)` and `(?!...)`) or a multi-pass approach where you first remove the content to be ignored, perform replacements, and then add it back.

**The uCalc Advantage** is its declarative and integrated nature. `SkipOver` is a simple, readable instruction that clearly states your intent. The engine handles the complex logic of prioritizing and excluding text internally, leading to rules that are safer, easier to write, and more maintainable.

**Examples:**

### Example ID: 1210

**Description:** A basic example demonstrating how to ignore a block of text in parentheses, preventing other rules from matching inside it.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("word", "WORD"); // Rule to uppercase 'word'
t.SkipOver("({ignore})"); // Rule to ignore content in parentheses

var text = "transform this word, but (not this word)";
wl(t.Transform(text))
```

**Output:**
```
transform this WORD, but (not this word)
```

---

---

## Executing Logic in Replacements - ID: 912
/doc/tutorials/text-transformation:-the-transformer/executing-logic-in-replacements/

**Description:** Learn to execute expressions and call functions within replacement strings using the powerful {@Eval} and {@@Eval} directives.

**Remarks:**

# 🧠 Executing Logic in Replacements

Traditional find-and-replace tools are typically limited to static text and simple backreferences (`$1`, `$2`). uCalc's [Transformer](/Reference/uCalcBase/Transformer/Constructor) elevates this by allowing you to execute complex logic, perform calculations, and call functions directly within the replacement string. This turns a simple text substitution into a dynamic, intelligent transformation.

The engine for this capability is a set of special pattern methods that evaluate expressions at different stages of the transformation process.

## The Core Tools: {@Eval}, {@@Eval}, and {@Exec}

### 1. `{@Eval}`: The Workhorse for Dynamic Values

The [`{@Eval}`](/Reference/Patterns/Pattern-Methods/{@Eval}) directive is the most common tool for executing logic. It evaluates a **fixed expression** using **dynamic values** captured from the current match. For performance, the expression is parsed only once when the rule is created.

To use a variable captured in your pattern (e.g., `{qty}`), simply refer to it by name inside the `Eval` block without curly braces.

```pseudocode
// The expression 'Double(qty) * Double(price)' is fixed.
// The values for 'qty' and 'price' change with each match.
t.FromTo("Qty: {@Number:qty}, Price: {@Number:price}", 
         "{@Self}, Total: {@Eval: Double(qty) * Double(price)}");
```

### 2. `{@@Eval}`: The Power Tool for Dynamic Formulas

The [`{@@Eval}`](/Reference/Patterns/Pattern-Methods/{@@...}) directive (with a double `@@`) is for meta-programming scenarios where the **expression itself** is captured from the source text. It parses and evaluates its content every single time a match is found.

This allows you to create a transformer that can solve mathematical problems embedded in a string.

```pseudocode
// The variable {formula} captures the text "10 * (5-2)".
// {@@Eval} then executes that captured text as an expression.
t.FromTo("solve({formula})", "{@@Eval: formula}");
```

### 3. `{@Exec}`: For Side Effects Only

The [`{@Exec}`](/Reference/Patterns/Pattern-Methods/{@Exec}) directive is a "void" version of `{@Eval}`. It executes an expression but **does not insert any text** into the replacement string. It is used exclusively for side effects, such as incrementing a counter, logging information, or setting a [Variable](/Reference/uCalcBase/Item) that will be used by another rule.

```pseudocode
// This rule finds a word but inserts nothing into the text as a replacement.
// Its only purpose is to increment the 'word_count' variable.
t.FromTo("{@Alpha}", "{@Self}{@Exec: word_count++}");
```

### ⚠️ Important: Type Conversion
All variables captured from a pattern, even those from `{@Number:val}`, are **text strings**. Before you can use them in a mathematical calculation inside an `{@Eval}` block, you must explicitly convert them to a numeric type using functions like `Double()` or `Int()`.

*   **Correct**: `{@Eval: Double(val) * 2}`
*   **Incorrect**: `{@Eval: val * 2}` (if `val` is `123`, this would result in `123123`).

## 💡 Why uCalc? (Comparative Analysis)

In most programming environments, performing logic during a regex replacement requires writing a separate callback function (like a `MatchEvaluator` in C#). This separates the logic from the pattern and can be verbose.

**C# MatchEvaluator Approach:**
```csharp
string ProcessMatch(Match m)
{
    int qty = int.Parse(m.Groups["qty"].Value);
    double price = double.Parse(m.Groups["price"].Value);
    return m.Value + ", Total: " + (qty * price);
}

Regex.Replace(input, @"Qty: (?<qty>\d+), Price: (?<price>[\d\.]+)", ProcessMatch);
```

**The uCalc Advantage:**
uCalc's declarative approach allows the logic to live directly and cleanly within the replacement string, resulting in more concise and readable rules.

```pseudocode
t.FromTo("Qty: {@Number:qty}, Price: {@Number:price}", 
         "{@Self}, Total: {@Eval: Double(qty) * Double(price)}");
```

**Examples:**

### Example ID: 1217

**Description:** Performing a simple unit conversion from inches to centimeters using `{@Eval}`.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// Capture a number followed by 'in' and convert it.
// Note: `len` is a string, so we must use Double(len) for the calculation.
t.FromTo("{@Number:len}in", "{@Eval: Double(len) * 2.54}cm");

wl(t.Transform("The board is 10in long."))
```

**Output:**
```
The board is 25.4cm long.
```

---

### Example ID: 1218

**Description:** A practical example that calculates line-item totals for a list of products by capturing quantity and price.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Rule to find quantity and price, then calculate total.
// Note the explicit Double() to convert the captured numerical
// values as text into double-precision numbers for {@Eval}.
t.FromTo("Qty: {@Number:qty}, Price: {@Number:price}", 
         "{@Self}, Total: {@Eval: Double(qty) * Double(price)}");

var invoice = [verbatim]Item: Book, Qty: 3, Price: 15.00
Item: Pen, Qty: 10, Price: 1.50[/verbatim];

wl(t.Transform(invoice))
```

**Output:**
```
Item: Book, Qty: 3, Price: 15.00, Total: 45
Item: Pen, Qty: 10, Price: 1.50, Total: 15
```

---

### Example ID: 1220

**Description:** Internal Test: Verifies that `{@@Eval}` can correctly parse and evaluate an expression that is itself captured from the text.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// The variable {formula} will capture the literal text "10 * (5-2)".
// {@@Eval} then executes that text as an expression.
t.FromTo("solve({formula})", "'{formula}' is {@@Eval: formula}.");

var text = "The answer to solve(10 * (5-2))";
wl(t.Transform(text))
```

**Output:**
```
The answer to '10 * (5-2)' is 30.
```

---

---

## uCalc Patterns for Common Regex Tasks (A Cookbook) - ID: 979
/doc/tutorials/text-transformation:-the-transformer/ucalc-patterns-for-common-regex-tasks--a-cookbook/

**Description:** A practical guide showing how to solve common text-processing problems using uCalc's token-aware patterns as a powerful alternative to Regex.

**Remarks:**

# 🍳 uCalc Cookbook: Regex to uCalc Patterns

For developers accustomed to Regular Expressions (Regex), switching to a new pattern-matching syntax can be a hurdle. This cookbook is designed to bridge that gap. It presents common text-processing problems and shows how to solve them using both traditional Regex and uCalc's powerful, token-aware patterns.

While Regex is a fantastic tool for character-level matching, you'll see how uCalc's approach often leads to patterns that are safer, more readable, and better at handling structured data.

---

## 1. Matching Whole Words

**The Goal:** Find the word `is` but not as a substring inside `This`.

*   **Regex Solution:** `\bis\b`
    You must explicitly add word boundaries (`\b`) to prevent partial matches.

*   **uCalc Solution:** `is`
    uCalc's engine is **token-aware**. It breaks the input into words first. The pattern `is` will only match the token `is`, not the characters `i` and `s` inside the token `This`.

---

## 2. Matching Any Number

**The Goal:** Find integers, decimals, and scientific notation (e.g., `10`, `3.14`, `-1.5e-2`).

*   **Regex Solution:** `[-+]?\d*\.?\d+([eE][-+]?\d+)?`
    This is complex, hard to read, and may not cover all formats.

*   **uCalc Solution:** `{@Number}`
    The [`{@Number}`](/Reference/Patterns/Matching-by-token-category/{@Number}) category matcher is a simple, readable instruction. The uCalc tokenizer handles the complex logic of identifying all valid number formats internally. If you need to support a new format (like hexadecimal `0x...`), you only need to update the token definition, not every pattern that uses it.

---

## 3. Matching Content Inside Quotes

**The Goal:** Extract the text from within double quotes, correctly handling escaped quotes.

*   **Regex Solution:** `"(.*?)"` (using a non-greedy quantifier) or `"((?:\\"|[^"])*)"` (more robust, but very complex).

*   **uCalc Solution:** `{@String:content}`
    The [`{@String}`](/Reference/Patterns/Matching-by-token-category/{@String}) category matcher leverages the tokenizer, which understands string literals as atomic units. It automatically and safely handles escaped quotes and other complexities.

---

## 4. Extracting Key-Value Pairs

**The Goal:** Parse `key = value;` where whitespace is variable.

*   **Regex Solution:** `\s*(\w+)\s*=\s*([^;]*);`
    You must manually account for optional whitespace (`\s*`) around the key, equals sign, and value.

*   **uCalc Solution:** `{@Alpha:key} = {value};`
    uCalc is **whitespace-insensitive** by default. A single space in the pattern matches any amount of horizontal whitespace (or none) in the source text, making the pattern clean and readable.

---

## 5. Matching Balanced Delimiters

**The Goal:** Match a complete HTML-style tag, like `<b>content</b>`, but reject mismatched tags like `<b>content</i>`.

*   **Regex Solution:** `<(\w+)>(.*?)<\/\1>`
    This uses a numeric backreference (`\1`) to ensure the closing tag matches the captured opening tag. It's functional but can become confusing with multiple capture groups.

*   **uCalc Solution:** `<{tag}>{content}</{tag}>`
    uCalc uses simple, named **backreferences**. By reusing the variable name `{tag}`, the engine automatically enforces that the captured text must be identical in both places. This is far more readable and maintainable.

---

## 6. Splitting a String by a Delimiter

**The Goal:** Split a comma-separated list, but correctly handle delimiters that appear inside quoted strings.

*   **Language Solution:** `myString.Split(',')`
    A simple split will incorrectly break up `a,"b,c",d` into `a`, `"b`, `c"`, `d`.

*   **uCalc Solution:** Use a [Transformer](/Reference/uCalcBase/Transformer/Constructor) to find each element.
    The pattern `{!ArgSeparator:item}` captures any token that is not a comma. The tokenizer's default `QuoteSensitive` behavior ensures that `"b,c"` is treated as a single string token, so the pattern correctly captures it as one element.

---

## 7. Validating an Email Address (Hybrid Approach)

**The Goal:** Check if a string looks like a valid email address.

*   **Regex Solution:** A very long and famously complex regex.

*   **uCalc Hybrid Solution:** `{'[\w.-]+'}@{'[\w.-]+'}\.{'[a-zA-Z]{2,}'}`
    This pattern shows uCalc's flexibility. While the overall structure (`user@domain.tld`) is defined with tokens, we can **embed short, simple regex snippets** inside single quotes for character-level validation where it makes sense. This gives you the best of both worlds: high-level structural awareness and low-level precision.

**Examples:**

### Example ID: 1338

**Description:** Extracts all numbers from a string, demonstrating the simplicity of the `{@Number}` category matcher.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
   t.FromTo("{@Number:n}", "[NUM:{n}]");

   var text = "Order 123 has 2 items for 49.95 total.";
   wl(t.Transform(text))
End Using;
```

**Output:**
```
Order [NUM:123] has [NUM:2] items for [NUM:49.95] total.
```

---

---

## Advanced Data Validation with the Transformer - ID: 980
/doc/tutorials/text-transformation:-the-transformer/advanced-data-validation-with-the-transformer/

**Description:** Learn how to use the Transformer to enforce structural rules, validate data formats, and ensure content integrity using advanced pattern properties.

**Remarks:**

# 🛡️ Advanced Data Validation with the Transformer

The [Transformer](/Reference/uCalcBase/Transformer/Constructor) is not just a tool for finding and replacing text; it's also a powerful engine for **validating** the structure and content of your data. By defining rules that describe what a valid document should look like, you can create sophisticated linters, configuration file validators, or static analysis tools.

This tutorial moves beyond simple pattern matching to explore the features that allow you to enforce constraints, check values, and ensure the integrity of your text data.

---

## 1. ✅ Existence and Occurrence Checks

The most basic form of validation is ensuring that a required pattern exists or that it appears a specific number of times. The Transformer provides both imperative and declarative ways to handle this.

### The Imperative Way: `Find()` and `Count()`

The simplest approach is to define a [Pattern](/Reference/uCalcBase/Transformer/Pattern) and then check the result of the [Matches](/Reference/uCalcBase/Transformer/Matches) collection after a [Find()](/Reference/uCalcBase/Transformer/Find) operation.

```pseudocode
NewUsing(uCalc::Transformer, t)
  t.Pattern("Header: OK");
  if (t.Find("Header: OK").@Matches().Count() > 0)
    wl("Document is valid.")
  end if
End Using
```

While functional, this requires you to write explicit checking logic in your application code for every rule.

### The Declarative Way: `Minimum` and `Maximum`

A more powerful and declarative approach is to use the `Minimum` and `Maximum` properties on a [Rule](/Reference/uCalcBase/Rule/Constructor) object. These properties instruct the engine to automatically invalidate a rule's matches if the count is not met.

*   [**Minimum(n)**](/Reference/uCalcBase/Rule/Minimum): The rule must match at least `n` times for its matches to be considered valid. If it finds fewer, its own matches are discarded (other rules are unaffected).
*   [**Maximum(n)**](/Reference/uCalcBase/Rule/Maximum): The rule must match at most `n` times. If it finds more, its own matches are discarded.
*   [**GlobalMinimum(n)**](/Reference/uCalcBase/Rule/GlobalMinimum) / [**GlobalMaximum(n)**](/Reference/uCalcBase/Rule/GlobalMaximum): Same as above, but if the condition is not met, the **entire transformation fails**, and no matches from *any* rule are returned.

This allows you to build validation logic directly into your patterns, as shown in the practical example below.

---

## 2. 🔬 Content Validation with `{@Eval}`

Sometimes, it's not enough to know that a pattern exists; you also need to validate its *content*. For example, a port number must not only be a number, but it must be within a specific range. The `{@Eval}` directive is the perfect tool for this.

You can create a rule that captures a value and then uses `{@Eval}` with a conditional function like `IIf` to perform a check during the transformation.

```pseudocode
// This rule will validate port numbers as it transforms them.
t.FromTo("Port: {@Number:port_num}", 
         "Port: {port_num} - {@Eval: IIf(Double(port_num) > 0 and Double(port_num) < 65536, 'OK', 'INVALID')}");
```

This turns the transformer into a dynamic validation engine that can check values against business logic, not just syntax.

---

## 3. ❌ Negative Validation

Validation can also mean ensuring that certain patterns do **not** exist. You can achieve this in two ways:

*   **Define a pattern for the invalid syntax** and then check if its `Matches.Count()` is greater than zero. If it is, the document is invalid.
*   Use [**SkipOver**](/Reference/uCalcBase/Transformer/SkipOver) for sections that are allowed but should not be processed by other validation rules. This is useful for ignoring comments or other non-functional blocks.

**Examples:**

### Example ID: 1341

**Description:** Checks for the existence of a required header in a string.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
var text_ok = "Header: OK";
var text_fail = "Header: ERROR";

// This rule only matches if the status is "OK"
t.Pattern("Header: OK");

// Find() returns the transformer, so we can chain Matches().Count()
if (t.SetText(text_ok).Find().@Matches().Count() > 0)
    wl("text_ok is valid.")
end if

if (t.SetText(text_fail).Find().@Matches().Count() == 0)
    wl("text_fail is invalid.")
end if
End Using
```

**Output:**
```
text_ok is valid.
text_fail is invalid.
```

---

### Example ID: 1342

**Description:** Practical: Validates a configuration file format by enforcing the number of times specific keys must appear.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, validator)

// Rule 1: Must contain exactly one 'Host' setting.
var hostRule = validator.Pattern("Host: {@Alpha}").SetMinimum(1).SetMaximum(1);

// Rule 2: Must contain at least one 'Port' setting.
var portRule = validator.Pattern("Port: {@Number}").SetMinimum(1);

var configFile_OK = [verbatim]
Host: server1
Port: 80
Port: 443
[/verbatim];
var configFile_FAIL = "Port: 80"; // Missing Host

wl("--- Testing Valid Config ---")
validator.SetText(configFile_OK).Find();
if (hostRule.@Matches().Count() > 0 && portRule.@Matches().Count() > 0)
    wl("Config file is valid.")
else
    wl("Config file is invalid.")
end if
wl()
wl("--- Testing Invalid Config ---")
validator.SetText(configFile_FAIL).Find();
// The Minimum(1) on hostRule causes it to have 0 matches if none are found.
if (hostRule.@Matches().Count() > 0 && portRule.@Matches().Count() > 0)
    wl("Config file is valid.")
else
    wl("Config file is invalid.")
    if (hostRule.@Matches().Count() == 0) 
      wl("- Reason: Host rule failed (found ", hostRule.@Matches().Count(), ", expected 1).")
    end if
end if
End Using
```

**Output:**
```
--- Testing Valid Config ---
Config file is valid.

--- Testing Invalid Config ---
Config file is invalid.
- Reason: Host rule failed (found 0, expected 1).
```

---

---

## Beyond the Basics - What Makes uCalc Special? - ID: 924
/doc/tutorials/beyond-the-basics---what-makes-ucalc-special?/

---

## Dynamic Syntax - ID: 925
/doc/tutorials/beyond-the-basics---what-makes-ucalc-special?/dynamic-syntax/

**Description:** Learn how uCalc's grammar can be extended at runtime by defining new operators, keywords, and literal formats.

**Remarks:**

# 🔧 Dynamic Syntax: Teaching uCalc New Tricks

Most programming languages and parsers have a fixed, unchangeable grammar. The meaning of `+`, `if`, or `123` is defined by the language specification and cannot be altered. uCalc is different. Its syntax is **dynamic**, meaning you can teach the engine new tricks—new operators, new keywords, and even new ways to write numbers—at runtime, without recompiling your application.

This capability transforms uCalc from a simple expression evaluator into a lightweight language workbench, allowing you to create expressive, human-readable Domain-Specific Languages (DSLs) tailored to your specific needs.

---

## 1. Creating Custom Operators and Syntax

There are two primary ways to create custom syntax, depending on your needs:

### A. Single-Word Operators with `DefineOperator`

The [DefineOperator](/Reference/uCalcBase/uCalc/DefineOperator) method is for creating new operators that consist of a single alphanumeric word (like `and`) or a single symbol (like `##`).

For example, let's create a `percentof` operator:
```pseudocode
// Define a 'percentof' operator with the same precedence as multiplication.
uc.DefineOperator("{percentage} percentof {total} = (percentage / 100) * total", 60);

// The new syntax is immediately available.
wl("15 percentof 200 is ", uc.Eval("15 percentof 200"));
```

### B. Multi-Word Syntax with the Transformer

For more complex, multi-word syntax like `100 USD to EUR`, the correct tool is the [ExpressionTransformer](/Reference/uCalcBase/uCalc/ExpressionTransformer). It allows you to define flexible, token-aware patterns that are transformed into standard expressions before evaluation.

```pseudocode
// Get the transformer that pre-processes expressions.
var t = uc.@ExpressionTransformer();

// Define a rule to handle the multi-word syntax.
t.FromTo("{@Number:amount} USD to EUR", "({@Eval: Double(amount) * 0.92})");

// The new syntax is now available in any expression.
wl("100 USD is ", uc.EvalStr("100 USD to EUR"), " EUR");
```

---

## 2. Creating Custom Literals (The Advanced Way)

Extending the syntax to support new literal formats, like C-style hexadecimal numbers (`0xFF`), is a more advanced process that showcases the power of uCalc's two-stage parsing pipeline. It involves two steps:

1.  **Lexical Definition**: Teach the tokenizer what the new literal *looks like* using a regular expression via [ExpressionTokens](/Reference/uCalcBase/uCalc/ExpressionTokens).
2.  **Semantic Transformation**: Tell the engine what the new literal *means* by transforming it into a standard expression via the [TokenTransformer](/Reference/uCalcBase/uCalc/TokenTransformer).

#### Example: Adding `0x...` Hexadecimal Support

```pseudocode
// Step 1: Define the lexical rule.
// TokenType::TokenTransform tells the parser that this token needs pre-processing.
uc.@ExpressionTokens().Add("0x[0-9a-fA-F]+", TokenType::TokenTransform);

// Step 2: Define the transformation rule.
// This captures the hex digits ('val') and replaces the whole token (e.g., "0xFF")
// with a standard function call that the engine already understands.
uc.@TokenTransformer().FromTo("{'0x'}{val:'[0-9a-fA-F]+'}", "BaseConvert('{val}', 16)");

// Step 3: Use the new literal format directly in any expression.
wl(uc.Eval("0xFF + 1")); // Evaluates 255 + 1
```

This two-step process allows you to integrate complex, custom syntax seamlessly into the uCalc engine.

---

## 💡 Why uCalc? (Comparative Analysis)

*   **vs. Parser Generators (ANTLR, Flex/Bison)**: These are powerful tools, but their grammars are **static**. To add a new operator or literal, you must modify a grammar file, run a code generator, and recompile your entire application. With uCalc, these changes can be made **programmatically at runtime**, allowing your application to adapt its own syntax on the fly.

*   **vs. Statically-Compiled Languages (C#, C++)**: In these languages, operator sets and precedence rules are fixed by the language specification. You cannot invent a multi-word `USD to EUR` syntax. uCalc gives you complete control over the grammar, allowing you to build languages that are far more expressive and domain-specific.

**Examples:**

### Example ID: 1225

**Description:** Creates a domain-specific currency conversion syntax using the ExpressionTransformer, the correct tool for multi-word patterns.

**Code:**
```pseudocode
// Use the ExpressionTransformer for multi-word syntax.
var t = uc.@ExpressionTransformer();

// Note: Captured variables are passed to @Eval as text
// Double() converts the text to Double a precision value
uc.Format("Result = Format('{:.2f}', Double(Result))", uc.DataTypeOf("Double"));
t.FromTo("{@Number:amount} USD to EUR", "({@Eval: Double(amount) * 0.92})");
t.FromTo("{@Number:amount} EUR to USD", "({@Eval: Double(amount) / 0.92})");

wl("100 USD is approx. ", uc.EvalStr("100 USD to EUR"), " EUR")
wl("120 EUR is approx. ", uc.EvalStr("120 EUR to USD"), " USD")
```

**Output:**
```
100 USD is approx. 92.00 EUR
120 EUR is approx. 130.43 USD
```

---

### Example ID: 1224

**Description:** Defines a custom `sum_to` operator to calculate the sum of a numeric range, demonstrating a single-word operator.

**Code:**
```pseudocode
// Define the variables that the operator's expression will use.
uc.DefineVariable("i");
uc.DefineVariable("total");

// Define a new 'sum_to' operator at runtime, with precedence level of 50.
// It uses the built-in ForLoop function to sum numbers into the 'total' variable.
uc.DefineOperator("{start} sum_to {end} = total = 0; ForLoop(i, start, end, 1, total = total + i)", 50);

// Use the new operator. The result is stored in the 'total' variable.
uc.Eval("1 sum_to 5");

wl("The sum from 1 to 5 is: ", uc.Eval("total"))
```

**Output:**
```
The sum from 1 to 5 is: 15
```

---

### Example ID: 1223

**Description:** Internal Test: Implements C-style hexadecimal literals (e.g., 0xFF) by adding a new token rule and a token transformation.

**Code:**
```pseudocode
// 1. Define the lexical rule.
// The regex matches '0x' followed by hex digits.
// The TokenType::TokenTransform tells the parser to pre-process this token.
uc.@ExpressionTokens().Add("0x[0-9a-fA-F]+", TokenType::TokenTransform);

// 2. Define the transformation rule.
// This captures the hex digits and replaces the whole token with a call to BaseConvert.
uc.@TokenTransformer().FromTo("{'0x'}{val:'[0-9a-fA-F]+'}", "BaseConvert('{val}', 16)");

// 3. Now, the new literal format can be used in expressions.
wl(uc.Eval("0xFF + 0xA")) // 255 + 10
wl(uc.EvalStr("Hex(0x100)")) // Hex(256)
```

**Output:**
```
265
100
```

---

---

## Structural Awareness (Tokens vs. Regex) - ID: 926
/doc/tutorials/beyond-the-basics---what-makes-ucalc-special?/structural-awareness--tokens-vs.-regex/

**Description:** Explains the fundamental difference between uCalc's token-aware parsing and traditional character-aware Regex, highlighting safety and power.

**Remarks:**

# 🧠 Structural Awareness: Seeing Code, Not Just Text

One of the most important concepts to understand about uCalc is that its [Transformer](/Reference/uCalcBase/Transformer/Constructor) is **structurally aware**. This is the key advantage it holds over traditional text-processing tools like Regular Expressions (Regex). In short:

*   **Regex is character-aware**: It sees text as a flat stream of characters.
*   **uCalc is token-aware**: It sees text as a structured sequence of meaningful units (words, numbers, strings, etc.).

This fundamental difference has profound implications for safety, power, and readability, especially when transforming structured text like source code, configuration files, or markup.

---

## 1. The Regex World: A Stream of Characters

Regular expressions are incredibly powerful for finding patterns in character streams. However, their greatest strength is also their greatest weakness: they are "blind" to the structure and context of the text they are processing.

### The Classic Refactoring Problem

Imagine you want to refactor a piece of code by renaming the variable `rate` to `annual_rate`. Your code looks like this:

```pseudocode
rate = 0.05; // Current rate
print("The rate is: ", rate);
```
*(Note: To enable C-style comments as shown, you would first define a comment token, for example, by calling [pseudocode]`uc.ExpressionTokens().Add("//.*", TokenType::Whitespace);`. This demonstrates uCalc's configurable syntax.)*

A developer's first instinct might be to use a simple find-and-replace operation for the word "rate". A naive regex like `\brate\b` would produce this incorrect result:

```pseudocode
annual_rate = 0.05; // Current annual_rate
print("The annual_rate is: ", annual_rate);
```

This is a catastrophic failure. The regex, blind to context, has incorrectly modified the text inside both a code comment and a string literal, corrupting the logic and the output.

---

## 2. The uCalc World: A Stream of Tokens

The uCalc [Transformer](/Reference/uCalcBase/Transformer/Constructor) avoids this problem by performing a crucial first step: **tokenization**. Before any pattern matching occurs, the engine's tokenizer (or lexer) breaks the input string into a stream of meaningful [Tokens](/Reference/Patterns/Introduction/Tokens):

1.  `rate` (Identifier)
2.  `=` ([Reducible](/Reference/Patterns/Matching-by-token-category/{@Reducible}) / Operator Symbol)
3.  `0.05` (Number Literal)
4.  `;` ([StatementSeparator](/Reference/Patterns/Matching-by-token-category/{@StatementSeparator}))
5.  `// Current rate` (Comment / [Whitespace](/Reference/Patterns/Introduction/Whitespace))
6.  `print` (Identifier)
7.  `(` ([Bracket](/Reference/Patterns/Matching-by-token-category/{@Bracket}))
8.  `"The rate is: "` (String Literal)
9.  `,` (Argument Separator)
10. `rate` (Identifier)
11. `)` ([Bracket](/Reference/Patterns/Matching-by-token-category/{@Bracket}))
12. `;` ([StatementSeparator](/Reference/Patterns/Matching-by-token-category/{@StatementSeparator}))

This process categorizes each part of the string. Comment tokens can be defined as whitespace with uCalc.Tokens `.Add("//.*", TokenType.Whitespace);`, which tells the parser to ignore them, while string literals are recognized as atomic units.

### The Safe Solution

When you define a uCalc rule to replace the **identifier** `rate`, the pattern matching engine operates on this stream of tokens. It knows that `"The rate is: "` is a single `String Literal` token and (once defined) `// Current rate` is a `Whitespace` token. **By default, it will not look inside them.**

A rule to replace the identifier `rate` will only match tokens #1 and #10, producing the correct, safe transformation:

```pseudocode
annual_rate = 0.05; // Current rate
print("The rate is: ", annual_rate);
```

This structural awareness is the core reason why the uCalc [Transformer](/Reference/uCalcBase/Transformer/Constructor) is a superior tool for static analysis, code refactoring, and transpilation.

---

## 💡 Why uCalc? (Summary of Advantages)

| Feature | Regular Expressions | uCalc Transformer |
| :--- | :--- | :--- |
| **Safety** | 🔴 **Unsafe**. Easily corrupts string literals, comments, and other structural blocks. | 🟢 **Safe by Default**. [QuoteSensitive](/Reference/uCalcBase/Rule/QuoteSensitive) and [BracketSensitive](/Reference/uCalcBase/Rule/BracketSensitive) properties respect code structure. |
| **Readability** | 🔴 **Low**. Patterns can become cryptic and hard to maintain (e.g., `(?<=\s)\d+`). | 🟢 **High**. Patterns use readable names and categories (e.g., [`{@Number}`](/Reference/Patterns/Matching-by-token-category/{@Number})). |
| **Power** | 🟡 **Medium**. Struggles with nested or recursive patterns (like matching balanced parentheses). | 🟢 **High**. Natively understands nested structures and token categories. |

**Examples:**

### Example ID: 1226

**Description:** A simple demonstration of safely renaming a variable without corrupting a string literal, a common pitfall for Regex.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// This rule only targets the alphanumeric token 'x'.
t.FromTo("x", "value");
var code = [verbatim]x = 5; print("The value of x is...");[/verbatim];
wl(t.Transform(code))
```

**Output:**
```
value = 5; print("The value of x is...");
```

---

### Example ID: 1227

**Description:** A real-world refactoring task to rename a function, showing how uCalc correctly ignores matches inside comments and strings by default.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// This rule replaces the ALPHANUMERIC token 'get_data', not just the text.
t.FromTo("get_data", "fetch_records");

var code = [verbatim]
// Note: 'get_data' is the old function name.
results = get_data(source);
print("The 'get_data' function was called.");
[/verbatim];

// The default tokenizer recognizes the comment and string literal as separate tokens,
// so the rule to replace the function name doesn't affect them.
wl(t.Transform(code))
```

**Output:**
```
// Note: 'get_data' is the old function name.
results = fetch_records(source);
print("The 'get_data' function was called.");
```

---

### Example ID: 1228

**Description:** Internal Test: Contrasts a token-aware uCalc replacement with a character-aware regex replacement to highlight safety.

**Code:**
```pseudocode
var code = [verbatim]rate = 0.05; print("rate"); // a rate[/verbatim];

wl("--- uCalc Transformer (Token-Aware & Correct) ---")
New(uCalc::Transformer, t)
t.@Tokens().Add("//.*", TokenType::Whitespace);
// Rule targets only the alphanumeric token 'rate'
t.FromTo("rate", "annual_rate");
wl(t.Transform(code))

wl("")
wl("--- Simulated Regex (Character-Aware & Incorrect) ---")
// This simulates a simple find-and-replace for the word 'rate'
// which incorrectly changes the string literal and comment.
var incorrect_result = [verbatim]annual_rate = 0.05; print("annual_rate"); // a annual_rate[/verbatim];
wl(incorrect_result)
```

**Output:**
```
--- uCalc Transformer (Token-Aware & Correct) ---
annual_rate = 0.05; print("rate"); // a rate

--- Simulated Regex (Character-Aware & Incorrect) ---
annual_rate = 0.05; print("annual_rate"); // a annual_rate
```

---

---

## Lazy Evaluation (ByExpr) - ID: 927
/doc/tutorials/beyond-the-basics---what-makes-ucalc-special?/lazy-evaluation--byexpr/

**Description:** Explains how uCalc's ByExpr modifier enables lazy evaluation, allowing for the creation of custom control structures and short-circuiting logic.

**Remarks:**

# 💤 Lazy Evaluation with `ByExpr`

Most programming languages and expression evaluators use **eager evaluation**. This means that when you call a function, all of its arguments are fully calculated *before* the function itself begins to run. While simple, this approach makes it impossible to create custom control structures like conditional statements or loops.

[pseudocode]`ByExpr` is the powerful uCalc modifier that solves this problem by enabling **lazy evaluation**.

---

## 1. The Problem with Eager Evaluation

Imagine trying to create your own `if` function:
[pseudocode]`MyIf(condition, then_branch, else_branch)`

With eager evaluation, if you call [pseudocode]`MyIf(1 > 0, 100, 1/0)`, the program will crash. Even though the `else_branch` containing `1/0` should never be executed, the evaluator calculates it *before* the `MyIf` function even has a chance to check the condition. This fundamental limitation prevents standard evaluators from implementing custom control flow.

---

## 2. The uCalc Solution: `ByExpr`

The `ByExpr` modifier changes how an argument is passed to a callback function. Instead of passing the argument's final **value**, it passes an unevaluated [Expression](/Reference/uCalcBase/Expression/Constructor) object.

Your callback function then has complete control over this `Expression` object. It can:
*   **Evaluate it**: Call [`.Evaluate()`](/Reference/uCalcBase/Expression/Evaluate) or [`.Execute()`](/Reference/uCalcBase/Expression/Execute) to get its result.
*   **Ignore it**: Choose not to evaluate it at all (the key to short-circuiting).
*   **Evaluate it multiple times**: The foundation for creating custom loops.

Inside the callback, you retrieve this object using the [cb.ArgExpr(n)](/Reference/uCalcBase/Callback/ArgExpr) method.

--- 

## 💡 Why uCalc? (Comparative Analysis)

*   **vs. C# Delegates/Lambdas (`Func<T>`)**: Passing an argument `ByExpr` is conceptually similar to passing a `Func<T>` delegate in C#. Both techniques provide a piece of code to be executed later. However, uCalc's approach is designed for a dynamic, string-based scripting environment. A key advantage is that uCalc's [Expression](/Reference/uCalcBase/Expression/Constructor) object allows for metaprogramming; [you can inspect the argument's original text before deciding whether to execute it, a capability not available with compiled lambdas].

*   **vs. Functional Languages (LISP, Haskell)**: Lazy evaluation is a core concept in many functional programming languages. `ByExpr` brings this powerful paradigm to mainstream imperative languages like C#, C++, and VB, allowing developers to build more expressive and powerful control structures without leaving their familiar environment.

*   **vs. Standard `eval()` Functions**: Built-in `eval()` functions in scripting languages are almost always eager, making them incapable of creating custom control structures. uCalc's `ByExpr` elevates it from a simple calculator to a lightweight language construction kit.

**Examples:**

### Example ID: 1229

**Description:** Creates a custom `IIf` function to demonstrate basic lazy evaluation. The division-by-zero error in the unevaluated branch is safely ignored.

**Code:**
```pseudocode
[head]
[callback MyIIf]
  var condition = cb.ArgBool(1);
  var thenPart = cb.ArgExpr(2);
  var elsePart = cb.ArgExpr(3);

  if (condition)
    cb.Return(thenPart.Evaluate());
  else
    cb.Return(elsePart.Evaluate());
  end if
[/callback]
[body]
uc.DefineFunction("MyIIf(cond As Bool, ByExpr thenExpr, ByExpr elseExpr)", MyIIf);

// The 'else' branch contains 1/0, but since the condition is true,
// it is never evaluated.
wl(uc.Eval("MyIIf(10 > 5, 100, 1/0)"))

// The 'then' branch contains 1/0, but it is never evaluated.
wl(uc.Eval("MyIIf(10 < 5, 1/0, 200)"))
```

**Output:**
```
100
200
```

---

### Example ID: 1230

**Description:** Practical: Builds a custom `Repeat` loop control structure that executes an action a specified number of times.

**Code:**
```pseudocode
[head]
[callback MyRepeat]
  var count = cb.ArgInt32(1);
  var action = cb.ArgExpr(2);
  var i = 0;
  for(i = 1 to count)
    action.Execute(); // Evaluate the expression on each iteration
  end for
[/callback]
[body]
// Define a counter variable in the engine
uc.DefineVariable("counter = 0");

// The action 'counter++' is passed as an unevaluated expression
uc.DefineFunction("Repeat(count As Int, ByExpr action)", MyRepeat);

// Execute the custom loop
uc.Eval("Repeat(5, counter++)");

w("Final counter value: ")
wl(uc.Eval("counter"))
```

**Output:**
```
Final counter value: 5
```

---

### Example ID: 1231

**Description:** Internal Test: Implements a `ShortCircuitOr` function to prove that the second argument is not evaluated if the first is true, using side effects (counters) for verification.

**Code:**
```pseudocode
[head]
[callback ShortCircuitOr]
  var arg1 = cb.ArgExpr(1);
  var arg2 = cb.ArgExpr(2);

  // Evaluate the first argument
  var result1 = arg1.EvaluateBool();

  // If the first is true, return immediately without touching the second
  if (result1)
    cb.ReturnBool(true);
  else
    // Otherwise, evaluate and return the second argument's result
    cb.ReturnBool(arg2.EvaluateBool());
  end if
[/callback]

[callback FuncA]
  cb.@uCalc().Eval("countA = countA + 1");
  cb.ReturnBool(true);
[/callback]

[callback FuncB]
  cb.@uCalc().Eval("countB = countB + 1");
  cb.ReturnBool(true);
[/callback]

[body]
uc.DefineVariable("countA = 0");
uc.DefineVariable("countB = 0");

uc.DefineFunction("FuncA() As Bool", FuncA);
uc.DefineFunction("FuncB() As Bool", FuncB);

uc.DefineFunction("SC_Or(ByExpr a, ByExpr b) As Bool", ShortCircuitOr);

wl("Calling SC_Or(FuncA(), FuncB())...")
uc.Eval("SC_Or(FuncA(), FuncB())");

wl("FuncA was called ", uc.Eval("countA"), " time(s).")
wl("FuncB was called ", uc.Eval("countB"), " time(s).") // Should be 0
```

**Output:**
```
Calling SC_Or(FuncA(), FuncB())...
FuncA was called 1 time(s).
FuncB was called 0 time(s).
```

---

---

## Metaprogramming in Callbacks (ByHandle) - ID: 928
/doc/tutorials/beyond-the-basics---what-makes-ucalc-special?/metaprogramming-in-callbacks--byhandle/

**Description:** Explains how the ByHandle parameter modifier enables metaprogramming in callbacks by passing an argument's underlying metadata object.

**Remarks:**

# 🔬 Metaprogramming in Callbacks: The Power of `ByHandle`

While most functions operate on values, some of the most powerful programming techniques involve operating on the code itself. This is called **metaprogramming**. In uCalc, the `ByHandle` parameter modifier is the key that unlocks this capability, allowing your callbacks to inspect the properties of the arguments they receive, not just their final values.

### The Three Flavors of Argument Passing

To understand `ByHandle`, it's useful to compare it with the other argument modifiers:

*   **`ByVal` (Default)**: Passes the argument's final, computed **value**. This is standard behavior.
*   **`ByExpr`**: Passes the argument as an unevaluated [Expression](/Reference/uCalcBase/Expression/Constructor) object, representing the **code** itself. This is used for lazy evaluation.
*   **`ByHandle`**: Passes the argument's underlying [Item](/Reference/uCalcBase/Item/Constructor) object, representing its **metadata**. This is used for introspection.

### What is an `Item` Handle?

When a parameter is marked with `ByHandle`, your callback doesn't receive a simple number or string. Instead, it receives a handle to the argument's internal [Item](/Reference/uCalcBase/Item/Constructor) object, which you can retrieve with [cb.ArgItem()](/Reference/uCalcBase/Callback/ArgItem). This object is a rich container of metadata, allowing you to ask questions about the argument, such as:

*   **What is its name?** (`item.Name()`)
*   **What is its data type?** (`item.DataType()`)
*   **Was it a literal constant or a variable?** (`item.IsProperty(ItemIs::Variable)`)
*   **What is its value?** (`item.ValueStr()`)
*   **Where is it in memory?** (`item.ValueAddr()`)

This ability to inspect an argument *before* deciding what to do with it is the essence of metaprogramming in uCalc.

### Core Use Cases

1.  **Generic Functions**: Create versatile functions that can handle any data type. The practical example below shows a `Print` function that can accept and correctly display any number of arguments of any type by inspecting each one.
2.  **Validation & Assertions**: Write functions that check properties of their inputs. For example, an `AssertIsVariable(arg)` function could raise an error if the user passes a literal value like `5` instead of a variable name.
3.  **Modifying Caller State**: By getting a variable's memory address, a function can modify its value directly in the caller's scope, as demonstrated in the internal test's `Swap` function.

### 💡 Why uCalc? (Comparative Analysis)

*   **vs. C# Reflection (`MethodInfo`, `ParameterInfo`)**: While C# has powerful reflection capabilities, they are often complex and operate on compile-time constructs. uCalc's `ByHandle` provides a lightweight, runtime-focused alternative that is deeply integrated into the callback model. Retrieving an argument's metadata is a simple method call, not a complex traversal of `Type` and `Assembly` objects.

*   **vs. Dynamic Languages (Python/JavaScript)**: Languages like Python have rich introspection tools (e.g., the `inspect` module). `ByHandle` brings this dynamic power into a strongly-typed host environment (C#/C++), offering a unique combination of flexibility and performance. It allows you to build functions that are as dynamic as a Python script but run with the speed of compiled C++ code.

**Examples:**

### Example ID: 1236

**Description:** A simple `Describe` function that uses `ByHandle` to inspect an argument's name and data type.

**Code:**
```pseudocode
[head]
[callback DescribeArg]
  // Retrieve the Item object for the first argument.
  var item = cb.ArgItem(1);

  // Inspect the item's metadata.
  var name = item.@Name();
  if ([c]name == ""[/c][vb]Len(name) == 0[/vb])
    name = "(literal)";
  end if

  wl("  - Name: ", name, ", Type: ", item.@DataType().@Name());
[/callback]
[body]
uc.DefineFunction("Describe(ByHandle arg As AnyType)", DescribeArg);
uc.DefineVariable("my_var = 100");

wl("Inspecting a variable:")
uc.Eval("Describe(my_var)");

wl("Inspecting a literal value:")
uc.Eval("Describe(123.45)");

wl("Inspecting a string value:")
uc.EvalStr("Describe('abc xyz')");
```

**Output:**
```
Inspecting a variable:
  - Name: my_var, Type: double
Inspecting a literal value:
  - Name: (literal), Type: double
Inspecting a string value:
  - Name: (literal), Type: string
```

---

### Example ID: 1237

**Description:** A practical, generic `Print` function that can accept any number of arguments of any type and display them in a formatted string.

**Code:**
```pseudocode
[head]
[callback PrintGeneric]
  var(string, output) = "";
  var i = 0;
  for (i = 1 to cb.ArgCount())
    // Get the item and retrieve its value as a string.
    var item = cb.ArgItem(i);
    output = output + item.ValueStr();
    if (i < cb.ArgCount())
      output = output + ", ";
    end if
  end for
  wl(output)
[/callback]
[body]
// Define a variadic function that accepts any number of arguments ByHandle.
uc.DefineFunction("Print(ByHandle args As AnyType...)", PrintGeneric);

uc.Eval("Print('User:', 'Alice', 'ID:', 101, 'Status:', true)");
```

**Output:**
```
User:, Alice, ID:, 101, Status:, true
```

---

---

## Hierarchical Parsing (LocalTransformer) - ID: 929
/doc/tutorials/beyond-the-basics---what-makes-ucalc-special?/hierarchical-parsing--localtransformer/

**Description:** Explains how to use LocalTransformer to create nested, multi-level parsing logic for structured data formats like HTML or XML.

**Remarks:**

# 🌳 Hierarchical Parsing with LocalTransformer

Standard find-and-replace operations are typically "flat"—they scan an entire document from start to finish. However, real-world data is often hierarchical, with nested structures like HTML tags, JSON objects, or code blocks. The `LocalTransformer` is uCalc's elegant solution for this, enabling you to build powerful, multi-level parsers that understand scope and nesting.

It allows you to say: "First, find this outer block. Then, and only within that block, find these inner elements."

---

## The Problem: Lack of Scope

Imagine you want to extract all the links (`<a>` tags) from a navigation menu in an HTML document, but ignore all other links in the main content. A global search for `<a>` tags is too broad and will incorrectly include links from the entire page.

```html
<nav>
  <a href="/home">Home</a>
  <a href="/about">About</a>
</nav>
<main>
  <p>Some text with another <a href="/link">link</a>.</p>
</main>
```

A simple, flat pattern would find all three links. To solve this with traditional tools like regex, you would need a complex, multi-step process: first find the `<nav>` block, extract its content into a new string, run a second regex on that substring, and then manually map the results' coordinates back to the original document. This is inefficient and error-prone.

---

## The Solution: The `LocalTransformer`

The [LocalTransformer](/Reference/uCalcBase/Rule/LocalTransformer) property on a [Rule](/Reference/uCalcBase/Rule/Constructor) object provides a clean, integrated solution. It creates a nested [Transformer](/Reference/uCalcBase/Transformer/Constructor) whose scope is limited exclusively to the text captured by its parent rule.

#### The Two-Step Workflow:

1.  **Define the Parent Rule**: Create a rule that finds and captures the outer container. The content to be searched is captured into a variable (e.g., `{body}`).

    ```pseudocode
    var parentRule = t.Pattern("<nav>{body}</nav>");
    ```

2.  **Define Child Rules on the Local Transformer**: Get the local transformer from the parent rule and define rules on it. These rules will *only* run on the text captured by `{body}`.

    ```pseudocode
    var local_t = parentRule.@LocalTransformer();
    local_t.Pattern("<a {etc}>...</a>");
    ```

When the main [Transformer](/Reference/uCalcBase/Transformer/Constructor) runs, the engine handles the entire hierarchical process automatically. This creates a parent-child relationship between matches, which you can inspect using the [IsChildRule](/Reference/uCalcBase/Rule/IsChildRule) property and filter using [MatchesOption](/Reference/Enums/MatchesOption) flags like `RootLevelOnly` and `InnermostOnly`.

---

## `LocalTransformer` vs. `Tokens.ContextSwitch`

Both features handle nested syntax, but they operate at different stages and solve different problems.

| Feature | `LocalTransformer` (This Topic) | `Tokens.ContextSwitch` |
| :--- | :--- | :--- |
| **Stage** | **Syntactic (Parser)** | **Lexical (Tokenizer)** |
| **What it Does** | Applies a new set of grammar rules to a block of *already-tokenized* text. | Swaps the entire set of token definitions. Changes *how* text is broken into tokens. |
| **Nesting** | **Yes**. Local transformers can be nested to any depth. | **No**. Switches are not nestable by default. |
| **Use Case** | Parsing nested structures within the *same* language (e.g., finding `<img>` tags only within a specific `<div>`). | Parsing completely different, embedded languages (e.g., `<script>` in HTML, SQL in a string literal). |

**Conclusion**: Use `LocalTransformer` for hierarchical parsing within a consistent syntax. Use [ContextSwitch](/Reference/uCalcBase/Tokens/ContextSwitch) when you encounter a block of text that follows entirely different lexical rules.

**Examples:**

### Example ID: 1239

**Description:** A simple demonstration of finding a word but only inside a specific parenthetical block.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// 1. Parent rule finds content inside parentheses.
var parentRule = t.FromTo("({body})", "({body})");

// 2. Get the local transformer for the parent.
var local_t = parentRule.@LocalTransformer();

// 3. Child rule runs only inside the parentheses.
local_t.FromTo("this", "THIS");

var text = "do not find this, but (find this) and not this";
wl(t.Transform(text))
```

**Output:**
```
do not find this, but (find THIS) and not this
```

---

### Example ID: 1240

**Description:** A practical example that extracts all `<a>` tags, but only from within a specific `<nav>` section of an HTML document.

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Ignore multi-line formatting
t.@DefaultRuleSet().@StatementSensitive(false);

// 1. Parent rule captures the content of the <nav> block.
var navRule = t.Pattern("<nav>{content}</nav>");

// 2. Get the local transformer for the nav block.
var local_t = navRule.@LocalTransformer();

// 3. This rule will only find `<a>` tags inside the <nav> block.
local_t.Pattern("<a href={url}>{text}</a>");

var html = [verbatim]<nav>
  <a href="/home">Home</a>
  <a href="/about">About</a>
</nav>
<main>
  <p>Some text with another <a href="/other">other link</a>.</p>
</main>[/verbatim];

t.@Text(html);
t.Find();

wl("--- Found Links (Innermost Matches Only) ---")
// Use InnermostOnly to see only the results from the local transformer.
wl(t.GetMatches(MatchesOption::InnermostOnly).@Text())
```

**Output:**
```
--- Found Links (Innermost Matches Only) ---
<a href="/home">Home</a>
<a href="/about">About</a>
```

---

---

## Advanced Integration - ID: 897
/doc/tutorials/advanced-integration/

---

## Binding to Native Code with Callbacks - ID: 913
/doc/tutorials/advanced-integration/binding-to-native-code-with-callbacks/

**Description:** Learn how to expose high-performance native host application code to the uCalc expression engine using callback functions.

**Remarks:**

# 🤝 Binding to Native Code with Callbacks

While defining simple functions as inline expressions is fast and convenient, the true power of uCalc's extensibility comes from **callback binding**. This feature creates a seamless bridge between the flexible uCalc scripting environment and your high-performance, native host application code (C#, C++, VB.NET).

A callback allows an expression to call a function in your compiled code, passing it arguments and receiving a value back. This is the primary mechanism for integrating uCalc with existing application logic, accessing system resources (like files or databases), or implementing complex algorithms that would be too slow or cumbersome for an expression string.

---

## 1. The Two-Step Process

Every callback binding involves two key parts: the definition in uCalc and the implementation in your host code.

### A. The Definition

You use [DefineFunction](/Reference/uCalcBase/uCalc/DefineFunction) or [DefineOperator](/Reference/uCalcBase/uCalc/DefineOperator) to tell the uCalc engine about your function. You provide the function's signature as a string, but instead of an expression body, you pass the memory address of your native callback function.

```pseudocode
// The second argument is a pointer/delegate to our native callback.
uc.DefineFunction("MyNativeFunc(x As Int)", MyNativeFunc_Callback);
```

### B. The Implementation (The Callback)

This is a function you write in your host language. When uCalc evaluates an expression containing your custom function, it calls this native code. Your callback function receives a special `Callback` object (typically named `cb` in examples) which acts as the interface for communicating with the engine.

Inside the callback, you use the `cb` object to:
1.  **Get Arguments**: Retrieve the values passed from the expression using methods like `cb.Arg(n)`, `cb.ArgStr(n)`, etc.
2.  **Return a Value**: Send a result back to the expression using `cb.Return(value)`, `cb.ReturnStr(value)`, etc.

It's crucial to understand that you do **not** use your language's standard `return` keyword to send a value back to uCalc. You must use the methods on the `Callback` object.

---

## 2. Getting Arguments and Returning Values

### Retrieving Arguments

The `Callback` object provides a family of type-safe methods for retrieving arguments.

*   `cb.Arg(n)`: Gets the nth argument as a `double`. The generic default.
*   `cb.ArgStr(n)`: Gets the nth argument as a `string`.
*   `cb.ArgInt32(n)`: Gets the nth argument as a 32-bit integer.
*   `cb.ArgBool(n)`: Gets the nth argument as a boolean.

⚠️ **Important**: Argument indexing is **1-based**, not 0-based. The first argument is at index `1`, the second at index `2`, and so on.

### Returning a Value

Similarly, you use type-specific methods to set the return value.

*   `cb.Return(value)`: Returns a `double`.
*   `cb.ReturnStr(value)`: Returns a `string`.
*   `cb.ReturnInt32(value)`: Returns a 32-bit integer.

The simple example below demonstrates this entire flow.

---

## ✨ Why uCalc? (Comparative Analysis)

*   **vs. Other Scripting Engines (Lua, Python)**: Binding C++ or C# functions to embedded scripting engines often requires complex binding libraries (like LuaBridge or Boost.Python), code generation, or significant boilerplate to marshal data types. uCalc's callback system is designed to be lightweight and direct, making it exceptionally easy to expose a single native function to the expression engine.

*   **vs. Native Code**: The most significant advantage is **runtime dynamism**. In a compiled language, a function call is resolved at compile-time. uCalc allows a string—which can be created at runtime from user input or a configuration file—to execute high-performance, pre-compiled native code. This provides the flexibility of a scripting language with the speed of a native application.

*   **Advanced Metaprogramming**: uCalc's callback system goes beyond simple value passing. With advanced argument modifiers like `ByExpr`, `ByHandle`, and `ByRef`, your native callback can receive unevaluated expressions, inspect argument metadata, or modify variables in the caller's scope. For more details, see the [Creating Custom Functions](/Tutorials/Getting-Started:-The-Expression-Parser/Creating-Custom-Functions) tutorial.

**Examples:**

### Example ID: 1242

**Description:** Defines a simple `Add` function that is implemented by a native callback to perform addition.

**Code:**
```pseudocode
[head]
[callback MyAdd]
  var x = cb.Arg(1);
  var y = cb.Arg(2);
  cb.Return(x + y);
[/callback]
[body]
// Link the uCalc function 'Add' to the native 'MyAdd' callback.
uc.DefineFunction("Add(x, y)", MyAdd);

// Now the native code can be called from an expression.
wl(uc.Eval("Add(10, 5)"))
```

**Output:**
```
15
```

---

### Example ID: 1243

**Description:** Demonstrates a practical callback that retrieves a 'host application setting', simulating I/O or access to native configuration.

**Code:**
```pseudocode
[head]
[callback GetSetting]
  // Get the name of the setting to retrieve.
  var settingName = cb.ArgStr(1);
  
  // In a real app, this would read from a config file, database, or registry.
  // We simulate it by evaluating another variable in the parent uCalc context.
  var value = cb.@uCalc().EvalStr(settingName);
  
  cb.ReturnStr(value);
[/callback]
[body]
// Simulate a host application's configuration store using uCalc variables.
uc.DefineVariable("AppName = 'uCalc Demo'");
uc.DefineVariable("Version = '1.2.3'");

// Define the function that provides a bridge to the 'host'.
uc.DefineFunction("GetHostSetting(name As String) As String", GetSetting);

// Use the custom function to build a string from the host settings.
wl(uc.EvalStr("GetHostSetting('AppName') + ' v' + GetHostSetting('Version')"));
```

**Output:**
```
uCalc Demo v1.2.3
```

---

### Example ID: 1244

**Description:** Internal Test: A variadic function that sums only the arguments matching a specific data type name, testing argument introspection capabilities.

**Code:**
```pseudocode
[head]
[callback SumIfType]
  var typeName = cb.ArgStr(1);
  var(double, total) = 0;
  var(string, totalStr) = "";
  var i = 0;

  // Loop through all arguments starting from the second one.
  for (i = 2 to cb.ArgCount())
    var item = cb.ArgItem(i);
    // Check if the argument's data type name matches.
    if (item.@DataType().@Name() == "double")      
      total = total + item.Value();
    else if (item.@DataType().@Name() == "string")
      totalStr = totalStr + item.ValueStr();
    end if
  end for
  
  if (typeName == "double")
      totalStr = [cpp]to_string(total)[/cpp][NotCpp]total.ToString()[/NotCpp]; 
  end if
  cb.ReturnStr(totalStr);
[/callback]
[body]
// Define the variadic function.
uc.DefineFunction("SumIfType(typeName As String, ByHandle other As AnyType ...) As String", SumIfType);

// This call will sum only the double values (5.0 and 10.123456), ignoring the integer.
wl(uc.EvalStr("SumIfType('double', 5.0, 'Hello ', 10.123456, 'world!')"));

// This call will concatinate only the string values.
wl(uc.EvalStr("SumIfType('string', 5.0, 'Hello ', 10.123456, 'world!')"));
```

**Output:**
```
15.123456
Hello world!
```

---

---

## Advanced Argument Passing - ID: 930
/doc/tutorials/advanced-integration/advanced-argument-passing/

**Description:** Explores advanced callback parameter modifiers like ByRef, ByExpr, and ByHandle for metaprogramming and lazy evaluation.

**Remarks:**

# 🚀 Advanced Argument Passing: ByRef, ByExpr, and ByHandle

While most functions operate on simple values passed `ByVal`, uCalc's real power comes from its advanced argument passing modifiers. These special keywords, used in function signatures defined with [DefineFunction](/Reference/uCalcBase/uCalc/DefineFunction), allow you to build functions that can modify variables in place, delay execution for performance, and inspect the very structure of the code they are given. They transform a simple [Callback](/Reference/uCalcBase/Callback/Constructor) from a calculator into an intelligent, context-aware meta-program.

This tutorial explores the three advanced modifiers that make this possible.

---

## 1. `ByRef`: Modifying Caller Variables

The `ByRef` modifier allows you to pass a variable **by reference**. This creates an *in-out* parameter, meaning your callback function receives a direct link to the original variable and can modify its value in the caller's scope.

#### 💡 Why uCalc? (Comparative Analysis)
This is conceptually similar to C#'s `ref` keyword or C++'s `&` references. The key difference is uCalc's dynamic nature. You are defining this reference behavior at **runtime** within a string-based script engine, enabling you to create functions with side effects that are not hardcoded at compile time. It provides the power of native reference passing within a flexible, sandboxed environment.

---

## 2. `ByExpr`: Lazy Evaluation for Control Structures

The `ByExpr` modifier is the key to **lazy evaluation**. Instead of evaluating an argument and passing its result, uCalc passes the argument as a complete, unevaluated [Expression](/Reference/uCalcBase/Expression/Constructor) object. Your callback function then has full control over if, when, and how many times that expression is executed.

This is the mechanism used to build custom control structures. The built-in [IIf](/Reference/Functions-and-Operators/Functions/Specialized) function, for example, uses `ByExpr` for its `then` and `else` parts to ensure that only the chosen branch is ever evaluated, preventing errors and side effects in the other.

#### 💡 Why uCalc? (Comparative Analysis)
Passing an expression is similar to passing a `Func<T>` delegate in C# or a lambda in C++. Both pass a piece of code to be executed later. However, uCalc's approach is superior for dynamic environments because:
*   The expression is defined in a string at runtime.
*   [The callback receives a rich [Expression](/Reference/uCalcBase/Expression/Constructor) object that can be inspected (e.g., getting its original text) before execution, enabling metaprogramming.]

---

## 3. `ByHandle`: Introspection and Metaprogramming

The `ByHandle` modifier is the most powerful tool for introspection. It passes the argument's underlying [Item](/Reference/uCalcBase/Item/Constructor) object, giving your callback access to a wealth of metadata about the argument before its value is even considered.

Inside the callback, you can use the `Item` object to inspect:
*   The argument's original name (`item.Name`).
*   Its data type (`item.DataType`).
*   Whether it was a literal, a variable, or another function call.
*   Its original definition string (`item.Text)`).

#### 💡 Why uCalc? (Comparative Analysis)
This is uCalc's equivalent of a full-fledged reflection API. While C# reflection operates on compiled types, uCalc's `ByHandle` provides this power at runtime on symbols defined within its dynamic scripting environment. It allows you to write functions that analyze the code they are given, a feature typically found only in highly dynamic languages like LISP.

---

## Summary Table

| Modifier | What is Passed | Primary Use Case |
| :--- | :--- | :--- |
| `ByRef` | A direct reference to a variable's memory. | Creating functions with side effects (in-out parameters). |
| `ByExpr` | An unevaluated [Expression](/Reference/uCalcBase/Expression/Constructor) object. | Lazy evaluation; building custom control structures like loops and conditionals. |
| `ByHandle`| The argument's underlying [Item](/Reference/uCalcBase/Item/Constructor) metadata object. | Introspection and metaprogramming; analyzing an argument's name, type, and source. |

**Examples:**

### Example ID: 1248

**Description:** A practical example of `ByRef` to create a classic `Swap` function that modifies its arguments in the caller's scope.

**Code:**
```pseudocode
[head]
[callback SwapValues]
  // Get the item handles for the two variables passed by reference
  var item1 = cb.ArgItem(1);
  var item2 = cb.ArgItem(2);

  // Use the item's DataType object to perform a highly efficient, pointer-based swap
  item1.@DataType().SwapScalarValues(item1.ValueAddr(), item2.ValueAddr());
[/callback]
[body]
// Define the Swap function with ByRef parameters
uc.DefineFunction("Swap(ByHandle a, ByHandle b)", SwapValues);

// Define the variables to be swapped
uc.DefineVariable("x = 100");
uc.DefineVariable("y = 200");

wl("Before: x = ", uc.Eval("x"), ", y = ", uc.Eval("y"))

// Call the swap function
uc.Eval("Swap(x, y)");

wl("After:  x = ", uc.Eval("x"), ", y = ", uc.Eval("y"))
```

**Output:**
```
Before: x = 100, y = 200
After:  x = 200, y = 100
```

---

### Example ID: 1249

**Description:** Demonstrates `ByExpr` to create a custom `Assert` function where the error message is only evaluated if the assertion fails, improving performance.

**Code:**
```pseudocode
[head]
[callback Assert]
  var condition = cb.ArgBool(1);

  // If the condition is false, then we evaluate the message expression
  if (condition == false)
    var errorMessage = cb.ArgExpr(2);
    wl("Assertion failed: ", errorMessage.EvaluateStr())
  end if
[/callback]
[body]
uc.DefineVariable("x = 50");

// The message is passed as an unevaluated expression
uc.DefineFunction("Assert(condition As Bool, ByExpr message As String)", Assert);

// This will do nothing because the condition is true
uc.Eval("Assert(10 < 20, 'This will not be evaluated')");

// This will trigger the assertion and evaluate the message expression
uc.Eval("Assert(x > 100, 'x (' + Str(x) + ') is not greater than 100')");
```

**Output:**
```
Assertion failed: x (50) is not greater than 100
```

---

### Example ID: 1250

**Description:** A practical example of `ByHandle` to create a `TypeOf` function that introspects an argument and returns its data type name as a string.

**Code:**
```pseudocode
[head]
[callback GetTypeOf]
  // Get the Item object for the argument
  var item = cb.ArgItem(1);

  // Get the item's DataType, then its name, and return it as a string
  cb.ReturnStr(item.@DataType().@Name());
[/callback]
[body]
// The ByHandle modifier passes the argument's metadata (Item) instead of its value
uc.DefineFunction("TypeOf(ByHandle arg As AnyType) As String", GetTypeOf);

uc.DefineVariable("myInt As Int = 10");
uc.DefineVariable("myStr As String = 'hello'");
uc.DefineVariable("myDbl = 3.14"); // Type is inferred as double

wl("Type of myInt: ", uc.EvalStr("TypeOf(myInt)"))
wl("Type of myStr: ", uc.EvalStr("TypeOf(myStr)"))
wl("Type of myDbl: ", uc.EvalStr("TypeOf(myDbl)"))
```

**Output:**
```
Type of myInt: int
Type of myStr: string
Type of myDbl: double
```

---

---

## Managing Parser Instances & Lifetime - ID: 915
/doc/tutorials/advanced-integration/managing-parser-instances-&-lifetime/

**Description:** Explains the critical patterns for managing uCalc instance memory and lifetime to prevent resource leaks, covering both automatic (RAII/using) and manual release strategies.

**Remarks:**

# ⚙️ Managing Parser Instances & Lifetime

A [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance is more than just an object; it's a complete, sandboxed parsing and evaluation engine with its own state, including variables, functions, and settings. Because the core engine is written in high-performance C++, proper management of its memory and lifetime is one of the most critical aspects of using the library correctly.

This guide explains why lifetime management is necessary and covers the two primary strategies for preventing resource leaks.

## 1. The Core Concept: Managed Handle, Unmanaged Engine

When you create a `uCalc` object in a managed language like C# or VB.NET, the variable you hold is a lightweight **handle**. This handle points to the substantial, underlying C++ engine instance where the real work happens. The garbage collector (GC) in .NET only knows about the handle, not the unmanaged C++ engine.

If you simply let a `uCalc` handle go out of scope, the GC will clean up the handle, but the C++ engine instance will remain in memory, causing a **memory leak**.

Therefore, you must explicitly tell the engine when an instance is no longer needed. There are two ways to do this.

## 2. Automatic Lifetime Management (The Recommended Way)

The best practice is to tie the lifetime of a `uCalc` instance to a specific lexical scope. This is achieved using language-idiomatic patterns that guarantee cleanup.

### 💎 For C# and VB.NET: The `using` Statement

All major uCalc objects implement the `IDisposable` interface, making them compatible with the `using` statement. This is the safest and most recommended pattern in .NET.

```pseudocode
NewUsing(uCalc, tempCalc(uc.Clone()))
    wl("Inside scope, instance is active.");
End Using // tempCalc.Release() is called automatically here.
wl("Outside scope, instance has been released.");
```
For more language-specific details, see the [C#](/Concepts/Language-specific/C#) and [VB](/Concepts/Language-specific/VB) topics.

### 💎 For C++: RAII and the `Owned()` Method

C++ developers should leverage the **RAII (Resource Acquisition Is Initialization)** pattern. By creating a `uCalc` object on the stack and calling the [Owned()](/Reference/uCalcBase/uCalc/Owned) method, you instruct its destructor to automatically call [Release()](/Reference/uCalcBase/uCalc/Release) when the object goes out of scope.

```pseudocode
// The 'NewUsing' block ensures the object's destructor calls Release().
{
    auto scopeduCalc = new uCalc();
    // .Owned() is implied by NewUsing in C++, but an explicit call may clarify intent.
    scopedCalc.DefineVariable("val = 100");
    wl("Inside C++ scope, instance is active.");
} // scopedCalc's destructor is called automatically here.
wl("Outside C++ scope, instance has been released.");
[NotCpp]
// This example demonstrates C++ specific RAII.
wl("Inside C++ scope, instance is active.");
wl("Outside C++ scope, instance has been released.");
[/NotCpp]
```
For more details, see the [C++](/Concepts/Language-specific/C++) language topic.

## 3. Manual Lifetime Management with `Release()`

If the lifetime of a `uCalc` instance is not tied to a specific scope (e.g., a globally accessible instance), you must manage its lifecycle manually by calling the [Release()](/Reference/uCalcBase/uCalc/Release) method when you are finished with it.

```pseudocode
// Create a new instance.
var myInstance = uc.Clone();

// ... use the instance ...

// Manually release it to prevent a memory leak.
myInstance.Release();
wl("Instance has been manually released.");
```

⚠️ **Warning**: Forgetting to call [Release()](/Reference/uCalcBase/uCalc/Release) on objects that are not managed by a `using` block or RAII is the most common cause of memory leaks when using uCalc.

**Examples:**

### Example ID: 1255

**Description:** Shows the RAII pattern in C++ using a stack-allocated object and the `Owned()` method for automatic cleanup.

**Code:**
```pseudocode
[cpp]
// The NewUsing block ensures the object's destructor calls Release().
NewUsing(uCalc, scopedCalc)
    scopedCalc.DefineVariable("val = 100");
    wl("Inside C++ scope: ", scopedCalc.Eval("val"));
End Using // scopedCalc's destructor calls Release() here.
wl("Outside C++ scope, instance is released.")
[/cpp]
[NotCpp]
// This example demonstrates C++ specific RAII.
wl("Inside C++ scope: 100")
wl("Outside C++ scope, instance is released.")
[/NotCpp]
```

**Output:**
```
Inside C++ scope: 100
Outside C++ scope, instance is released.
```

---

---

## The uCalc.String Library - ID: 898
/doc/tutorials/the-ucalc.string-library/

---

## Introduction to Smart Strings - ID: 916
/doc/tutorials/the-ucalc.string-library/introduction-to-smart-strings/

**Description:** Introduces the uCalc.String class, a mutable, token-aware string object designed for high-performance, chainable text manipulation.

**Remarks:**

[revisit]
# ✨ Introduction to Smart Strings

Welcome to the `uCalc.String` library! This is uCalc's answer to the limitations of standard string types. While native strings are great for storage, they are often inefficient for complex manipulation. `uCalc.String` is a high-performance, **mutable**, and **token-aware** string class designed from the ground up for parsing and transformation tasks.

Think of it as a `StringBuilder` on steroids, combining the features of a text builder, a lightweight transformation engine, and a list processor into a single, fluent API.

## 1. ⚡ Mutability & Performance

The biggest difference from a standard `string` is **mutability**. Native strings are immutable; every modification (like a replace or append) creates a brand new string object in memory, which is inefficient. `uCalc.String` is designed to be modified **in-place**, making it ideal for building or manipulating text in loops.

```pseudocode
// Standard strings create new objects
var s = "Hello";
s = s + " World"; // 's' now points to a new string object

// uCalc.String modifies its internal buffer
New(uCalc::String, ucs("Hello"));
ucs.Append(" World"); // The existing object is modified
```

## 2. 🧠 Token-Aware Operations

This is the "smart" part of Smart Strings. Unlike `Regex` or standard `string.Replace()`, which are character-aware, [uCalc.String](/Reference/uCalcBase/String/Constructor) is **token-aware**. It understands the structure of your text.

By default, operations like [SubString()](/Reference/uCalcBase/String/SubString) or [Replace()](/Reference/uCalcBase/String/Replace) don't count characters; they count **tokens** (words, numbers, symbols). This provides structural safety, automatically respecting word boundaries, quoted strings, and nested brackets.

## 3. ⛓️ Fluent Chaining & Live Views

[uCalc.String](/Reference/uCalcBase/String/Constructor) is designed for a fluent, chainable API. Methods can be linked together to create powerful "one-liner" transformations.

Crucially, methods that extract a portion of a string (like [After()](/Reference/uCalcBase/String/After) or [Between()](/Reference/uCalcBase/String/Between)) don't return a disconnected copy. They return a new [uCalc.String](/Reference/uCalcBase/String/Constructor) object that is a **live, modifiable view** into the parent. Any changes made to the child view are instantly reflected in the original parent string.

This architecture enables powerful editing pipelines and is a core concept you'll see in the following examples.

## `uCalc.String` vs. `Transformer`

*   **[uCalc.String](/Reference/uCalcBase/String/Constructor)**: Best for fluent, single-string "one-liner" transformations. Think of it as a scripting tool for quick modifications.
*   **[Transformer](/Reference/uCalcBase/Transformer/Constructor)**: Best for managing a complex set of reusable rules or performing multi-pass transformations. Think of it as a compiler for text.

They share the same underlying engine but offer different interfaces for different tasks. Ready to see it in action?

**Examples:**

### Example ID: 1257

**Description:** A simple find-and-replace operation using the fluent, chainable API.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("The quick brown fox."))

// Replace returns the modified String object, but also modifies it in-place
s.Replace("brown", "red");

// Use implicit conversion to print the result
wl(s)
End Using;
```

**Output:**
```
The quick red fox.
```

---

---

## Chaining Fluent Operations - ID: 917
/doc/tutorials/the-ucalc.string-library/chaining-fluent-operations/

**Description:** Explains how to link multiple uCalc.String operations together in a single, readable statement to create powerful text-processing pipelines.

**Remarks:**

[revisit]
# ⛓️ Chaining Fluent Operations

One of the most powerful features of the [uCalc.String](/Reference/uCalcBase/String/Constructor) class is its **fluent interface**. This means that most methods return the `uCalc.String` object itself, allowing you to "chain" multiple operations together into a single, highly readable statement. This turns complex, multi-step text manipulations into concise, elegant pipelines.

## The "Live View" Pipeline

The core concept behind chaining is the "live view." Methods that extract a portion of a string—like [After()](/Reference/uCalcBase/String/After), [Before()](/Reference/uCalcBase/String/Before), and [Between()](/Reference/uCalcBase/String/Between)—do not create a disconnected copy of the text. Instead, they return a new `uCalc.String` object that acts as a live, modifiable window or "view" into the original, parent string.

Think of it like focusing a lens:
1.  You start with the full document (the parent `uCalc.String`).
2.  You use `After("start")` to create a view focused only on the text after your starting point.
3.  You then chain `.Between("(", ")")` onto that view, narrowing your focus even further to just the content inside the parentheses.
4.  Finally, you apply an action like `.Replace("old", "new")` to that focused view.

Because the view is live, the replacement you make is reflected directly in the original, parent string. This allows for incredibly powerful and efficient in-place editing.

## 💡 Why uCalc? (Comparative Analysis)

In traditional string manipulation, achieving the same result requires a verbose, multi-step process that creates temporary, disconnected string objects at each stage.

**Typical C# Approach (Manual & Inefficient):**
```csharp
string text = "config user='admin' level=9";
int userPos = text.IndexOf("user=") + 5; // Find start
string temp1 = text.Substring(userPos); // Create first temp string
int startQuote = temp1.IndexOf("'") + 1;
int endQuote = temp1.IndexOf("'", startQuote);
string username = temp1.Substring(startQuote, endQuote - startQuote); // Create second temp string
string modifiedUsername = username.ToUpper(); // Create third temp string
string final = text.Replace(username, modifiedUsername); // Create final string
```

This code is hard to read, inefficient due to multiple string allocations, and prone to off-by-one errors.

**The uCalc Fluent Approach (Clean & Efficient):**
```pseudocode
NewUsing(uCalc::String, s("config user='admin' level=9"))
s.After("user=").Between("'", "'").ToUpper();
End Using
```
This single line of code achieves the same result by creating a pipeline of live views. It is more readable, less error-prone, and performs better by avoiding the creation of intermediate string copies.

**Examples:**

### Example ID: 1260

**Description:** A succinct example demonstrating a simple chain of two replacement actions on the root string.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("A and C"))

// Each Replace() call returns the modified string object, allowing the next call.
s.Replace("A", "B").Replace("C", "D");

w("Result: ")
wl(s)
End Using;
```

**Output:**
```
Result: B and D
```

---

---

## Hands-on starter projects - ID: 989
/doc/tutorials/hands-on-starter-projects/

---

## Project: Building a Markdown to HTML Converter - ID: 1005
/doc/tutorials/hands-on-starter-projects/project:-building-a-markdown-to-html-converter/

**Description:** A step-by-step guide to building a simple Markdown to HTML converter using the declarative rules of the uCalc Transformer.

**Remarks:**

# 📝 Project: Building a Markdown to HTML Converter

This project will guide you through building a simple, functional Markdown to HTML converter. It's a perfect real-world example of how the declarative power of the [uCalc.Transformer](/Reference/uCalcBase/Transformer/Constructor) can solve complex text-structuring problems more safely and readably than traditional tools like Regular Expressions.

### The Goal

We'll create a transformer that can convert basic Markdown syntax into the corresponding HTML tags:
*   **Headers**: `# A Header` → `<h1>A Header</h1>`
*   **List Items**: `* An item` → `<li>An item</li>`
*   **Bold Text**: `**bold**` → `<b>bold</b>`
*   **Italic Text**: `*italic*` → `<i>italic</i>`

---

### 🤔 Why uCalc Instead of Regex?

While you could attempt this with a series of `Regex.Replace` calls, you would quickly run into problems, especially with inline styles. A regex for italic text (`\*(.*?)\*`) would incorrectly match bold text (`**text**`), leading to broken tags. Handling this requires complex negative lookarounds that are difficult to write and maintain.

The uCalc [Transformer](/Reference/uCalcBase/Transformer/Constructor) avoids this by being **token-aware** and using a clear **rule precedence** system, making the solution both more robust and easier to understand.

---

## Step 1: Setting Up the Transformer

First, we need a [Transformer](/Reference/uCalcBase/Transformer/Constructor) instance. We will also enable [RewindOnChange](/Reference/uCalcBase/Rule/RewindOnChange) for all rules. This is crucial because it tells the transformer to re-scan the text after a replacement. Without it, after converting a list item line like `* text with **bold**` into `<li>text with **bold**</li>`, the engine would not re-scan the new text to find and convert the `**bold**` part.

```pseudocode
NewUsing(uCalc::Transformer, t)
    t.@DefaultRuleSet().@RewindOnChange(true);
    // ... rules go here ...
End Using
```

## Step 2: Defining the Rules

Next, we'll define our conversion logic using [FromTo()](/Reference/uCalcBase/Transformer/FromTo) rules. We'll start with block-level elements (headers and lists), which operate on whole lines.

```pseudocode
// Headers: Match a '#' at the start of a line, capture the rest.
// The implicit newline at the end of the line will stop the {line} capture.
t.FromTo("#{@Whitespace}{line}", "<h1>{line}</h1>");

// List Items: Match a '*' at the start of a line.
t.FromTo("*{@Whitespace}{line}", "<li>{line}</li>");
```

Now for the inline elements. This is where rule order becomes critical.

```pseudocode
// Rule for Italic text
t.FromTo("*{text}*", "<i>{text}</i>");

// Rule for Bold text
t.FromTo("**{text}**", "<b>{text}</b>");
```

## Step 3: Rule Order is Crucial! (LIFO Precedence)

In the code above, why did we define the rule for italics *before* the rule for bold? Because the [Transformer](/Reference/uCalcBase/Transformer/Constructor) checks rules in a **LIFO (Last-In, First-Out)** order. The **last rule defined is checked first**.

*   The pattern `**{text}**` is more specific than `*{text}*`.
*   If the italic rule were defined last, it would match `**bold**` as `*` + `*bold` + `*`, resulting in `<i>*bold</i>*`—incorrect HTML!
*   By defining the bold rule last, we give it higher precedence. The transformer will check for `**...**` first. If it matches, great. If not, it will then check for `*...*`.

This is a fundamental concept for writing correct transformation logic.

## Step 4: Putting It All Together

The full example below combines these rules to process a sample Markdown document. The transformer will correctly handle both block-level tags and nested inline tags in a single pass.

## Next Steps: Handling `<ul>` Tags

You'll notice this simple converter creates `<li>` tags but doesn't wrap them in the required `<ul>...</ul>` container. This is a classic multi-pass transformation problem. To solve it, you could:
1.  Run the first pass (as we did here) to generate the `<li>` tags.
2.  Run a second pass with a new rule that finds consecutive blocks of `<li>` tags and wraps them in `<ul>...</ul>`.

This demonstrates how you can build sophisticated pipelines by chaining transformers or using the [Pass](/Reference/uCalcBase/Transformer/Pass) system.

**Examples:**

### Example ID: 1404

**Description:** A single-pass transformer that converts headers, list items, bold, and italic Markdown syntax to HTML.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
    t.@DefaultRuleSet().@RewindOnChange(true);

    // 2. Define Rules (General rules first, specific rules last for LIFO precedence)

    // -- Inline rules --
    // Italic is defined before Bold, giving Bold higher precedence.
    t.FromTo("*{text}*", "<i>{text}</i>");
    t.FromTo("**{text}**", "<b>{text}</b>");

    // -- Block-level rules --
    t.FromTo("#{@Whitespace}{line}", "<h1>{line}</h1>");
    t.FromTo("*{@Whitespace}{line}", "<li>{line}</li>");
    t.FromTo("</li>{@nl}{@nl}", "</li>{@nl}</ul>{@nl}"); // {@nl} = NewLine
    t.FromTo("{@nl}{@nl}*{@Whitespace}", "{@nl}<ul>{@nl}* ");

    // 3. Define the input Markdown text
    var markdown = [verbatim]
# Main Header

* First list item
* Second list item with **bold** text.
* Third list item with *italic* text.

Another paragraph with **bold** and *italic*.
[/verbatim];

    // 4. Run the transformation and print the result
    wl(t.Transform(markdown))
End Using
```

**Output:**
```
<h1>Main Header</h1>
<ul>
<li>First list item</li>
<li>Second list item with <b>bold</b> text.</li>
<li>Third list item with <i>italic</i> text.</li>
</ul>
Another paragraph with <b>bold</b> and <i>italic</i>.
```

---

---

## Project: Building a JSON Formatter and Minifier - ID: 996
/doc/tutorials/hands-on-starter-projects/project:-building-a-json-formatter-and-minifier/

**Description:** A step-by-step project to build a simple parser for INI-style configuration files using the uCalc Transformer's hierarchical parsing capabilities.

**Remarks:**

# 💡 Project: Building a JSON Formatter and Minifier

This project will guide you through building two essential tools for working with JSON: a **formatter** (or "pretty-printer") to make it human-readable, and a **minifier** to make it compact for transmission. It's a perfect real-world example of how the uCalc [Transformer's](/Reference/uCalcBase/Transformer/Constructor) token-aware, rule-based engine can parse and manipulate structured data formats.

### The Goal

We'll create two transformers that can take a JSON string and convert it between these two formats:

**Minified Input:**
`{"id":123,"name":"Example","tags":["A","B"],"active":true}`

**Formatted Output:**
```json
{
  "id": 123,
  "name": "Example",
  "tags": [
    "A",
    "B"
  ],
  "active": true
}
```

### 💡 Why uCalc? (vs. Regex or a Dedicated JSON Library)

*   **vs. Dedicated Libraries (Newtonsoft.Json, System.Text.Json)**: For production use, a dedicated, security-hardened JSON library is always the right choice. This project is an educational exercise to demonstrate *how* you would build a parser for a structured language. The principles learned here can be applied to any custom, non-standard format where a dedicated library doesn't exist.

*   **vs. Regular Expressions**: A regex-based approach would be extremely fragile. It would struggle to distinguish between a comma separating key-value pairs and a comma inside a string literal. uCalc's [Transformer](/Reference/uCalcBase/Transformer/Constructor) is **token-aware**. By default, it treats a quoted string as a single, unbreakable unit, making it safe and reliable for this task.

---

## Step 1: The Formatter (Pretty-Printer)

The formatter's job is to insert newlines and indentation around structural tokens: `{`, `}`, `[`, `]`, `,`, and `:`. To manage the indentation level, we need to maintain state during the transformation. This is a perfect use case for a uCalc variable controlled by `{@Exec}`.

### The Strategy
1.  Create a `uCalc` variable named `indent` to track the current indentation level.
2.  Create a helper function `IndentStr()` to generate the indentation string.
3.  Define rules for each structural token to insert newlines and call `IndentStr()`, incrementing or decrementing the `indent` variable as needed.

## Step 2: The Minifier

The minifier's job is much simpler: remove all non-essential whitespace. This includes spaces, tabs, and newlines that are not inside a string literal.

### The Strategy
1.  Define a rule to find and remove all tokens categorized as `{@Whitespace}`.
2.  Define a second rule to find and remove all `{@Newline}` tokens.

Because the [Transformer](/Reference/uCalcBase/Transformer/Constructor) is `QuoteSensitive` by default, it will automatically protect any whitespace inside string values.

Let's see the complete implementation.


**Examples:**

### Example ID: 1382

**Description:** A complete JSON formatter that takes a minified string and pretty-prints it with proper indentation.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t(uc))
    // 1. Define state variable in the uCalc instance.
    uc.DefineVariable("indent = 0");

    // 2. Define the transformation rules.
    // Note: '{', '}', '[', ']' are escaped with quotes to be treated as literals.

    // Rule for '{' and '[': Add newline, increment indent, add indent string.
    t.FromTo("{ '{' | '[' }", "{@Self}{@nl}{@Exec: indent++}{@Eval: '  ' * indent}");

    // Rule for '}' and ']': Add newline, decrement indent, add indent string.
    t.FromTo("{ '}' | ']' }", "{@nl}{@Exec: indent--}{@Eval: '  ' * indent}{@Self}");

    // Rule for ',': Add newline and current indent string.
    t.FromTo(",", ",{@nl}{@Eval: '  ' * indent}");

    // Rule for ':': Add a space after it for readability.
    t.FromTo(":", ": ");

    // 3. Define the minified input string.
    var minifiedJson = [verbatim]{"id":123,"name":"Example","tags":["A","B"],"active":true}[/verbatim];

    // 4. Run the transformation and print the result.
    wl(t.Transform(minifiedJson))
End Using
```

**Output:**
```
{
  "id": 123,
  "name": "Example",
  "tags": [
    "A",
    "B"
  ],
  "active": true
}
```

---

### Example ID: 1383

**Description:** A complete JSON minifier that takes a formatted string and removes all non-essential whitespace.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
    // 1. Define rules to remove whitespace and newlines.
    // The engine's default QuoteSensitive=true ensures whitespace inside strings is protected.
    t.FromTo("{@Whitespace}", "");
    t.FromTo("{@Newline}", "");

    // 2. Define the formatted input string.
    var formattedJson = [verbatim]{
  "id": 123,
  "name": "Example, with spaces",
  "tags": [
    "A",
    "B"
  ]
}[/verbatim];

    // 3. Run the transformation and print the result.
    wl(t.Transform(formattedJson))
End Using
```

**Output:**
```
{"id":123,"name":"Example, with spaces","tags":["A","B"]}
```

---

---

## Project: Building a Basic Calculator UI - ID: 972
/doc/tutorials/hands-on-starter-projects/project:-building-a-basic-calculator-ui/

**Description:** A step-by-step tutorial on creating a functional calculator application, using uCalc's expression parser to handle the evaluation logic.

**Remarks:**

# 💡 Project: Building a Basic Calculator UI

This project brings together the core concepts of the uCalc expression parser to build a familiar, practical application: a basic calculator. You'll see how to handle user input from a simple UI and let uCalc do all the heavy lifting of parsing and calculation with a single function call.

This tutorial is UI-framework-agnostic. Whether you're using WinForms, WPF, Qt, or a web framework, the core logic for interfacing with uCalc remains the same.

## Prerequisites

*   Familiarity with the [EvalStr](/Reference/Classes/uCalc/EvalStr/) method.
*   Basic knowledge of your chosen UI framework for creating buttons and a text display.

---

## 🖥️ Step 1: The User Interface

Every calculator needs a basic set of components:

1.  **A Display**: A read-only text box to show the current expression and the final result. Let's call it `display_text`.
2.  **Number Buttons**: Buttons for `0` through `9`.
3.  **Operator Buttons**: Buttons for `+`, `-`, `*`, `/`.
4.  **Action Buttons**:
    *   An **Equals** (`=`) button to trigger the calculation.
    *   A **Clear** (`C`) button to reset the display.

The layout would look something like a standard pocket calculator.

---

## 🧠 Step 2: The Core Logic - Handling Button Clicks

The logic behind the UI is surprisingly simple. We'll manage a single string variable that represents the content of the calculator's display. The example below will simulate this process.

### Number and Operator Buttons (`0-9`, `+`, `-`, `*`, `/`)
When a user clicks any of these buttons, the action is the same: **append the button's character to the `display_text` string.**

*   If the display shows `"123"`, pressing `+` changes it to `"123+"`.
*   If the display shows `"123+"`, pressing `4` changes it to `"123+4"`.

### The Clear Button (`C`)
When the 'C' button is clicked, simply **clear the `display_text` string** to an empty string (`""`).

---

## ✨ Step 3: The Magic - The Equals Button (`=`)

This is where uCalc shines. When the user presses the `=` button, all you need to do is:

1.  Get the complete expression string from your `display_text`.
2.  Pass this string directly to the [EvalStr](/Reference/Classes/uCalc/EvalStr/) method.
3.  Take the result from `EvalStr` and set it as the new content of `display_text`.

That's it! uCalc handles everything else:
*   It correctly parses the order of operations.
*   It performs the calculations.
*   If the user entered an invalid expression (like `"5 * + 3"`), `EvalStr` will return a descriptive error message (e.g., `"Syntax error"`), which you can display directly to the user.

### 💡 Why uCalc? (Comparative Analysis)

How would you do this *without* uCalc? You would need to build a complete parsing engine yourself. This typically involves complex algorithms like:

*   **Shunting-yard algorithm**: To convert the infix expression (`5 + 2`) into a postfix (Reverse Polish Notation) expression (`5 2 +`).
*   **Postfix Evaluation**: To evaluate the RPN expression using a stack.
*   **State Management**: To handle operator precedence, parentheses, and error states.

This can be hundreds of lines of complex, error-prone code. uCalc reduces this entire complex problem to a single line: `result = uc.EvalStr(expression)`.

---

## 🚀 Step 4: Putting It All Together

The following example simulates the complete logic of the calculator's "brain". It shows how a string is built up from simulated button presses and then evaluated by uCalc.

**Examples:**

### Example ID: 1365

**Description:** Simulates the core logic of a calculator, showing how user input is built into an expression string and evaluated.

**Code:**
```pseudocode
var(string, display_text) = "";

// Simulate user pressing buttons: 1, 2, 3, +, 4, 5, 6
display_text = display_text + "123";
wl("Display: ", display_text)

display_text = display_text + "+";
wl("Display: ", display_text)

display_text = display_text + "456";
wl("Display: ", display_text)

// Simulate pressing '='. This is where uCalc does the work.
var result = uc.EvalStr(display_text);
display_text = result;
wl("Result: ", display_text)

wl("")

// Simulate a new calculation with an error
display_text = "5 * / 3";
wl("Display: ", display_text)
result = uc.EvalStr(display_text);
display_text = result;
wl("Result: ", display_text)

wl("")

// Simulate clearing the display
display_text = "C"; // Let's say 'C' is a special command
if (display_text == "C")
    display_text = "";
end if
wl("Display after clear: '", display_text, "'");
```

**Output:**
```
Display: 123
Display: 123+
Display: 123+456
Result: 579

Display: 5 * / 3
Result: Syntax error

Display after clear: ''
```

---

---

## Project: Creating a Simple DSL for Financial Transactions - ID: 974
/doc/tutorials/hands-on-starter-projects/project:-creating-a-simple-dsl-for-financial-transactions/

**Description:** A step-by-step guide to building a simple, readable Domain-Specific Language (DSL) for processing financial transactions using the ExpressionTransformer.

**Remarks:**

# 📈 Project: Creating a Simple DSL for Financial Transactions

A Domain-Specific Language (DSL) is a mini-language tailored to a specific task. By creating a DSL, you can make complex operations more readable, maintainable, and accessible to non-programmers. This project will guide you through building a simple yet powerful DSL for processing a list of financial transactions using uCalc's [ExpressionTransformer](/Reference/uCalcBase/uCalc/ExpressionTransformer).

## The Goal: A Readable Transaction Script

Instead of writing complex C# or C++ code to process transactions, we want our application to understand a simple, human-readable script like this:

```
DEPOSIT 1000.00
WITHDRAW 50.75
INTEREST 0.5
WITHDRAW 200.00
```

This script is far more intuitive and can be easily created, modified, or stored in configuration files or a database.

## The Strategy: Transforming DSL into uCalc Expressions

The key to building our DSL is to teach the uCalc engine to understand our new keywords (`DEPOSIT`, `WITHDRAW`, `INTEREST`). We won't modify the core parser; instead, we'll use the [ExpressionTransformer](/Reference/uCalcBase/uCalc/ExpressionTransformer) to transform our DSL syntax into standard mathematical expressions *before* they are evaluated.

For example, the line `DEPOSIT 1000.00` will be automatically rewritten to `balance = balance + 1000.00`.

## Step 1: Setting Up the Environment

First, we need a variable within our uCalc instance to hold the account balance. We'll create it using [DefineVariable](/Reference/uCalcBase/uCalc/DefineVariable).

```pseudocode
// This variable will store the running total.
uc.DefineVariable("balance = 0.0");
```

## Step 2: Defining the DSL Syntax

Next, we'll get the [ExpressionTransformer](/Reference/uCalcBase/uCalc/ExpressionTransformer) and add rules for each of our keywords using [FromTo()](/Reference/uCalcBase/Transformer/FromTo). We use the [{@Number}](/Reference/Patterns/Matching-by-token-category/{@Number}) category matcher to capture the numeric amount for each transaction.

```pseudocode
// Get the transformer that pre-processes expressions.
var t = uc.@ExpressionTransformer();

// Rule for DEPOSIT
t.FromTo("DEPOSIT {@Number:amount}", "balance = balance + {amount}");

// Rule for WITHDRAW
t.FromTo("WITHDRAW {@Number:amount}", "balance = balance - {amount}");

// Rule for INTEREST (rate is a percentage)
t.FromTo("INTEREST {@Number:rate}", "balance = balance * (1 + {rate} / 100.0)");
```

## Step 3: Processing the Script

With our transformation rules in place, we can now pass the entire multi-line script to [EvalStr()](/Reference/uCalcBase/uCalc/EvalStr). Because newlines are treated as statement separators by default, uCalc will automatically pre-process and execute each line sequentially.

`EvalStr()` returns the result of the *last* statement executed. The other statements simply modify the `balance` variable as a side effect. To see the final result, we make a final call to evaluate the `balance` variable itself.

## Conclusion

You've successfully created a simple but functional DSL! This approach offers several advantages over hardcoding logic:

*   **Readability**: The transaction script is clean and self-documenting.
*   **Maintainability**: You can change the logic behind a keyword (e.g., add a transaction fee to `WITHDRAW`) by modifying a single rule, without touching your application's compiled code.
*   **Flexibility**: The script can be generated, stored, and loaded from anywhere, making your application highly configurable.

**Examples:**

### Example ID: 1330

**Description:** A "Hello World" example showing how to define a single DSL command and process a one-line script.

**Code:**
```pseudocode
// 1. Define the account balance variable
uc.DefineVariable("balance = 100.0");

// 2. Get the expression transformer and define a single rule
var t = uc.@ExpressionTransformer();
t.FromTo("DEPOSIT {@Number:amount}", "balance = balance + {amount}");

// 3. Process a single-line script.
// This gets transformed to "balance = balance + 500" and executed.
uc.EvalStr("DEPOSIT 500");

// 4. Print the final balance
wl("Final Balance: ", uc.EvalStr("balance"))
```

**Output:**
```
Final Balance: 600
```

---

### Example ID: 1331

**Description:** The complete financial DSL processing a multi-line script of deposits, withdrawals, and interest calculation.

**Code:**
```pseudocode
// 1. Initialize the account balance
uc.DefineVariable("balance = 0.0");

// 2. Define the DSL rules on the expression transformer
var t = uc.@ExpressionTransformer();
t.FromTo("DEPOSIT {@Number:amount}", "balance = balance + {amount}");
t.FromTo("WITHDRAW {@Number:amount}", "balance = balance - {amount}");
t.FromTo("INTEREST {@Number:rate}", "balance = balance * (1 + {rate} / 100.0)");

// 3. Define the multi-line transaction script
var script = [verbatim]
DEPOSIT 1000.00
WITHDRAW 50.75
INTEREST 0.5
WITHDRAW 200.00
[/verbatim];

wl("Initial Balance: ", uc.Eval("balance"))
wl("Processing script...")

// 4. Evaluate the entire script.
// Note: EvalStr returns the result of the LAST line.
// The intermediate lines modify the 'balance' variable.
uc.EvalStr(script);

// 5. Get the final balance
wl("Final Balance: ", uc.EvalStr("balance"))
```

**Output:**
```
Initial Balance: 0
Processing script...
Final Balance: 753.99625
```

---

### Example ID: 1332

**Description:** Internal Test: An advanced example that adds logging to each transaction to trace the balance changes, showing how DSLs can be combined with custom functions.

**Code:**
```pseudocode
[head]
[callback LogBalance]
  // Get the message and the current balance to log
  var msg = cb.ArgStr(1);
  var bal = cb.@uCalc().Eval("balance");
  wl("[LOG] ", msg, " | New Balance: ", bal)
[/callback]

[body]
// 1. Initialize the balance and the logger function
uc.DefineVariable("balance = 0");
uc.DefineFunction("LOG(msg As String)", LogBalance);

// 2. Define DSL rules that also call the LOG function
var t = uc.@ExpressionTransformer();

// Each rule now has a side effect: logging its action.
t.FromTo("DEPOSIT {@Number:amount}", 
         "balance = balance + {amount}; LOG('Deposited {amount}')");
t.FromTo("WITHDRAW {@Number:amount}", 
         "balance = balance - {amount}; LOG('Withdrew {amount}')");

// 3. A longer script to test the log
var script = [verbatim]
DEPOSIT 500
WITHDRAW 100
DEPOSIT 250
WITHDRAW 75
[/verbatim];

wl("--- Transaction Log ---")
uc.EvalStr(script);
wl("-----------------------")

wl("Final Balance: ", uc.Eval("balance"))
```

**Output:**
```
--- Transaction Log ---
[LOG] Deposited 500 | New Balance: 500
[LOG] Withdrew 100 | New Balance: 400
[LOG] Deposited 250 | New Balance: 650
[LOG] Withdrew 75 | New Balance: 575
-----------------------
Final Balance: 575
```

---

---

## Project: Creating a Basic Template Engine (like Liquid or Jinja) - ID: 985
/doc/tutorials/hands-on-starter-projects/project:-creating-a-basic-template-engine--like-liquid-or-jinja/

**Description:** A step-by-step project to build a simple but powerful template engine, similar to Liquid or Jinja, using uCalc's Transformer and callback system.

**Remarks:**

# 💡 Project: Creating a Basic Template Engine

This project will guide you through building a simple but powerful text template engine, similar to popular libraries like Shopify's Liquid or Python's Jinja. A template engine allows you to generate dynamic content by processing a template string with placeholders and logic, and filling it with data.

This is a perfect real-world showcase of how uCalc's [Transformer](/Reference/Classes/uCalc.Transformer/Introduction/) and expression parser work together to create a custom Domain-Specific Language (DSL).

### The Goal: Our Template Syntax

We want to create a system that can process a template like this:

```
Hello, {{ user_name }}!
{% if is_premium_user %}
Your premium access is active.
{% endif %}
Your items:
{% for item in items %}
- {{ item }}
{% endfor %}
```

Our engine will need to understand three constructs:
1.  **Variable Placeholders**: `{{ ... }}` to insert data.
2.  **Conditional Blocks**: `{% if ... %}` ... `{% endif %}` to show content based on a condition.
3.  **Loop Blocks**: `{% for ... %}` ... `{% endfor %}` to iterate over a collection.

--- 

## Step 1: Setting Up the Data Context

First, we need some data for our template to use. We'll define these as standard variables in our `uCalc` instance.

```pseudocode
// The data model for our template
uc.DefineVariable("user_name = 'Alice'");
uc.DefineVariable("is_premium_user = true");
uc.DefineVariable("items[] = {'Book', 'Pen', 'Paper'}");
```

---

## Step 2: Simple Variable Placeholders `{{ ... }}`

This is a simple find-and-replace task. We'll use a [Transformer](/Reference/Classes/uCalc.Transformer/Introduction/) rule to find any content inside `{{ }}` and evaluate it.

```pseudocode
// The {@@Eval} directive evaluates the captured 'expr' string.
t.FromTo("'{' '{' {expr} '}' '}'", "{@@Eval: expr}");
```

---

## Step 3: Conditional Logic `{% if ... %}`

For conditional blocks, we need to capture the condition and the body. We can then use the built-in [IIf()](/Reference/Functions-and-Operators/Functions/Specialized/) function within an `{@Eval}` block to conditionally include the body.

Crucially, we must set [RewindOnChange(true)](/Reference/Classes/uCalc.Rule/RewindOnChange/) on this rule. This tells the transformer to re-scan the output. Without it, any `{{...}}` placeholders *inside* the `if` block would not be processed.

```pseudocode
// The RewindOnChange is essential for processing nested placeholders.
t.FromTo("{% if {cond} %}{body}{% endif %}", "{@@Eval: IIf({cond}, '{body}', '')}").@RewindOnChange(true);
```

---

## Step 4: Loops `{% for ... %}` via a Callback

A simple replacement can't handle loops. This requires a callback function that integrates with the host application's logic. We'll define a custom function, `RenderLoop`, that the transformer can call.

Our transformer rule will convert the `{% for %}` syntax into a call to this function:
[pseudocode]`t.FromTo("{% for {var} in {collection} %}{body}{% endfor %}", "{@Eval: RenderLoop('{collection}', '{var}', '{body}')}").@RewindOnChange(true);`

The `RenderLoop` callback is the engine of our loop. It will:
1.  Get the collection array from the `uCalc` instance.
2.  Loop through each item in the collection.
3.  For each item, define a temporary variable with the loop variable's name (e.g., `item`).
4.  Process the template body for that single iteration using a temporary transformer.
5.  Append the result to a final output string.

This powerful pattern allows the flexible script engine to drive complex, high-performance logic in the host application.

--- 

## 💡 Why uCalc? (Comparative Analysis)

Dedicated template libraries like Scriban (.NET) or Jinja (Python) are powerful, but they come with a fixed, predefined syntax. You must use `{{...}}` or their specific keywords.

**The uCalc Advantage is Flexibility.** We just *invented* our own template language. With uCalc, the syntax is entirely under your control. You could just as easily define the syntax to be `<%= ... %>` or `$VarName$` by simply changing the patterns in your transformer rules. This makes uCalc an ideal tool for not just *using* a language, but for *building* one tailored to your exact needs.

**Examples:**

### Example ID: 1368

**Description:** Simple variable replacement in a template.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Define the data
uc.DefineVariable("user_name = 'Alice'");

// Define the placeholder rule
// '{' is a special character and must be escaped
t.FromTo("'{' '{' {expr} '}' '}'", "{@@Eval: expr}");

// Process the template
wl(t.Transform("Hello, {{ user_name }}!"))
```

**Output:**
```
Hello, Alice!
```

---

---

## Project: A Unit Conversion DSL - ID: 987
/doc/tutorials/hands-on-starter-projects/project:-a-unit-conversion-dsl/

**Description:** A step-by-step guide to building a simple, readable Domain-Specific Language (DSL) for unit conversions using the ExpressionTransformer.

**Remarks:**

# 📐 Project: Building a Unit Conversion DSL

This tutorial will guide you through building a simple but powerful Domain-Specific Language (DSL) for handling unit conversions. By leveraging uCalc's [ExpressionTransformer](/Reference/uCalcBase/uCalc/ExpressionTransformer), you can transform complex, hard-to-read formulas into an intuitive, human-readable syntax.

### The Goal: From Code to DSL

Instead of writing verbose code like `(value - 32) * 5 / 9` or calling functions like `ConvertFtoC(value)`, we want to enable a natural language syntax directly within our expressions:

*   `10 in to cm`
*   `98.6 F to C`
*   `100 km to miles`

This approach makes expressions more readable, maintainable, and easier for non-programmers to use.

---

## Step 1: The Basic Approach (Hardcoded Rules)

The quickest way to build our DSL is to define a specific rule for each conversion pair using the [ExpressionTransformer](/Reference/uCalcBase/uCalc/ExpressionTransformer). This pre-processes the expression string, rewriting our custom syntax into a standard mathematical formula before the main parser evaluates it.

```pseudocode
// Get the transformer that pre-processes all expressions.
var t = uc.@ExpressionTransformer();

// Rule for Inches to Centimeters
// The pattern `{@Number:val} in to cm` finds a number followed by the anchors "in to cm".
// The replacement uses {@Eval} to perform the calculation on the captured value.
// Note: Captured values are text, so we use Double() to convert 'val' to a number.
t.FromTo("{@Number:val} in to cm", "({@Eval: Double(val) * 2.54})");

// Rule for Fahrenheit to Celsius
t.FromTo("{@Number:val} F to C", "({@Eval: (Double(val) - 32) * 5 / 9})");

// Now we can use the new syntax directly in any expression.
wl("10 inches is ", uc.EvalStr("10 in to cm"), " cm.")
wl("98.6 Fahrenheit is ", uc.EvalStr("98.6 F to C"), " Celsius.")
```

While this works perfectly, it requires a separate rule for every single conversion (`cm to in`, `ft to m`, etc.), which can become difficult to maintain.

---

## Step 2: The Advanced Approach (A Generic System)

A more scalable and maintainable solution is to create a single, generic rule that can handle *any* unit conversion by looking up conversion factors stored in variables. This turns our transformer into a flexible conversion engine.

### A. Define Conversion Factors
First, we store our conversion factors as variables in the uCalc instance. We'll use a consistent naming convention, like `fromUnit_to_toUnit`.

```pseudocode
// Define one-way conversion factors.
uc.DefineVariable("in_to_cm = 2.54");
uc.DefineVariable("ft_to_m = 0.3048");
uc.DefineVariable("km_to_miles = 0.621371");
```

### B. Create a Generic Conversion Function
Next, we'll create a single callback function, `Convert`, that can handle any conversion. This function will dynamically construct the name of the factor variable (e.g., `"in_to_cm"`) and use it to perform the calculation. The logic will even be smart enough to handle inverse conversions (e.g., `cm to in`) automatically.

### C. Create a Generic Transformer Rule
Finally, we create one generic rule in the [ExpressionTransformer](/Reference/uCalcBase/uCalc/ExpressionTransformer) that captures the value and the two units, then calls our `Convert` function.

```pseudocode
var t = uc.@ExpressionTransformer();
t.FromTo("{@Number:val} {@Alpha:from} to {@Alpha:to}", "Convert({val}, '{from}', '{to}')");
```

The "Practical (Real World)" example below provides the complete implementation for this advanced approach, including the callback logic for the `Convert` function. This pattern is the key to building powerful, data-driven DSLs with uCalc.

**Examples:**

### Example ID: 1354

**Description:** A simple find-and-replace to convert inches to centimeters using a single ExpressionTransformer rule.

**Code:**
```pseudocode
// Get the transformer that pre-processes expressions.
var t = uc.@ExpressionTransformer();

// Define a rule to find "X in to cm" and replace it with the calculated value.
// Note: 'val' is captured as text and must be converted to a number with Double().
t.FromTo("{@Number:val} in to cm", "({@Eval: Double(val) * 2.54})");

// Use the new syntax directly in an expression.
wl(uc.EvalStr("10 in to cm"))
```

**Output:**
```
25.4
```

---

### Example ID: 1355

**Description:** A generic conversion system that uses a single transformer rule and a callback to dynamically look up conversion factors stored in variables.

**Code:**
```pseudocode
[head]
[callback ConvertUnits]
    var  value = cb.Arg(1);
    var fromUnit = cb.ArgStr(2);
    var toUnit = cb.ArgStr(3);
    
    // Construct the variable names for direct and inverse factors
    var factorName = fromUnit + "_to_" + toUnit;
    var inverseFactorName = toUnit + "_to_" + fromUnit;

    var uc_instance = cb.@uCalc();

    // Try to find the direct conversion factor
    var factorItem = uc_instance.ItemOf(factorName);
    if (factorItem.NotEmpty())
        [cpp]cb.Return(value * factorItem.Value());[/cpp][NotCpp]cb.Return(Math.Round(value * factorItem.Value(), 4));[/NotCpp]
        return;
    end if

    // If not found, try to find the inverse factor and use its reciprocal
    var inverseFactorItem = uc_instance.ItemOf(inverseFactorName);
    if (inverseFactorItem.NotEmpty())
        cb.Return(value / inverseFactorItem.Value());
        return;
    end if

    // If no factor is found, raise an error
    cb.@Error().Raise("Conversion factor not found for " + fromUnit + " to " + toUnit);
[/callback]
[body]
// Define the conversion factors as variables
uc.DefineVariable("in_to_cm = 2.54");
uc.DefineVariable("km_to_miles = 0.621371");

// Define a custom function for temperature, since it's not a simple multiplication
uc.DefineFunction("ConvertTempFToC(val) = (val - 32) * 5.0/9.0");

// Register our generic conversion callback
uc.DefineFunction("Convert(val, fromUnit As String, toUnit As String)", ConvertUnits);

// Create generic rules in the expression transformer
var t = uc.@ExpressionTransformer();
t.FromTo("{@Number:val} {@Alpha:from} to {@Alpha:to}", "Convert({val}, '{from}', '{to}')");
// A specific rule for Fahrenheit to Celsius since it's more complex (higher precedence because it's defined last)
t.FromTo("{@Number:val} F to C", "ConvertTempFToC({val})");

wl("10 in to cm = ", uc.Eval("10 in to cm"))
wl("100 km to miles = ", uc.Eval("100 km to miles"))

// Test the inverse conversion, which the callback handles automatically
wl("254 cm to in = ", uc.Eval("254 cm to in"))
wl("98.6 F to C = ", uc.Eval("98.6 F to C"))
```

**Output:**
```
10 in to cm = 25.4
100 km to miles = 62.1371
254 cm to in = 100
98.6 F to C = 37
```

---

---

## Project: An Interactive Command-Line Shell (REPL) - ID: 988
/doc/tutorials/hands-on-starter-projects/project:-an-interactive-command-line-shell--repl/

**Description:** A step-by-step tutorial for building a command-line calculator (REPL) that dynamically evaluates user input using the uCalc expression parser.

**Remarks:**

# 💻 Project: Building an Interactive Command-Line Shell (REPL)

This project demonstrates one of the most classic and powerful use cases for an expression parser: building a **Read-Eval-Print Loop (REPL)**. A REPL is an interactive, command-line environment that takes single user inputs, evaluates them, and returns the result. You've seen this in environments like the Python interactive shell or your web browser's developer console.

Our goal is to build a simple but fully functional command-line calculator that can process mathematical formulas, execute functions, and handle errors gracefully, all powered by a simple loop and a single uCalc method.

## Prerequisites

*   Familiarity with the [EvalStr](/Reference/uCalcBase/uCalc/EvalStr) method.

---

## ⚙️ The Core Logic: A 4-Step Loop

Every REPL follows the same fundamental cycle:

1.  **Read**: Get a line of input from the user.
2.  **Eval**: Evaluate the input string.
3.  **Print**: Display the result.
4.  **Loop**: Repeat the process.

Let's break down how we'll implement this with uCalc.

### Step 1: The "Read" Phase

This step involves prompting the user and reading a line of text from the console. In our example, we will simulate this by reading from a pre-defined array of strings to ensure the example is self-contained.

### Step 2: The "Eval" Phase - The Magic of `EvalStr`

This is where the uCalc engine does all the heavy lifting. The raw string provided by the user is passed directly to the [EvalStr](/Reference/uCalcBase/uCalc/EvalStr) method.

[pseudocode]`result = uc.EvalStr(userInput);`

This single method call is powerful enough for our entire REPL because:
*   It can parse and evaluate any valid expression, including arithmetic, function calls, and string operations.
*   It automatically handles any data type and returns the result as a string, ready for display.
*   Most importantly, it is **safe**. If the user enters an invalid expression (like `"1 +"`), it does not throw an exception but instead returns the error message as a string (e.g., `"Syntax error"`).

### Step 3: The "Print" Phase

This is the simplest step. We take the string returned by [EvalStr](/Reference/uCalcBase/uCalc/EvalStr)—whether it's a valid result or an error message—and print it directly to the console.

### Step 4: The Loop and Exit Condition

We wrap this logic in a `do...loop` that runs continuously. To make it a usable tool, we add a simple check for an exit command (like `"exit"` or `"quit"`) to break the loop and end the program.

---

## 💡 Why uCalc? (Comparative Analysis)

How would you build this REPL *without* uCalc? You would need to build a complete parsing and evaluation engine from scratch. This is a non-trivial computer science problem that typically involves:

1.  **Lexical Analysis (Tokenization)**: Writing code to split the input string `"5 * (10 + 2)"` into a stream of tokens: `5`, `*`, `(`, `10`, `+`, `2`, `)`.
2.  **Syntactic Analysis (Parsing)**: Implementing an algorithm like the **Shunting-yard algorithm** to convert the infix token stream into a postfix (Reverse Polish Notation) representation that respects operator precedence: `5`, `10`, `2`, `+`, `*`.
3.  **Evaluation**: Writing code to evaluate the postfix expression using a stack.
4.  **Error Handling**: Building robust error detection and reporting for every stage.

This would involve hundreds of lines of complex, error-prone code. uCalc encapsulates this entire pipeline into a single, highly-optimized, and safe method call: [EvalStr](/Reference/uCalcBase/uCalc/EvalStr).

--- 

Now let's see the complete implementation in action.

**Examples:**

### Example ID: 1357

**Description:** A complete, working command-line REPL that reads user input, evaluates it with uCalc, and prints the result or any error messages.

**Code:**
```pseudocode
// This example simulates a full REPL session by iterating through a series of inputs.
wl("uCalc Interactive Shell (simulated session)")
wl("Type 'exit' or 'quit' to end.")
wl("")

var(string[], inputs) = {
    "10 * (5 + 3)",
    "UCase('hello world')",
    "1 / 0",
    "1 +",
    "exit"
};

var index = 0;

do
  w("> ")
  
  // Simulate reading from the console by assigning inputs sequentially.
  // In a real application, this would read the input interactively from the console.
  var input = inputs[index];

  wl(input)

  // 1. Check for an exit command
  if (input == "exit" || input == "quit")
    wl("Exiting.")
    return [Cpp]0[/Cpp];
  end if

  // 2. Evaluate the input and 3. Print the result
  wl(uc.EvalStr(input))
  wl("")
  
  index = index + 1;
loop while (true)
```

**Output:**
```
uCalc Interactive Shell (simulated session)
Type 'exit' or 'quit' to end.

> 10 * (5 + 3)
80

> UCase('hello world')
HELLO WORLD

> 1 / 0
inf

> 1 +
Syntax error

> exit
Exiting.
```

---

---

## Project: Building a Data Sanitization and Validation Pipeline - ID: 992
/doc/tutorials/hands-on-starter-projects/project:-building-a-data-sanitization-and-validation-pipeline/

**Description:** A step-by-step guide to building a data processing pipeline that cleans, validates, and reformats semi-structured text using the uCalc Transformer.

**Remarks:**

# 🛡️ Project: Building a Data Sanitization and Validation Pipeline

This project demonstrates a common real-world task: taking messy, semi-structured data (like from a log file or user input) and transforming it into a clean, validated, and consistently formatted output. It's a perfect showcase of how to combine multiple [Transformer](/Reference/Classes/uCalc.Transformer/Introduction/) rules with custom validation logic using `{@Eval}` and native callbacks.

### The Goal: From Messy to Clean

We want to create a pipeline that can process a string of key-value pairs, where the formatting is inconsistent, and produce a clean, structured output. 

**Input:**
`user= Alice  ; age= 30 ; email= not-an-email ; status=active`

**Desired Output:**
`User: Alice, Age: 30, Email: not-an-email (INVALID), Status: ACTIVE`

This requires several steps: trimming whitespace, changing case, and validating the format of specific fields.

### 💡 Why uCalc? (vs. Manual String Splitting & Regex)

Manually parsing this with `string.Split()` would be brittle and fail with inconsistent spacing. Using multiple regular expressions would be complex and hard to maintain. uCalc's [Transformer](/Reference/Classes/uCalc.Transformer/Introduction/) provides a single, declarative engine to handle all these steps in a readable and robust way.

---

## Step 1: The Strategy

Our approach will be to define a separate [FromTo](/Reference/Classes/uCalc.Transformer/FromTo/) rule for each key (`user`, `age`, `email`, `status`). Each rule will:
1.  Match its key and capture the value.
2.  Use built-in functions like `UCase()` inside an `{@Eval}` block to sanitize the captured value.
3.  For the `email` field, we'll call a custom native callback function to perform validation.
4.  We'll enable [RewindOnChange](/Reference/Classes/uCalc.Rule/RewindOnChange/) to ensure all rules are applied sequentially to the input string.

---

## Step 2: The Validation Logic (Callback)

For complex validation that goes beyond simple expressions, we'll use a native callback. We'll create a function `IsValidEmail` that performs a basic check and returns `true` or `false`. This function will then be exposed to the uCalc engine.

---

## Step 3: The Transformation Rules

We will define four rules. The rule for `email` is the most interesting, as it combines sanitization (trimming) with a call to our custom validation function inside a conditional `IIf` expression.

```
t.FromTo("email = {val};",
         "Email: {val} {@Eval: IIf(IsValidEmail(val), '(Valid)', '(INVALID)')},");
```

Let's see the complete implementation in action.

**Examples:**

### Example ID: 1370

**Description:** Basic data cleaning by trimming whitespace and changing the case of a single key-value pair.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Rule to find 'status', capture its value, trim whitespace, and convert to uppercase.
t.FromTo("status = {val}", "Status: {@Eval: UCase(val)}");

var input = "status=  active  ";
wl(t.Transform(input))
```

**Output:**
```
Status: ACTIVE
```

---

### Example ID: 1371

**Description:** A complete data sanitization pipeline that processes multiple key-value pairs, using a native callback to perform custom email validation.

**Code:**
```pseudocode
[head]
[callback IsValidEmail]
    var email = cb.ArgStr(1);
    var uc = cb.@uCalc();
    // Simple validation: check for '@' and '.'
    var isValid = uc.EvalStr("Contains('" + email + "', '@') And Contains('" + email + "', '@')");
    if (isValid == "true")
        cb.ReturnBool(true);
    else
        cb.ReturnBool(false);
    end if
[/callback]

[body]
// 1. Define the custom validation function in the uCalc engine
uc.DefineFunction("IsValidEmail(email As String) As Bool", IsValidEmail);

// 2. Create and configure the transformer
NewUsing(uCalc::Transformer, t(uc))
    // 3. Define the sanitization and validation rules
    t.FromTo("user = {val};", "User: {val},");
    t.FromTo("age = {val};", "Age: {val},");
    t.FromTo("status = {val}", "Status: {@Eval: UCase(val)}"); // Last rule, no trailing comma
    
    // The email rule uses the custom function for validation
    t.FromTo("email = {val};", 
             "Email: {val} {@Eval: IIf(IsValidEmail(val), '(Valid)', '(INVALID)')},");

    // 4. Define the messy input strings
    var input1 = "user= Alice  ; age  =30 ; email= alice@ucalc.com ; status=active";
    var input2 = "user= Bob; age= 45; email= bob-at-ucalc ; status=inactive";

    // 5. Run the transformations
    wl(t.Transform(input1))
    wl(t.Transform(input2))
End Using;
```

**Output:**
```
User: Alice, Age: 30, Email: alice@ucalc.com (Valid), Status: ACTIVE
User: Bob, Age: 45, Email: bob-at-ucalc (INVALID), Status: INACTIVE
```

---

---

## Project: Transpiling Legacy Code to Modern - ID: 994
/doc/tutorials/hands-on-starter-projects/project:-transpiling-legacy-code-to-modern/

**Description:** A step-by-step project to build a simple transpiler that converts a legacy scripting syntax to a modern equivalent using the uCalc Transformer.

**Remarks:**

# 🚀 Project: Transpiling Legacy Code to Modern

A **transpiler** is a tool that reads source code written in one language and transforms it into equivalent code in another language. This project will guide you through building a simple transpiler that converts a legacy, BASIC-like syntax into a more modern, JavaScript-like format.

This is a perfect real-world demonstration of the uCalc [Transformer](/reference/classes/ucalc.transformer/introduction)'s power. Because it is **token-aware**, it can safely restructure code without the risks associated with character-based tools like regular expressions.

### The Goal: From Legacy BASIC to Modern Script

We'll create a transpiler that can process a script like this:

**Legacy Input:**
```
REM This is a comment
LET X = 10
LET Y = X * 2
IF Y > 15 THEN PRINT "Value is large"
```

And convert it into this modern equivalent:

**Modern Output:**
```javascript
// This is a comment
var x = 10;
var y = x * 2;
if (y > 15) {
  console.log("Value is large");
}
```

### 💡 Why uCalc Instead of Regex?

Attempting this with a series of `Regex.Replace` calls would be extremely fragile. A regex for `PRINT "..."` could accidentally match text inside another string or comment. A regex for `LET X = ...` would struggle with variable spacing and different expression types.

The uCalc [Transformer](/reference/classes/ucalc.transformer/introduction) avoids these pitfalls because it understands the code's structure. It knows the difference between the keyword `PRINT` and the word "PRINT" inside a string literal.

---

## Step 1: Setting Up the Transformer

First, we need a [Transformer](/reference/classes/ucalc.transformer/introduction) instance. We'll also configure its tokenizer to recognize our legacy comment style (`REM ...`).

```pseudocode
New(uCalc::Transformer, t)
// Treat newlines as significant separators
t.@DefaultRuleSet().@StatementSensitive(true);

// Define 'REM' comments as whitespace so they are ignored by other rules,
// but we'll also have a rule to convert them.
t.@Tokens().Add("REM.*", TokenType::Whitespace);
```

## Step 2: Defining the Transpilation Rules

We'll define a [FromTo](/reference/classes/ucalc.transformer/fromto) rule for each language construct we want to convert. The order is important: more specific rules should be defined last to give them higher precedence.

```pseudocode
// Rule for comments
t.FromTo("REM {comment}", "// {comment}");

// Rule for variable assignment
t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};");

// Rule for PRINT statements
t.FromTo("PRINT {output}", "console.log({output});");

// Rule for IF...THEN statements
t.FromTo("IF {condition} THEN {action}", "if ({condition}) {\n  {action}\n}");
```

Notice how we use token category matchers like `{@Alpha}` and variables like `{condition}` and `{action}` to capture the dynamic parts of the code.

## Step 3: Handling Nested Logic with `RewindOnChange`

Our `IF...THEN` rule has a problem: if the `{action}` is a `PRINT` statement, it won't be transformed! The `IF` rule runs, captures the literal text `PRINT "..."`, and finishes.

To solve this, we need to tell the transformer to re-scan the text after a replacement. This is done with the [RewindOnChange](/reference/classes/ucalc.rule/rewindonchange-=-[bool]) property.

```pseudocode
var ifRule = t.FromTo("IF {condition} THEN {action}", "if ({condition}) {\n  {action}\n}");
ifRule.@RewindOnChange(true);
```
Now, after the `IF` statement is transformed, the engine will rewind and re-scan its body, allowing the `PRINT` rule to match and transform the inner action.

---

## Step 4: Putting It All Together

The complete example below combines these rules to process a sample legacy script, correctly handling comments, variable assignments, and nested statements.

This project demonstrates how a few declarative rules can build a powerful and safe code transformation pipeline, a task that would be orders of magnitude more complex and error-prone with traditional tools.

**Examples:**

### Example ID: 1376

**Description:** Converting a single line of legacy variable declaration syntax to a modern equivalent.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
// Rule to convert legacy variable declaration
t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};");
wl(t.Transform("LET X = 100"))
End Using
```

**Output:**
```
var X = 100;
```

---

### Example ID: 1377

**Description:** A practical example that transpiles a multi-line legacy script, including comments, variables, and a conditional statement with a nested action.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Rules must be defined in an order that allows for proper transformation.

// 1. Comment rule
t.FromTo("REM {comment}", "// {comment}");

// 2. Variable assignment rule
t.FromTo("LET {@Alpha:var} = {val}", "var {var} = {val};");

// 3. Print statement rule
t.FromTo("PRINT {output}", "console.log({output});");

// 4. IF...THEN rule with RewindOnChange to handle nested statements
var ifRule = t.FromTo("IF {condition} THEN {action}", [verbatim]if ({condition}) {
  {action}
}[/verbatim]);
ifRule.@RewindOnChange(true);

// The legacy script to transpile
var legacyScript = [verbatim]REM Initialize variables
LET X = 10
LET Y = X * 2
IF Y > 15 THEN PRINT "Value is large"[/verbatim];

// Run the transformation
wl(t.Transform(legacyScript))
```

**Output:**
```
// Initialize variables
var X = 10;
var Y = X * 2;
if (Y > 15) {
  console.log("Value is large");
}
```

---

---

## Project: Creating a Spreadsheet Formula Evaluator - ID: 995
/doc/tutorials/hands-on-starter-projects/project:-creating-a-spreadsheet-formula-evaluator/

**Description:** A step-by-step project to build a reactive spreadsheet engine where changing one cell automatically updates all dependent cells.

**Remarks:**

# 📊 Project: Creating a Spreadsheet Formula Evaluator

This project demonstrates one of uCalc's most powerful features: building a reactive calculation engine, similar to a spreadsheet. You'll learn how to define cells with formulas that depend on other cells and see how uCalc automatically handles the complex task of recalculating dependencies when a value changes.

## The Goal: A Reactive Spreadsheet

Our goal is to simulate a simple spreadsheet where:
*   Cell `A1` contains the value `10`.
*   Cell `B1` contains the formula `A1 * 2`.
*   Cell `C1` contains the formula `A1 + B1`.

The critical requirement is that if we change the value of `A1`, the values of `B1` and `C1` must update **automatically**, without any manual intervention.

## The Challenge: Dependency Tracking

In a traditional programming environment, solving this problem is surprisingly complex. You would need to:
1.  **Parse Formulas**: Manually parse each formula (`A1 + B1`) to identify its dependencies (`A1`, `B1`).
2.  **Build a Dependency Graph**: Create a data structure (like a directed graph) that maps which cells depend on which others.
3.  **Implement a Recalculation Engine**: When a cell is changed, you must traverse this graph (using an algorithm like topological sort) to find all "dirty" cells and re-evaluate them in the correct order.

This is a non-trivial computer science problem.

## The uCalc Solution: The `Overwrite` Flag

uCalc abstracts away this entire complexity with a single, powerful feature: the `overwrite` flag in its definition methods. When you define a function with `overwrite: true`, uCalc automatically handles the dependency tracking and re-parsing for you.

---

## Step 1: Representing Cells as Functions

We can represent each cell in our spreadsheet as a uCalc function with no parameters (e.g., `A1()`, `B2()`). The body of the function will be the cell's content—either a literal value or a formula.

```pseudocode
// Cell A1 is a function named "A1" that returns 10.
uc.DefineFunction("A1() = 10", overwrite: true);
```

## Step 2: Defining the Initial Spreadsheet

Let's define our three cells. The key is to use the `overwrite: true` flag (or the `Overwrite ~~` command with the generic [Define](/Reference/Classes/uCalc/Define) method). This tells uCalc that these definitions can be replaced later and that it should track dependencies.

```pseudocode
// Define our three cells with the overwrite flag
uc.DefineFunction("A1() = 10", overwrite: true);
uc.DefineFunction("B1() = A1() * 2", overwrite: true);
uc.DefineFunction("C1() = A1() + B1()", overwrite: true);

// Let's check the initial values
wl("Initial B1: ", uc.Eval("B1()")); // Expected: 20
wl("Initial C1: ", uc.Eval("C1()")); // Expected: 30
```

## Step 3: The Magic - Overwriting a Cell

Now, let's change the value of `A1`. We simply redefine it using the same `overwrite` flag.

```pseudocode
// Overwrite the definition of A1
uc.DefineFunction("A1() = 50", overwrite: true);
```

Behind the scenes, uCalc detects that `A1` has changed. It then automatically finds all other functions (`B1` and `C1`) that depended on `A1` and re-parses their definitions. Their internal execution plans are updated to reflect the new logic.

Now, when we evaluate `B1` and `C1` again, they return the new, correct values without any further work from us.

```pseudocode
// Re-evaluate the dependent cells
wl("Updated B1: ", uc.Eval("B1()")); // Expected: 100
wl("Updated C1: ", uc.Eval("C1()")); // Expected: 150
```

---

## 💡 Why uCalc? (Comparative Analysis)

uCalc's `overwrite` feature is a specialized tool that provides a massive advantage for building reactive systems.

*   **vs. Manual Dependency Graph**: As described above, building a dependency graph manually is complex and error-prone. uCalc's engine has this logic built-in, saving hundreds of lines of code and significant development time.
*   **vs. Reactive Frameworks (e.g., Rx.NET)**: While powerful, reactive frameworks are a very different paradigm. They are designed for handling streams of events over time. uCalc's `overwrite` feature is specifically tailored for the static dependency graph problem found in spreadsheets and configuration systems, offering a much simpler and more direct solution for this specific use case.

By abstracting away the complexity of dependency management, uCalc allows you to focus on defining your logic, not on the mechanics of how it's updated.

**Examples:**

### Example ID: 1379

**Description:** Automatic recalculation when a source cell is changed.

**Code:**
```pseudocode
// Define cells A1 and B1, where B1 depends on A1
uc.Define("Overwrite ~~ Function: A1() = 10");
uc.Define("Overwrite ~~ Function: B1() = A1() * 5");

wl("Initial B1 value: ", uc.Eval("B1()")) // Expected: 50

// Now, change the value of A1. B1 will update automatically.
uc.Define("Overwrite ~~ Function: A1() = 20");

wl("Updated B1 value: ", uc.Eval("B1()")) // Expected: 100
```

**Output:**
```
Initial B1 value: 50
Updated B1 value: 100
```

---

### Example ID: 1380

**Description:** A practical example simulating a small spreadsheet with interdependent cells.

**Code:**
```pseudocode
// Define interdependent 'cells' using the Overwrite command.
uc.Define("Overwrite ~~ Function: A1() = 10");
uc.Define("Overwrite ~~ Function: B1() = A1() * 2");
uc.Define("Overwrite ~~ Function: C1() = A1() + B1()");

wl("Initial C1: ", uc.Eval("C1()")) // Should be 10 + (10 * 2) = 30

// Now, overwrite the source cell A1. All dependent cells should automatically update.
uc.Define("Overwrite ~~ Function: A1() = 50");

wl("Updated B1: ", uc.Eval("B1()")) // Should now be 50 * 2 = 100
wl("Updated C1: ", uc.Eval("C1()")) // Should now be 50 + 100 = 150
```

**Output:**
```
Initial C1: 30
Updated B1: 100
Updated C1: 150
```

---

### Example ID: 1381

**Description:** Internal Test: Verifies a multi-level dependency cascade where a change to a root cell propagates through several levels of dependent cells.

**Code:**
```pseudocode
// Internal Test: Verifying a multi-level dependency cascade.
uc.Define("Overwrite ~~ Function: BaseValue() = 2");
uc.Define("Overwrite ~~ Function: Level1() = BaseValue() * 10"); // 20
uc.Define("Overwrite ~~ Function: Level2() = Level1() + 5");    // 25
uc.Define("Overwrite ~~ Function: Level3() = Level2() * 2");    // 50

wl("Initial Level3 value: ", uc.Eval("Level3()"))

// Change the root value. All levels should recalculate.
uc.Define("Overwrite ~~ Function: BaseValue() = 3");

wl("--- After changing BaseValue to 3 ---")
wl("Updated Level1: ", uc.Eval("Level1()")) // 3 * 10 = 30
wl("Updated Level2: ", uc.Eval("Level2()")) // 30 + 5 = 35
wl("Updated Level3: ", uc.Eval("Level3()")) // 35 * 2 = 70
```

**Output:**
```
Initial Level3 value: 50
--- After changing BaseValue to 3 ---
Updated Level1: 30
Updated Level2: 35
Updated Level3: 70
```

---

---

## Project: Implementing a Custom Syntax Highlighter - ID: 997
/doc/tutorials/hands-on-starter-projects/project:-implementing-a-custom-syntax-highlighter/

**Description:** A step-by-step project on building a static analysis tool (linter) to enforce coding standards on a custom scripting language using the uCalc Transformer.

**Remarks:**

# 💡 Project: Implementing a Custom Syntax Highlighter

A syntax highlighter is a tool that analyzes source code and applies formatting (like colors and styles) to different parts of the syntax, such as keywords, strings, and comments. This project will guide you through building a simple but powerful syntax highlighter using the declarative rules of the [uCalc.Transformer](/reference/classes/ucalc.transformer/introduction/).

This is a classic real-world example of static analysis and demonstrates why the `Transformer`'s token-aware engine is far superior to traditional regular expressions for this task.

### The Goal

We will create a transformer that can scan a simple script and wrap different language elements in pseudo-HTML tags for styling:

*   **Keywords**: `if`, `else`, `for`, `while` → `<keyword>if</keyword>`
*   **Strings**: `"hello"` → `<string>"hello"</string>`
*   **Comments**: `// a comment` → `<comment>// a comment</comment>`

### ⚖️ Why uCalc Instead of Regex?

Attempting this with a series of `Regex.Replace` calls is extremely difficult and fragile. A regex for keywords would incorrectly match those words if they appeared inside a string literal or a comment. Handling these exceptions requires complex negative lookarounds that are hard to write and maintain.

`uCalc`'s key advantage is **token-awareness**. The tokenizer runs first and identifies strings and comments as single, atomic units. This means a rule to find the keyword `if` will not even look inside a string like `"An if statement"`, preventing incorrect matches by default.

--- 

## Step 1: The Strategy - Categorize and Tag

Our approach will be to define a separate [Pattern()](/reference/classes/ucalc.transformer/pattern/) rule for each syntax category we want to highlight. We will then use the [Tag](/reference/classes/ucalc.rule/tag-=-[int]/) property to assign a unique integer ID to each rule. This allows us to programmatically identify which category a match belongs to.

1.  **Define Categories**: Create integer constants for our syntax types (e.g., `TAG_KEYWORD = 1`, `TAG_STRING = 2`).
2.  **Define Rules**: Create a `Pattern()` for each category and assign the appropriate tag using `.SetTag()`. Rule precedence (LIFO) is important here: more specific rules (like keywords) should be defined after more general ones (like generic identifiers).
3.  **Process Matches**: After running `Find()`, we will iterate through the [Matches](/reference/classes/ucalc.matches/introduction/) collection. For each `Match`, we will get its originating `Rule` and check its `Tag` to determine how to format it.

## Step 2: The Implementation

The full example below puts all these pieces together. It defines the rules, processes a sample code snippet, and then iterates through the matches to build a final, highlighted HTML-like string. This demonstrates a complete, working syntax highlighting engine.


**Examples:**

### Example ID: 1384

**Description:** A complete syntax highlighter that finds keywords, strings, and comments, and wraps them in pseudo-HTML tags for styling.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
    // 1. Define integer constants for our syntax categories
    var TAG_KEYWORD = 1;
    var TAG_STRING = 2;
    var TAG_COMMENT = 3;

    // 2. Define the transformation rules and tag them
    t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD);
    t.Pattern("{@String}").SetTag(TAG_STRING);
    t.Pattern("// {text}").SetTag(TAG_COMMENT);

    // 3. Set the source code and run the find operation
    var(string, sourceCode) = [verbatim]for (i=0; i<10; i++) {
  s = "hello";
  // comment
}[/verbatim];
    t.@Text(sourceCode);
    t.Find();

    // 4. Build the highlighted output string
    var (string, highlightedOutput) = "";
    var lastPos = 0;

    foreach (var match in t.@Matches())
        // Append the plain text between the last match and this one
        highlightedOutput = highlightedOutput + sourceCode.[Cpp]substr[/Cpp][NotCpp]Substring[/NotCpp](lastPos, match.@StartPosition() - lastPos);

        // Get the tag and wrap the matched text accordingly
        var tag = match.@Rule().@Tag();
        if (tag == TAG_KEYWORD)
            highlightedOutput = highlightedOutput + "<keyword>" + match.@Text() + "</keyword>";
        else if (tag == TAG_STRING)
            highlightedOutput = highlightedOutput + "<string>" + match.@Text() + "</string>";
        else if (tag == TAG_COMMENT)
            highlightedOutput = highlightedOutput + "<comment>" + match.@Text() + "</comment>";
        else
            highlightedOutput = highlightedOutput + match.@Text(); // No tag, append as-is
        end if

        // Update the position for the next iteration
        lastPos = match.@EndPosition();
    end for

    // Append any remaining text after the last match
    highlightedOutput = highlightedOutput + sourceCode.[Cpp]substr[/Cpp][NotCpp]Substring[/NotCpp](lastPos);

    wl(highlightedOutput)
End Using
```

**Output:**
```
<keyword>for</keyword> (i=0; i<10; i++) {
  s = <string>"hello"</string>;
  <comment>// comment</comment>
}
```

---

---

## Project: Creating a DSL for Board Game Rules - ID: 998
/doc/tutorials/hands-on-starter-projects/project:-creating-a-dsl-for-board-game-rules/

**Description:** A step-by-step project to build a simple Domain-Specific Language (DSL) for board game rules using the uCalc Transformer.

**Remarks:**

# 🎲 Project: Building a DSL for Board Game Rules

This project will guide you through building a simple but powerful Domain-Specific Language (DSL) for processing board game actions. It's a perfect real-world example of how the declarative power of the [uCalc.Transformer](/reference/classes/ucalc.transformer/) can create a readable, maintainable, and easily modifiable rules engine.

### The Goal: A Readable Game Script

Instead of hardcoding complex `if/else` or `switch` statements in your application, we want to process a simple, human-readable script that represents a player's turn:

```
PLAYER 1 MOVES 5 SPACES
PLAYER 2 GAINS 10 GOLD
PLAYER 1 DRAWS 2 CARDS
```

This script is far more intuitive and can be easily modified for different game variants or expansions without recompiling the main application.

### The Strategy: Transforming DSL into uCalc Expressions

The key to building our DSL is to teach the uCalc engine to understand our new keywords (`MOVE`, `GAIN`, `DRAW`). We'll use the [ExpressionTransformer](/reference/classes/ucalc/expressiontransformer-=-[transformer]/) to transform our DSL syntax into standard mathematical expressions *before* they are evaluated.

For example, the line `PLAYER 1 MOVES 5 SPACES` will be automatically rewritten to `player1_position = player1_position + 5`.

---

## Step 1: Setting Up the Game State

First, we need variables within our uCalc instance to represent the game state. We'll create these using [DefineVariable()](/reference/classes/ucalc/definevariable/).

```pseudocode
// Player 1's state
uc.DefineVariable("player1_position = 0");
uc.DefineVariable("player1_gold = 20");
uc.DefineVariable("player1_cards = 5");

// Player 2's state
uc.DefineVariable("player2_position = 0");
uc.DefineVariable("player2_gold = 20");
uc.DefineVariable("player2_cards = 5");
```

---

## Step 2: Defining the DSL Rules

Next, we'll get the [ExpressionTransformer](/reference/classes/ucalc/expressiontransformer-=-[transformer]/) and add rules for each of our keywords using [FromTo()](/reference/classes/ucalc.transformer/fromto/). We use the `{@Number}` category matcher to capture the dynamic values for the player number and the action amount.

```pseudocode
// Get the transformer that pre-processes expressions.
var t = uc.@ExpressionTransformer();

// Rule for MOVE
t.FromTo("PLAYER {@Number:p} MOVES {@Number:n} SPACES", "player{p}_position = player{p}_position + {n}");

// Rule for GAIN
t.FromTo("PLAYER {@Number:p} GAINS {@Number:n} GOLD", "player{p}_gold = player{p}_gold + {n}");

// Rule for DRAW
t.FromTo("PLAYER {@Number:p} DRAWS {@Number:n} CARDS", "player{p}_cards = player{p}_cards + {n}");
```

---

## Step 3: Processing a Game Turn

With our transformation rules in place, we can now pass an entire multi-line script to [EvalStr()](/reference/classes/ucalc/evalstr/). Because newlines are treated as statement separators by default, uCalc will automatically pre-process and execute each line sequentially.

After the script runs, we can inspect the variables to see the final game state.

### ⚖️ Why uCalc? (Comparative Analysis)

*   **vs. Hardcoding Logic**: A hardcoded approach is rigid. If a rule changes (e.g., a special space doubles the gold gained), you must recompile the application. A DSL allows rules to be loaded from a text file, making the game easily modifiable for house rules or expansions.
*   **vs. Full Scripting Engine (Lua/Python)**: Embedding a full scripting engine is heavyweight and complex. uCalc provides a lightweight, sandboxed environment perfect for this kind of task-specific language. The [ExpressionTransformer](/reference/classes/ucalc/expressiontransformer-=-[transformer]/) is a simpler tool for this job than writing a full parser for the DSL from scratch.

**Examples:**

### Example ID: 1385

**Description:** A minimal example of a DSL command to move a player piece.

**Code:**
```pseudocode
uc.DefineVariable("player1_position = 0");

// Define a rule to translate the MOVE command
var t = uc.@ExpressionTransformer();
t.FromTo("PLAYER {@Number:p} MOVES {@Number:n} SPACES", "player{p}_position = player{p}_position + {n}");

// Execute a single command
uc.EvalStr("PLAYER 1 MOVES 5 SPACES");

wl("Player 1 is now at position: ", uc.EvalStr("player1_position"))
```

**Output:**
```
Player 1 is now at position: 5
```

---

### Example ID: 1386

**Description:** A complete game turn script demonstrating multiple DSL commands for moving, gaining resources, and drawing cards.

**Code:**
```pseudocode
// 1. Define the initial game state
uc.DefineVariable("p1_pos = 0");
uc.DefineVariable("p1_gold = 10");
uc.DefineVariable("p2_pos = 0");
uc.DefineVariable("p2_gold = 10");

// 2. Define the DSL rules
var t = uc.@ExpressionTransformer();
t.FromTo("PLAYER {@Number:p} MOVES {@Number:n}", "p{p}_pos = p{p}_pos + {n}");
t.FromTo("PLAYER {@Number:p} GAINS {@Number:n} GOLD", "p{p}_gold = p{p}_gold + {n}");

// 3. Define the script for the turn
var game_turn_script = [verbatim]
PLAYER 1 MOVES 4
PLAYER 2 MOVES 2
PLAYER 1 GAINS 5 GOLD
PLAYER 2 MOVES 3
[/verbatim];

// 4. Execute the script
uc.EvalStr(game_turn_script);

// 5. Display the final state
wl("--- End of Turn State ---")
wl("Player 1 Position: ", uc.EvalStr("p1_pos"))
wl("Player 1 Gold: ", uc.EvalStr("p1_gold"))
wl("Player 2 Position: ", uc.EvalStr("p2_pos"))
wl("Player 2 Gold: ", uc.EvalStr("p2_gold"))
```

**Output:**
```
--- End of Turn State ---
Player 1 Position: 4
Player 1 Gold: 15
Player 2 Position: 5
Player 2 Gold: 10
```

---

---

## Project: Extracting and Aggregating Metrics from Server Logs - ID: 999
/doc/tutorials/hands-on-starter-projects/project:-extracting-and-aggregating-metrics-from-server-logs/

**Description:** A step-by-step guide to building a server log parser that extracts and aggregates key performance metrics using the uCalc Transformer.

**Remarks:**

# 📊 Project: Extracting and Aggregating Metrics from Server Logs

This project will guide you through building a powerful and efficient server log parser. It's a classic real-world problem that perfectly showcases the advantages of uCalc's token-aware [Transformer](/Reference/uCalcBase/Transformer/Constructor) over traditional tools like Regular Expressions or manual string splitting.

### The Goal: From Raw Logs to Actionable Insights

Our objective is to take a raw, unstructured log file and transform it into a structured summary of key performance indicators (KPIs). We want to answer questions like:
*   How many total requests were processed?
*   What was the error rate?
*   What was the average response time?
*   What was the peak response time?

### The Input Data

Here is a sample of the `access.log` content we will be working with. It contains a mix of successful requests and errors, with inconsistent spacing.

```
2024-10-26 10:00:05 INFO    192.168.1.10   "GET /api/users HTTP/1.1" 200 15ms
2024-10-26 10:00:06 INFO    192.168.1.15   "GET /api/products HTTP/1.1" 200 22ms
This is a malformed line and should be ignored.
2024-10-26 10:00:07 ERROR   192.168.1.22   "POST /api/login HTTP/1.1" 500 120ms
2024-10-26 10:00:08 INFO    192.168.1.10   "GET /api/users/1 HTTP/1.1" 200 8ms
```

---

## The Strategy: A Single, Powerful Rule

We will use a single [Transformer](/Reference/uCalcBase/Transformer/Constructor) rule to process the entire log file. This rule will be designed to:

1.  **Match a Valid Log Line**: The pattern will capture all the relevant fields: timestamp, log level, IP address, request details, status code, and response time.
2.  **Aggregate Metrics with `{@Exec}`**: The replacement part of the rule will not produce any text. Instead, it will use a series of [`{@Exec}`](/Reference/Patterns/Pattern-Methods/{@Exec}) directives to update a set of counter variables for each line it processes. This is a highly efficient way to perform calculations as a side effect of a transformation.
3.  **Ignore Invalid Lines**: The pattern will be specific enough that it won't match malformed lines, which will be gracefully ignored.

---

## Step 1: Setting Up the Metric Variables

First, we need to define the variables in our `uCalc` instance that will store the aggregated metrics. We initialize them all to zero.

```pseudocode
uc.DefineVariable("request_count = 0");
uc.DefineVariable("error_count = 0");
uc.DefineVariable("total_response_time = 0.0");
uc.DefineVariable("max_response_time = 0.0");
```

## Step 2: Defining the Log Parsing Rule

Next, we create our [Transformer](/Reference/uCalcBase/Transformer/Constructor) and define the main rule. The pattern is designed to be robust against variable whitespace. The key is using `{@String:request}` to capture the entire HTTP request, including the spaces inside it, as a single token.

```pseudocode
New(uCalc::Transformer, t)

// The pattern captures all fields from a valid log line.
var pattern = "{@date} {@time} {@level} {@ip} {@String:request} {@Number:status} {@Number:time}ms";
```

## Step 3: The Aggregation Logic

The replacement string is where the magic happens. It contains no visible text, only a sequence of [`{@Exec}`](/Reference/Patterns/Pattern-Methods/{@Exec}) calls that update our metric variables for each match. Note that we must use `Double(time)` to convert the captured time string into a number for calculations.

```pseudocode
var replacement = ""
    + "{@Exec: request_count++}"
    + "{@Exec: total_response_time = total_response_time + Double(time)}"
    + "{@Exec: max_response_time = Max(max_response_time, Double(time))}"
    + "{@Exec: if(status >= 400, error_count++)}";

t.FromTo(pattern, replacement);
```

## Step 4: Running the Analysis and Displaying Results

Finally, we pass the entire multi-line log string to the `Transform` method. After it completes, our metric variables will hold the final aggregated values, which we can retrieve with `EvalStr`.

```pseudocode
// After running t.Transform(logText)...

wl("--- Log Analysis Summary ---");
wl("Total Requests: ", uc.EvalStr("request_count"));
wl("Total Errors: ", uc.EvalStr("error_count"));
wl("Average Response Time: ", uc.EvalStr("total_response_time / request_count"), "ms");
wl("Maximum Response Time: ", uc.EvalStr("max_response_time"), "ms");
```

## ⚖️ Why uCalc? (Comparative Analysis)

*   **vs. Regex**: Crafting a single, robust regex to capture all these fields while handling variable whitespace would be extremely complex and difficult to maintain. Furthermore, regex has no built-in mechanism for performing calculations during the match.
*   **vs. Manual `Split()`**: A simple `Split(' ')` would fail because of the spaces inside the quoted request string (e.g., `"GET /api/users HTTP/1.1"`). uCalc's tokenizer correctly identifies this as a single string token, making the pattern robust and simple.

**Examples:**

### Example ID: 1388

**Description:** Extracting the status code and response time from a single log line using a simple pattern.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
    var(string, logLine) = [verbatim]2024-10-26 10:00:05 INFO 192.168.1.10 "GET /api/users HTTP/1.1" 200 15ms[/verbatim];

    // Define a pattern to capture the status and time
    var(string, pattern) = "{@String:request} {@Number:status} {@Number:time}ms";

    // The replacement string formats the captured data for display
    // {request} or {request(1)} would return the string without surrounding quotes
    // {request(0)} returns the string with surrounding quotes
    var(string, replacement) = "Request: {request(0)}, Status: {status}, Time: {time}ms";

    t.FromTo(pattern, replacement);

    // Use Filter() to extract only the transformed match
    wl(t.Transform(logLine).@Matches())
End Using
```

**Output:**
```
Request: "GET /api/users HTTP/1.1", Status: 200, Time: 15ms
```

---

### Example ID: 1389

**Description:** A complete log processing pipeline that parses multiple lines and calculates aggregate metrics like total requests, error count, and average response time.

**Code:**
```pseudocode
// 1. Define variables to hold the metrics
uc.DefineVariable("request_count = 0");
uc.DefineVariable("error_count = 0");
uc.DefineVariable("total_response_time = 0.0");
uc.DefineVariable("max_response_time = 0.0");

// 2. Create the transformer and define the rule
NewUsing(uCalc::Transformer, t(uc))
    var pattern = "{@String:request} {@Number:status} {@Number:time}ms";

    // 3. The replacement string uses @Exec for side-effects (updating variables)
    var replacement = [verbatim]
{@Exec: request_count++}
{@Exec: total_response_time = total_response_time + Double(time)}
{@Exec: max_response_time = Max(max_response_time, Double(time))}
{@Exec: iif(Double(status) >= 400, error_count++, 0)}
[/verbatim];

    t.FromTo(pattern, replacement);

    // 4. Define the multi-line log data
    var logText = [verbatim]
2024-10-26 10:00:05 INFO    192.168.1.10   "GET /api/users HTTP/1.1" 200 15ms
2024-10-26 10:00:06 INFO    192.168.1.15   "GET /api/products HTTP/1.1" 200 22ms
2024-10-26 10:00:07 ERROR   192.168.1.22   "POST /api/login HTTP/1.1" 500 120ms
2024-10-26 10:00:08 INFO    192.168.1.10   "GET /api/users/1 HTTP/1.1" 200 8ms
[/verbatim];

    // 5. Run the transformation (the output will be empty as we only use @Exec)
    t.Transform(logText);
End Using

// 6. Display the final aggregated metrics
wl("--- Log Analysis Summary ---")
wl("Total Requests: ", uc.EvalStr("request_count"))
wl("Total Errors: ", uc.EvalStr("error_count"))
wl("Average Response Time: ", uc.EvalStr("total_response_time / request_count"), "ms")
wl("Maximum Response Time: ", uc.EvalStr("max_response_time"), "ms")
```

**Output:**
```
--- Log Analysis Summary ---
Total Requests: 4
Total Errors: 1
Average Response Time: 41.25ms
Maximum Response Time: 120ms
```

---

---

## Project: Parsing and Evaluating Complex Boolean Logic - ID: 1000
/doc/tutorials/hands-on-starter-projects/project:-parsing-and-evaluating-complex-boolean-logic/

**Description:** A step-by-step guide to building a rule engine that can parse and evaluate complex boolean logic using uCalc's built-in operators and custom DSLs.

**Remarks:**

# 🧠 Project: Parsing and Evaluating Complex Boolean Logic

This project demonstrates how to use uCalc to build a powerful engine for parsing and evaluating complex boolean logic expressions. This is a common requirement for applications like business rule engines, access control systems, search query parsers, and data validation frameworks.

### The Goal: A Dynamic Rule Engine

We want to evaluate logical statements provided as strings at runtime, using a context of variables. Our engine should correctly handle:
*   **Comparison Operators**: `==`, `>`, `<`, `>=`, `<=`, `<>`
*   **Logical Operators**: `AND`, `OR`, `NOT`
*   **Grouping**: Parentheses `()` to control the order of operations.

A typical expression might look like this:
`"(status == 'Active' AND login_attempts < 3) OR is_admin == true"`

### Why uCalc is the Perfect Tool

Building a boolean logic parser from scratch is a significant undertaking. You would need to implement a lexer, a parser that understands operator precedence (e.g., `AND` before `OR`), and an evaluation engine.

uCalc provides all of this functionality out of the box:
*   **Built-in Operators**: It already understands all standard comparison and logical operators.
*   **Precedence & Associativity**: The engine correctly handles the order of operations.
*   **Dynamic Context**: You can easily define variables at runtime to provide the data against which the rules are evaluated.
*   **Extensibility**: As shown in the practical example, you can use the [ExpressionTransformer](/reference/classes/ucalc/expressiontransformer-=-[transformer]/) to create a more natural, domain-specific language (DSL) on top of the core logic.

---

## Step 1: The Basic Approach (Using Built-in Logic)

The simplest way to evaluate a boolean expression is to define your variables and then pass the expression string directly to [EvalStr()](/reference/classes/ucalc/evalstr/). uCalc's default grammar will handle the rest.

The "Succinct" example below demonstrates this direct approach.

---

## Step 2: The Advanced Approach (Creating a Custom DSL)

For a more user-friendly or domain-specific syntax, you can use the [ExpressionTransformer](/reference/classes/ucalc/expressiontransformer-=-[transformer]/) to transpile custom keywords into standard uCalc expressions before they are evaluated.

Let's say we want to support a more natural language syntax:
*   `IS` instead of `==`
*   `IS NOT` instead of `<>`
*   `CONTAINS` for string searching

We can define simple `FromTo` rules to map this custom syntax to uCalc's built-in operators and functions. This creates a powerful abstraction layer, making the rules easier for non-programmers to write and understand.

The "Practical" example demonstrates this technique.

---

## Step 3: Providing the Data Context

In either approach, the boolean expression is evaluated against a set of variables. These variables represent the "facts" or the current state of the system. You define them using [DefineVariable()](/reference/classes/ucalc/definevariable/) before evaluating the expression.

```pseudocode
// Define the data context for our rule engine
uc.DefineVariable("status = 'Active'");
uc.DefineVariable("login_attempts = 2");
uc.DefineVariable("is_admin = false");
```

When the expression is evaluated, uCalc will look up these variable names and use their current values in the calculation.

Let's see the complete implementations.

**Examples:**

### Example ID: 1391

**Description:** Evaluates a complex boolean expression using uCalc's built-in operators.

**Code:**
```pseudocode
uc.DefineVariable("status = 'Active'");
uc.DefineVariable("login_attempts = 2");
uc.DefineVariable("is_admin = false");

var rule = "(status == 'Active' AND login_attempts < 3) OR is_admin == true";

wl("Evaluating rule: ", rule)
w("Result: ")
wl(uc.EvalStr(rule))
```

**Output:**
```
Evaluating rule: (status == 'Active' AND login_attempts < 3) OR is_admin == true
Result: true
```

---

---

## Project: Building a Custom Query String Parser - ID: 1003
/doc/tutorials/hands-on-starter-projects/project:-building-a-custom-query-string-parser/

**Description:** A step-by-step guide to building a robust parser for URL query strings using the uCalc Transformer.

**Remarks:**

# 💡 Project: Building a Custom Query String Parser

This project demonstrates how to build a robust parser for URL query strings using the uCalc [Transformer](/Reference/uCalcBase/Transformer/Constructor). You'll learn how to handle key-value pairs, separators, and even URL-encoded characters, creating a tool that is far more reliable than simple string splitting.

### The Goal: From Raw String to Structured Data

Our objective is to parse a standard URL query string and extract its key-value pairs into a clean, readable format.

**Input:**
`product=uCalc%20SDK&version=2.1&beta`

**Desired Output:**
```
- product: 'uCalc SDK'
- version: '2.1'
- Flag: 'beta'
```

### ⚖️ Why uCalc? (vs. Manual String Splitting)

A common approach to this problem is to split the string by `&` and then split each part by `=`. This is simple but brittle and fails on many real-world edge cases:
*   **URL-encoded values**: `name=John%20Doe` would be incorrectly parsed.
*   **Parameters without values**: A flag like `&beta` would break the `split('=')` logic.
*   **Empty values**: A key like `version=` would require special handling.

uCalc's token-aware, rule-based engine handles these cases gracefully, leading to a more robust and maintainable solution.

---

## The Strategy: A Multi-Rule Transformer

We will build our parser using a [Transformer](/Reference/uCalcBase/Transformer/Constructor) with a few key components:

1.  **Custom Tokenizer**: We'll teach the tokenizer to recognize `&` as a **statement separator**. This allows the transformer to process each key-value pair as a separate unit.
2.  **Pattern Rules**: We'll define patterns to match different types of parameters:
    *   A rule for standard `key=value` pairs.
    *   A rule for "flag" parameters that have no value.
3.  **Custom Function**: We'll create a native callback function, `URLDecode`, to handle URL-encoded characters like `%20`.
4.  **`{@Eval}` Integration**: Our replacement logic will use `{@Eval}` to call the `URLDecode` function on captured values, cleaning the data as it's extracted.

---

## Step-by-Step Implementation

The practical example below demonstrates the complete implementation, including the setup of the tokenizer, the definition of the rules, and the integration of a native callback for decoding.

**Examples:**

### Example ID: 1398

**Description:** Extracting a single key-value pair from a query string.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
   // Define a rule to find a key-value pair
   t.FromTo("{@Alphanumeric:key}={@Alphanumeric:val}", "Key: {key}, Value: {val}");

   // Process a simple query string
   wl(t.Transform("user=admin"))
End Using
```

**Output:**
```
Key: user, Value: admin
```

---

### Example ID: 1399

**Description:** A practical, real-world parser that handles multiple key-value pairs and URL-encoded characters using a custom callback.

**Code:**
```pseudocode
[head]
[callback URLDecode]
    // In a real application, this would be a full URL decoding implementation.
    // For this example, we'll just handle spaces (%20) and plus signs (+).
    var(uCalc::String, s) = cb.ArgStr(1);
    s.Replace("%20", " ").Replace("+", " ");
    cb.ReturnStr(s.@Text());
[/callback]

[body]
// 1. Define the custom URLDecode function in the uCalc engine
uc.DefineFunction("URLDecode(s As String) As String", URLDecode);

// 2. Create the transformer and configure its tokenizer
NewUsing(uCalc::Transformer, t(uc))
    // Treat '&' as a statement separator to process each pair individually
    t.@Tokens().Add("&", TokenType::StatementSep);

    // 3. Define the rule to capture key-value pairs and decode the value
    t.FromTo("{@Alphanumeric:key}={value}", "- {key}: '{@Eval: URLDecode(value)}'");

    // 4. Process a real-world query string
    var queryString = "name=John%20Doe&role=user+admin&id=123";
    
    // Use Filter() to get a clean, newline-separated list of the results
    wl(t.Transform(queryString).@Matches())
End Using
```

**Output:**
```
- name: 'John Doe'
- role: 'user admin'
- id: '123'
```

---

---

## Project: An Advanced Find-and-Replace Utility - ID: 1004
/doc/tutorials/hands-on-starter-projects/project:-an-advanced-find-and-replace-utility/

**Description:** A step-by-step project to build an advanced, token-aware find-and-replace utility for code refactoring using the uCalc Transformer.

**Remarks:**

# 💡 Project: An Advanced Find-and-Replace Utility

This project will guide you through building a powerful, command-line-style find-and-replace utility. Unlike basic text replacement, this tool will be **structurally aware**, making it safe for refactoring source code. It's a perfect real-world example of why the token-aware [uCalc.Transformer](/Reference/uCalcBase/Transformer/Constructor) is superior to Regular Expressions for manipulating structured text.

### The Goal

We'll create a tool that can intelligently rename a function or variable in a code snippet, correctly ignoring occurrences of the name inside comments and string literals.

### The Problem with Naive Find-and-Replace

A standard text editor's find-and-replace is character-based and 'blind' to context. If you try to rename the function `GetUserData` to `FetchUserProfile`, a naive tool would corrupt the code by changing the name inside comments and strings where it shouldn't.

**Input Code:**
```
// Deprecated: Use FetchUserProfile instead of GetUserData
function GetUserData(id) {
    print("Calling GetUserData is not recommended.");
    return http.get("/users/" + id);
}
var user = GetUserData(123);
```

**Incorrect Naive Result:**
```
// Deprecated: Use FetchUserProfile instead of FetchUserProfile
function FetchUserProfile(id) {
    print("Calling FetchUserProfile is not recommended.");
    return http.get("/users/" + id);
}
var user = FetchUserProfile(123);
```

This project will show you how to do it correctly with uCalc.

---

## Step 1: The Basic Replacement Rule

The core of our tool is a [Transformer](/Reference/uCalcBase/Transformer/Constructor) with a simple [FromTo](/Reference/uCalcBase/Transformer/FromTo) rule.

```pseudocode
New(uCalc::Transformer, t)
t.FromTo("GetUserData", "FetchUserProfile");
```

## Step 2: Handling "Whole Word" Matching (The Token Advantage)

How do we prevent renaming `GetUserData` from breaking a variable named `GetUserData_Fast`? With Regex, you'd need word boundaries (`\b`). With uCalc, this is **automatic**. The tokenizer identifies `GetUserData` and `GetUserData_Fast` as two distinct alphanumeric tokens. The rule for `GetUserData` will not match the other one.

## Step 3: Ignoring Comments with `SkipOver`

This is where uCalc's power becomes clear. To prevent the tool from changing text inside comments, we don't need complex lookarounds. We simply tell the transformer to treat comments as "dead zones" using [SkipOver](/Reference/uCalcBase/Transformer/SkipOver).

```pseudocode
// These rules run before any FromTo rules, protecting the content.
t.SkipOver("// {text}");
t.SkipOver("/* {text} */");
```

## Step 4: Ignoring Strings (Built-in Safety)

How do we protect the text inside `print("...")`? We don't have to do anything! By default, all rules are **QuoteSensitive**, meaning the tokenizer treats a quoted string as a single, atomic unit. The `FromTo` rule will not even look inside it.

## Putting It All Together

The practical example below combines these concepts into a complete, working refactoring tool. It correctly transforms the code, demonstrating the safety and power of a token-aware approach.

**Examples:**

### Example ID: 1401

**Description:** A basic, token-aware variable rename.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
   // This rule will only match the standalone token 'rate', not 'exchange_rate'.
   t.FromTo("rate", "interestRate");

   var code = "var exchange_rate = 0.5; var rate = 0.1;";
   wl(t.Transform(code))
End Using
```

**Output:**
```
var exchange_rate = 0.5; var interestRate = 0.1;
```

---

### Example ID: 1402

**Description:** A practical implementation of the code refactoring utility, safely renaming a function while ignoring occurrences in comments and strings.

**Code:**
```pseudocode
// Simulate user inputs for the tool
var findText = "GetUserData";
var replaceText = "FetchUserProfile";
var sourceCode = [verbatim]
// Deprecated: Use FetchUserProfile instead of GetUserData
function GetUserData(id) {
    print("Calling GetUserData is not recommended.");
    return http.get("/users/" + id);
}
var user = GetUserData(123);
[/verbatim];

NewUsing(uCalc::Transformer, refactorTool)
    // 1. Define rules to ignore comments. These have the highest precedence.
    refactorTool.SkipOver("// {text}");
    refactorTool.SkipOver("/* {text} */");

    // 2. Define the replacement rule. QuoteSensitive is true by default, protecting strings.
    var rule = refactorTool.FromTo(findText, replaceText);

    // 3. Run the transformation and print the result.
    wl(refactorTool.Transform(sourceCode))
End Using
```

**Output:**
```

// Deprecated: Use FetchUserProfile instead of GetUserData
function FetchUserProfile(id) {
    print("Calling GetUserData is not recommended.");
    return http.get("/users/" + id);
}
var user = FetchUserProfile(123);

```

---

---

## Project: Parsing LOGO Turtle Graphics Commands - ID: 1008
/doc/tutorials/hands-on-starter-projects/project:-parsing-logo-turtle-graphics-commands/

**Description:** A step-by-step tutorial on building a parser for the classic LOGO turtle graphics language, demonstrating how to create a Domain-Specific Language (DSL) with the ExpressionTransformer.

**Remarks:**

# 🐢 Project: Parsing LOGO Turtle Graphics Commands

This project is a fun, hands-on tutorial that demonstrates how to build a parser for a simple but classic programming language: LOGO. We'll create a Domain-Specific Language (DSL) that understands "turtle graphics" commands like `FD 100` (forward 100) and `RT 90` (right turn 90), and even handles loops with `REPEAT`.

This is a perfect real-world example of how uCalc's [ExpressionTransformer](/reference/classes/ucalc/expressiontransformer-=-[transformer]/) and expression parser work together to create a custom language interpreter from scratch.

### The Goal: Our LOGO DSL

We want our uCalc instance to understand a script like this, which draws a square:
```logo
PD       // Pen Down
REPEAT 4 [
  FD 100 // Forward 100 pixels
  RT 90  // Right turn 90 degrees
]
PU       // Pen Up
```

### The Strategy: Transforming LOGO into uCalc Expressions

The core idea is to use the [ExpressionTransformer](/reference/classes/ucalc/expressiontransformer-=-[transformer]/) to translate our LOGO commands into standard uCalc expressions *before* they are evaluated. For example, `RT 90` will be rewritten to `angle = angle - 90`. For movement, we'll create a native callback to handle the trigonometry, demonstrating how a DSL can be integrated with high-performance host application code.

---

### Step 1: The Turtle's State

First, we need to define the variables that will represent our turtle's state: its position (`x`, `y`), its heading (`angle`), and whether its pen is down (`pen_down`).

```pseudocode
// Initial state of our "turtle"
uc.DefineVariable("x = 0.0");
uc.DefineVariable("y = 0.0");
uc.DefineVariable("angle = 90.0"); // Start facing up (90 degrees)
uc.DefineVariable("pen_down = false");
uc.DefineConstant("PI = 3.1415926535");
```

We also define helper functions to work with degrees, as LOGO uses degrees while uCalc's trigonometric functions use radians.
```pseudocode
uc.DefineFunction("CosD(a) = Cos(a * PI / 180)");
uc.DefineFunction("SinD(a) = Sin(a * PI / 180)");
```

---

### Step 2: The Core Movement Logic (A Native Callback)

To keep our transformation rules clean, we'll encapsulate the complex movement logic in a single native callback function called `Move`. This function will calculate the new `x` and `y` coordinates and simulate drawing a line if the pen is down.

```pseudocode
[head]
[callback MoveTurtle]
  var dist = cb.Arg(1);
  var uc_inst = cb.@uCalc();

  // Get current state
  var x = uc_inst.ItemOf("x").Value();
  var y = uc_inst.ItemOf("y").Value();
  var angle = uc_inst.ItemOf("angle").Value();
  var pen_down = uc_inst.ItemOf("pen_down").ValueBool();

  // Calculate new position
  var new_x = x + dist * uc_inst.Eval("CosD(" + to_string(angle) + ")");
  var new_y = y + dist * uc_inst.Eval("SinD(" + to_string(angle) + ")");

  if (pen_down)
    wl("Drawing line from (", x, ",", y, ") to (", new_x, ",", new_y, ")");
  else
    wl("Moving from (", x, ",", y, ") to (", new_x, ",", new_y, ")");
  end if

  // Update state
  uc_inst.ItemOf("x").Value(new_x);
  uc_inst.ItemOf("y").Value(new_y);
[/callback]
[body]
// Define the uCalc function that bridges to our native code
uc.DefineFunction("Move(dist)", MoveTurtle);
```

---

### Step 3: Defining the DSL Rules

Now we define the transformation rules on the [ExpressionTransformer](/reference/classes/ucalc/expressiontransformer-=-[transformer]/). Each rule finds a LOGO command and replaces it with a standard uCalc expression.

```pseudocode
var t = uc.@ExpressionTransformer();

// Movement commands call our native callback
t.FromTo("FD {@Number:dist}", "Move({dist})");
t.FromTo("BK {@Number:dist}", "Move(-{dist})");

// Turning commands modify the angle variable
t.FromTo("RT {@Number:deg}", "angle = angle - {deg}");
t.FromTo("LT {@Number:deg}", "angle = angle + {deg}");

// Pen commands modify the boolean flag
t.FromTo("PU", "pen_down = false");
t.FromTo("PD", "pen_down = true");
```

---

### Step 4: Handling Loops with `REPEAT`

The `REPEAT` command is the most interesting. We'll transform it into a uCalc [ForLoop](/reference/functions-and-operators/functions/specialized) function. The key here is setting `RewindOnChange(true)`. This tells the transformer to re-scan the text inside the loop's body, ensuring that commands like `FD` and `RT` inside the `REPEAT` block are also transformed.

```pseudocode
// The body is captured as a literal string and passed to ForLoop
// RewindOnChange is crucial for processing the commands inside the body
t.FromTo("REPEAT {@Number:n} '[' {body} ']'").@RewindOnChange(true);
```

---

### Step 5: Putting It All Together

With our state, callback, and rules defined, we can now execute a LOGO script. The `EvalStr` method will automatically apply the [ExpressionTransformer](/reference/classes/ucalc/expressiontransformer-=-[transformer]/) rules before evaluating the resulting expressions.

---

### ⚖️ Why uCalc? (Comparative Analysis)

*   **vs. Manual Parsing**: Writing a parser for LOGO from scratch would require a tokenizer, a state machine to handle `REPEAT` blocks, and an interpreter. This would be hundreds of lines of complex code. uCalc reduces this to a handful of declarative rules.
*   **vs. Parser Generators (ANTLR)**: Tools like ANTLR are static. To add a new command like `CIRCLE`, you would need to modify a grammar file and recompile. With uCalc, you can add a new `FromTo` rule at runtime, making the language extensible.
*   **Integration**: The seamless integration of the [ExpressionTransformer](/reference/classes/ucalc/expressiontransformer-=-[transformer]/) (for the DSL syntax) and the Expression Parser (for the math and state changes) is the key. The ability to bridge to high-performance native code via callbacks provides the best of both worlds.

**Examples:**

### Example ID: 1409

**Description:** Basic forward and turn commands (LOGO).

**Code:**
```pseudocode
[head]
[callback MoveTurtle]
  var dist = cb.Arg(1);
  var uc_inst = cb.@uCalc();
  var x = uc_inst.ItemOf("x").Value();
  var y = uc_inst.ItemOf("y").Value();
  var angle = uc_inst.ItemOf("angle").Value();
  var pen_down = uc_inst.ItemOf("pen_down").ValueBool();
  var(int, new_x) = [NotCpp]Convert.ToInt32([/NotCpp]x + dist * uc_inst.Eval("CosD(" + to_string(angle) + ")")[NotCpp])[/NotCpp];
  var(int, new_y) = [NotCpp]Convert.ToInt32([/NotCpp]y + dist * uc_inst.Eval("SinD(" + to_string(angle) + ")")[NotCpp])[/NotCpp];
  if (pen_down)
    wl("Drawing line to (", new_x, ",", new_y, ")")
  else
    wl("Moving to (", new_x, ",", new_y, ")")
  end if
  uc_inst.ItemOf("x").Value(new_x);
  uc_inst.ItemOf("y").Value(new_y);
[/callback]

[body]
// --- Setup ---
uc.DefineVariable("x = 0.0");
uc.DefineVariable("y = 0.0");
uc.DefineVariable("angle = 90.0");
uc.DefineVariable("pen_down = false");
uc.DefineConstant("PI = 3.1415926535");
uc.DefineFunction("CosD(a) = Cos(a * PI / 180)");
uc.DefineFunction("SinD(a) = Sin(a * PI / 180)");
uc.DefineFunction("Move(dist)", MoveTurtle);

var t = uc.@ExpressionTransformer();
t.FromTo("FD {@Number:dist}", "Move({dist})");
t.FromTo("RT {@Number:deg}", "angle = angle - {deg}");
t.FromTo("PD", "pen_down = true");

// --- Script ---
var script = [verbatim]
PD
FD 100
RT 90
FD 50
[/verbatim];

uc.EvalStr(script);

wl("Final Position: (", uc.Eval("x"), ", ", uc.Eval("y"), ")")
```

**Output:**
```
Drawing line to (0,100)
Drawing line to (50,100)
Final Position: (50, 100)
```

---

---

## Project: Creating a Natural Language Date Parser - ID: 1010
/doc/tutorials/hands-on-starter-projects/project:-creating-a-natural-language-date-parser/

**Description:** A step-by-step project to build a simple parser that understands natural language date expressions like 'tomorrow' or 'next Friday' using the uCalc Transformer.

**Remarks:**

# 🗓️ Project: Creating a Natural Language Date Parser

This project will guide you through building a simple but powerful parser that can understand natural language date expressions like "tomorrow," "next Friday," or "in 3 weeks." It's a perfect real-world example of how the declarative power of the [uCalc.Transformer](/Reference/uCalcBase/Transformer/Constructor) and the logic of the **Expression Parser** work together to solve complex problems elegantly.

### The Goal: A Human-Friendly Date Syntax

Instead of forcing users to pick from a calendar or enter a rigid `MM/DD/YYYY` format, we want our application to understand simple, human-readable phrases. Our target DSL (Domain-Specific Language) will include:
*   `today`
*   `tomorrow`
*   `next Monday`, `next Tuesday`, etc.
*   `in 3 days`, `in 2 weeks`, `in 4 months`

### The Strategy: Transforming Phrases into Function Calls

The core idea is to use the [Transformer](/Reference/uCalcBase/Transformer/Constructor) to find these natural language phrases and rewrite them into calls to custom date-math functions that the uCalc engine can evaluate. For example:
*   The string `"tomorrow"` will be transformed into an expression like `"AddDays(Now(), 1)"`.
*   The string `"in 3 weeks"` will be transformed into `"AddDuration(Now(), 3, 'weeks')"`.

This requires two main components: a set of helper functions for date arithmetic and a set of transformer rules to perform the translation.

---

## Step 1: The Helper Functions (The Brains)

First, we need to give our uCalc engine the ability to perform date calculations. We'll do this by defining a few custom functions that are implemented by native callbacks. In a real application, these would use your language's native date/time library.

*   **`GetCurrentDate()`**: A function that returns the current date.
*   **`AddDuration(date, number, unit)`**: A function that takes a date, a number, and a unit string (e.g., "days", "weeks", "months") and returns a new date.
*   **`GetNextDayOfWeek(dayName)`**: A function that calculates the date of the next occurrence of a specific day of the week.
*   **`FormatDate(date, format)`**: A utility to format the final date object into a readable string.

## Step 2: The Transformation Rules (The Translator)

Next, we'll create a [Transformer](/Reference/uCalcBase/Transformer/Constructor) and define a [FromTo](/Reference/uCalcBase/Transformer/FromTo) rule for each phrase in our DSL. These rules will use the `{@Eval}` directive to call our helper functions.

```pseudocode
// Rule for simple keywords
t.FromTo("today", "{@Eval: FormatDate(GetCurrentDate())}");
t.FromTo("tomorrow", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), 1, 'day'))}");

// Rule for 'next {day}'
t.FromTo("next {@Alpha:day}", "{@Eval: FormatDate(GetNextDayOfWeek('{day}'))}");

// Rule for 'in {num} {unit}'
t.FromTo("in {@Number:num} {@Alpha:unit}", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), {num}, '{unit}'))}");
```

## Step 3: Putting It All Together

With our helper functions and transformer rules in place, we can now process any string. The `Transform()` method will find the natural language phrases, replace them with the evaluated results from our date functions, and return the final, formatted string.

The complete implementation is shown in the example below.

## ⚖️ Why uCalc? (Comparative Analysis)

*   **vs. Regular Expressions**: Building a regex to handle all these date variations would be extremely complex and brittle. A pattern to calculate "next Friday" would be nearly impossible. uCalc's token-aware patterns and embedded logic provide a far more robust and readable solution.

*   **vs. Specialized Date Libraries (e.g., Chrono.js, dateparser)**: While powerful, these libraries are often large dependencies focused on a single task. uCalc allows you to build a lightweight, *custom* parser for just the phrases you need. More importantly, it's fully integrated with the rest of the uCalc engine, allowing your date logic to be part of a larger expression evaluation or transformation pipeline.

**Examples:**

### Example ID: 1415

**Description:** A complete, working natural language date parser that handles keywords, relative days, and future durations.

**Code:**
```pseudocode
[head]
[callback GetCurrentDate]
    // In a real application, this would return the system's current date.
    // For this example, we'll use a fixed date for consistent output.
    // Let's pretend today is January 15, 2026 (a Thursday).
    cb.Return(46036); // Using Excel-style date serial number for simplicity
[/callback]

[callback AddDuration]
    var startDate = cb.Arg(1);
    var number = cb.Arg(2);
    var unit = cb.ArgStr(3);
    var result = startDate;

    if (unit == "day" || unit == "days")
        result = startDate + number;
    else if (unit == "week" || unit == "weeks")
        result = startDate + (number * 7);
    else if (unit == "month" || unit == "months")
        result = startDate + (number * 30); // Approximation for example
    end if
    cb.Return(result);
[/callback]

[callback GetNextDayOfWeek]
    var dayName = cb.ArgStr(1);
    var today = 46036; // Thursday, Jan 15, 2026
    var todayDayOfWeek = 5; // 1=Sun, 2=Mon, ..., 5=Thu

    var targetDay = 0;
    if (dayName == "Sunday") targetDay = 1;
    if (dayName == "Monday") targetDay = 2;
    if (dayName == "Tuesday") targetDay = 3;
    if (dayName == "Wednesday") targetDay = 4;
    if (dayName == "Thursday") targetDay = 5;
    if (dayName == "Friday") targetDay = 6;
    if (dayName == "Saturday") targetDay = 7;

    var daysToAdd = (targetDay - todayDayOfWeek + 7) [c]%[/c][vb]Mod[/vb] 7;
    // Always get the *next* week's day
    if (daysToAdd == 0) daysToAdd = 7;

    cb.Return(today + daysToAdd);
[/callback]

[callback FormatDate]
    // This is a simplified formatter for the example.
    // A real implementation would be more robust.
    var dateSerial = cb.Arg(1);
    if (dateSerial == 46036) cb.ReturnStr("2026-01-15");
    if (dateSerial == 46037) cb.ReturnStr("2026-01-16");
    if (dateSerial == 46039) cb.ReturnStr("2026-01-18");
    if (dateSerial == 46043) cb.ReturnStr("2026-01-22");
    if (dateSerial == 46050) cb.ReturnStr("2026-01-29");
    if (dateSerial == 46096) cb.ReturnStr("2026-03-16");
[/callback]

[body]
// 1. Define the helper functions in the uCalc engine
uc.DefineFunction("GetCurrentDate()", GetCurrentDate);
uc.DefineFunction("AddDuration(date, num, unit As String)", AddDuration);
uc.DefineFunction("GetNextDayOfWeek(dayName As String)", GetNextDayOfWeek);
uc.DefineFunction("FormatDate(date) As String", FormatDate);

// 2. Create the transformer and define the DSL rules
NewUsing(uCalc::Transformer, t(uc))
    // Set case-insensitivity for all rules
    t.@DefaultRuleSet().@CaseSensitive(false);

    // Define the rules
    t.FromTo("today", "{@Eval: FormatDate(GetCurrentDate())}");
    t.FromTo("tomorrow", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), 1, 'day'))}");
    t.FromTo("next {@Alpha:day}", "{@Eval: FormatDate(GetNextDayOfWeek(day))}");
    t.FromTo("in {@Number:num} {@Alpha:unit}", "{@Eval: FormatDate(AddDuration(GetCurrentDate(), Double(num), unit))}");

    // 3. Process the input strings
    wl("Input: 'today' -> Output: ", t.Transform("today"))
    wl("Input: 'tomorrow' -> Output: ", t.Transform("tomorrow"))
    wl("Input: 'next Sunday' -> Output: ", t.Transform("next Sunday"))
    wl("Input: 'in 2 weeks' -> Output: ", t.Transform("in 2 weeks"))
    wl("Input: 'in 60 days' -> Output: ", t.Transform("in 60 days"))
End Using
```

**Output:**
```
Input: 'today' -> Output: 2026-01-15
Input: 'tomorrow' -> Output: 2026-01-16
Input: 'next Sunday' -> Output: 2026-01-18
Input: 'in 2 weeks' -> Output: 2026-01-29
Input: 'in 60 days' -> Output: 2026-03-16
```

---

---

## Project: Developing a Simple LISP Interpreter - ID: 1011
/doc/tutorials/hands-on-starter-projects/project:-developing-a-simple-lisp-interpreter/

**Description:** A step-by-step tutorial on building a simple LISP interpreter using uCalc's ExpressionTransformer.

**Remarks:**

# 💡 Project: Building a Simple LISP Interpreter

This project is a masterclass in uCalc's dynamic syntax capabilities. We will build a simple, functional interpreter for a LISP-like language. LISP (LISt Processing) is famous for its distinctive parenthesized prefix notation, also known as S-expressions (Symbolic Expressions).

This project showcases how uCalc's [Transformer](/reference/classes/ucalc.transformer/introduction/) can transpile one language's syntax into another on the fly using a set of declarative, recursive rules.

### The Goal: Our LISP Syntax

We want our uCalc engine to understand expressions like this:

*   `(+ 1 2)`
*   `(- 10 5)`
*   `(* 2 3 4)` (variadic)
*   `(/ 100 5 2)` (variadic)
*   `(+ 1 (* 2 3))` (nested)

These will be transformed into standard uCalc expressions (`1 + 2`, `10 - 5`, etc.) and evaluated.

---

## The Strategy: A Declarative, Multi-Rule Approach

A simple find-and-replace rule isn't enough because we need to handle nested and variadic expressions. The solution is to create a set of transformation rules that work together to recursively simplify the LISP expression from the inside out until only a single value remains.

This requires three key uCalc features:
1.  **`RewindOnChange(true)`**: After a rule makes a replacement, the transformer re-scans the text, allowing other rules (or the same rule) to be applied to the result. This is the engine for our recursion.
2.  **`{@@Eval}`**: This directive evaluates a captured string as an expression. We'll use it to perform the arithmetic for each sub-expression.
3.  **Immediate Transform (`%`)**: This variable modifier forces the transformer to evaluate nested patterns first, which is essential for our inside-out evaluation strategy.

---

## Step 1: The Base Case - Binary Operations

The simplest rule handles a binary operation. It finds an operator followed by two operands, evaluates them, and replaces the entire S-expression with the result.

[pseudocode]`t.FromTo("({op:1} {a:1} {b:1})", "{@@Eval: a + op + b}");`

This rule transforms `(+ 10 20)` into the result `30`.

## Step 2: The Recursive Step - Variadic Operations

To handle more than two operands, we define a rule that reduces the list one step at a time. It finds an operator and at least three operands, evaluates the first two, and puts the result back at the front of the list.

[pseudocode]`t.FromTo("({op:1} {a:1} {b:1} {more})", "({op} {@@Eval: a + op + b} {more})");`

With `RewindOnChange(true)`, this rule will be applied repeatedly:
1.  `(* 2 3 4)` becomes `(* 6 4)`
2.  The transformer rewinds and finds `(* 6 4)`, which is then evaluated by the base case rule to `24`.

## Step 3: Inside-Out Evaluation - Nested Expressions

To handle nested expressions like `(/ 100 (+ 5 5))`, we need to evaluate the inner part first. The immediate transform modifier (`%`) on a variable forces this behavior.

[pseudocode]`t.FromTo("({op:1} {a:1} {expr%: ({exp})})", "({op} {a} {expr}");`

This rule looks for an expression where the second operand is itself a parenthesized expression. The `%` on `{expr%}` tells the transformer: "Stop and fully evaluate the inner expression `({exp})` first, then substitute its result back here." `RewindOnChange` then allows the simplified outer expression to be re-evaluated.

## Step 4: Putting It All Together

When an expression like `(+ 1 (* 2 3))` is processed:

1.  **Pass 1**: The nesting rule matches. The `%` modifier forces the inner part `(* 2 3)` to be evaluated first. The base case rule transforms `(* 2 3)` into `6`.
2.  The expression becomes `(+ 1 6)`.
3.  **Rewind**: The transformer re-scans the new string `(+ 1 6)`.
4.  **Pass 2**: The base case rule `({op:1} {a:1} {b:1})` matches `(+ 1 6)` and evaluates it to `7`.

## ⚖️ Why uCalc? (Comparative Analysis)

Building a LISP interpreter from scratch is a classic computer science exercise that involves:
1.  **Lexical Analysis**: Writing a tokenizer to handle parentheses, symbols, and numbers.
2.  **Syntactic Analysis**: Building a parser to construct an Abstract Syntax Tree (AST) from the token stream.
3.  **Evaluation**: Writing an evaluator that walks the AST to compute the result.

uCalc allows us to skip almost all of this work. We leverage:
*   uCalc's built-in, high-performance **tokenizer**.
*   uCalc's powerful **Transformer** to handle the syntactic analysis (parsing) declaratively.
*   uCalc's mature **evaluation engine** to handle the final computation.

We are simply building a lightweight "syntactic frontend" that translates one syntax into another that the engine already understands. This dramatically reduces the complexity and amount of code required.

**Examples:**

### Example ID: 1416

**Description:** A simple LISP transpiler that handles only binary operators.

**Code:**
```pseudocode
var t = uc.@ExpressionTransformer();
t.FromTo("({op:1} {a:1} {b:1})", "({a} {op} {b})");

wl("LISP: (+ 10 20)")
wl("uCalc: ", t.Transform("(+ 10 20)"))
wl("Result: ", uc.Eval("(+ 10 20)"))
```

**Output:**
```
LISP: (+ 10 20)
uCalc: (10 + 20)
Result: 30
```

---

### Example ID: 1417

**Description:** A practical LISP interpreter that handles variadic (multiple arguments) and nested expressions.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@DefaultRuleSet().@RewindOnChange(true);

// {@@Eval} evaluates the expression obtained by concatinating the captured
// elements {op} for operator, and {a} and {b} for the two numbers.
// These elements are strings and do not need curly braces within {@@Eval}
// :1 tels it to capture one token at a time.
t.FromTo("({op:1} {a:1} {b:1})", "{@@Eval: a + op + b}");

// If there are more than to numbers, as indicated by {more}, then the first
// two numbers are evaluated and put back into the list.  The operator remains.
t.FromTo("({op:1} {a:1} {b:1} {more})", "({op} {@@Eval: a + op + b} {more})");

// If a nested expression is present, it is evaluated immediately, by using
// % in {expr%} and the section is reprocessed again with the resulting value
// since .@RewindOnChange(true) was set.
t.FromTo("({op:1} {expr%: ({exp})}", "({op} {expr}");
t.FromTo("({op:1} {a:1} {expr%: ({exp})}", "({op} {a} {expr}");

// --- Test Cases ---
wl("--- Simple Binary ---")
var expr = "(- 100 25)";
wl("LISP: ", expr)
wl("Result: ", t.Transform(expr))
wl("")

wl("--- Variadic (Multiple Args) ---")
expr = "(* 2 3 4)";
wl("LISP: ", expr)
wl("Result: ", t.Transform(expr))
wl("")

wl("--- Nested Expressions ---")
expr = "(/ 100 (+ 5 5))";
wl("LISP: ", expr)
wl("Result: ", t.Transform(expr))
expr = "(+ (* (- 100 (/ 80 4)) 3) (- (* (+ 5 3) (- 12 7)) (+ (* 2 3) 4)))";
wl("LISP: ", expr)
wl("Result: ", t.Transform(expr))
wl("")
```

**Output:**
```
--- Simple Binary ---
LISP: (- 100 25)
Result: 75

--- Variadic (Multiple Args) ---
LISP: (* 2 3 4)
Result: 24

--- Nested Expressions ---
LISP: (/ 100 (+ 5 5))
Result: 10
LISP: (+ (* (- 100 (/ 80 4)) 3) (- (* (+ 5 3) (- 12 7)) (+ (* 2 3) 4)))
Result: 270
```

---

---

## Project: Implementing a BBCode to Markdown Converter - ID: 1019
/doc/tutorials/hands-on-starter-projects/project:-implementing-a-bbcode-to-markdown-converter/

**Description:** A step-by-step guide to building a simple BBCode to Markdown converter using the declarative rules of the uCalc Transformer.

**Remarks:**

# 💡 Project: Building a BBCode to Markdown Converter

This project will guide you through building a simple but functional converter for **BBCode**, a lightweight markup language commonly used in forums and message boards. We'll transform BBCode syntax into its more modern equivalent, **Markdown**, using the declarative power of the [uCalc.Transformer](/Reference/uCalcBase/Transformer/Constructor).

This is a perfect real-world example of a "transpiler"—a tool that converts source code from one language to another. It showcases how uCalc's token-aware patterns can handle structured text safely and readably.

### The Goal

We'll create a transformer that can convert common BBCode tags into Markdown:

| BBCode | Markdown |
| :--- | :--- |
| `[b]bold text[/b]` | `**bold text**` |
| `[i]italic text[/i]` | `*italic text*` |
| `[u]underline text[/u]` | `<u>underline text</u>` |
| `[url=http://example.com]link[/url]` | `[link](http://example.com)` |
| `[quote]quoted text[/quote]` | `> quoted text` |

*Note: Since Markdown has no standard syntax for underlining, we'll convert `[u]` tags to their HTML equivalent.*

### ⚖️ Why uCalc Instead of Regex?

While you could attempt this with a series of `Regex.Replace` calls, you would quickly run into problems, especially with **nested tags**. A simple regex for `[b]...[/b]` would greedily match from the first `[b]` to the *last* `[/b]` in a string like `[b]bold[/b] and [b]more bold[/b]`, breaking the structure.

uCalc's [Transformer](/Reference/uCalcBase/Transformer/Constructor) avoids this by being **token-aware**. It understands the structure of the tags and can handle nested content correctly and safely.

---

## Step 1: Setting Up the Transformer

First, we need a [Transformer](/Reference/uCalcBase/Transformer/Constructor) instance. Since BBCode content can span multiple lines, we must disable `StatementSensitive` on the [DefaultRuleSet](/Reference/uCalcBase/Transformer/DefaultRuleSet). This tells the transformer to treat newlines as simple whitespace, allowing variable captures like `{text}` to span multiple lines.

```pseudocode
New(uCalc::Transformer, t)
t.@DefaultRuleSet().@StatementSensitive(false);
```

## Step 2: Defining the Rules

Next, we'll define our conversion logic using [FromTo()](/Reference/uCalcBase/Transformer/FromTo) rules. The key is to use a pattern that captures the tag name and content, using [backreferences](/Reference/Patterns/Introduction/Variables-and-Anchors) to ensure the opening and closing tags match.

The pattern `[{tag}]{content}[/{tag}]` is perfect for this. The `{tag}` variable captures the tag name (like `b` or `i`), and the backreference `[/{tag}]` ensures it only matches the corresponding closing tag.

### Simple Inline Tags (Bold, Italic, Underline)
These rules are straightforward find-and-replace operations.

```pseudocode
// Rule for Bold text
t.FromTo("[b]{text}[/b]", "**{text}**");

// Rule for Italic text
t.FromTo("[i]{text}[/i]", "*{text}*");

// Rule for Underline (converts to HTML)
t.FromTo("[u]{text}[/u]", "<u>{text}</u>");
```

### The URL Tag (with an attribute)
This rule is slightly more complex as it needs to capture the URL from the tag's attribute.

```pseudocode
// Pattern captures the URL into {href} and the link text into {text}
t.FromTo("[url={href}]{text}[/url]", "[{text}]({href})");
```

### The Quote Tag (Block-level)
This rule converts the `[quote]` block into a Markdown blockquote.

```pseudocode
t.FromTo("[quote]{content}[/quote]", "> {content}");
```

## Step 3: Putting It All Together

The complete example below combines these rules to process a sample BBCode document. The transformer will correctly handle all the tags in a single, efficient pass.

**Examples:**

### Example ID: 1434

**Description:** A complete, single-pass transformer that converts common BBCode tags (bold, italic, underline, URL, and quote) to their Markdown equivalents.

**Code:**
```pseudocode
// 1. Setup the Transformer
NewUsing(uCalc::Transformer, t)
    // Allow patterns to match across multiple lines
    t.@DefaultRuleSet().@StatementSensitive(false);

    // 2. Define the conversion rules
    
    // Simple inline tags
    t.FromTo("'['b']'{text}'['/b']'", "**{text}**");
    t.FromTo("'['i']'{text}'['/i']'", "*{text}*");
    t.FromTo("'['u']'{text}'['/u']'", "<u>{text}</u>");

    // URL tag with attribute
    t.FromTo("'['url={href}']'{text}'['/url']'", "[{text}]({href})");

    // Quote block tag
    t.FromTo("'['quote']'{content}'['/quote']'", "> {content}");

    // 3. Define the input BBCode text
    var bbCode = [verbatim]
Hello, this is a test of the converter.

This text is [b]bold[/b] and this is [i]italic[/i].
You can also [u]underline[/u] text.

Here is a link to the uCalc website: [url=https://www.ucalc.com]uCalc[/url].

[quote]This is a block of quoted text.
It can span multiple lines.[/quote]
[/verbatim];

    // 4. Run the transformation and print the result
    wl(t.Transform(bbCode))
End Using
```

**Output:**
```
Hello, this is a test of the converter.

This text is **bold** and this is *italic*.
You can also <u>underline</u> text.

Here is a link to the uCalc website: [uCalc](https://www.ucalc.com).

> This is a block of quoted text.
It can span multiple lines.

```

---

---

## Project: Developing a Basic Web Server Route Matcher - ID: 1020
/doc/tutorials/hands-on-starter-projects/project:-developing-a-basic-web-server-route-matcher/

**Description:** A step-by-step guide to building a simple web server route matcher using the uCalc Transformer's declarative patterns.

**Remarks:**

# 💡 Project: Developing a Basic Web Server Route Matcher

A core task for any web server is **routing**: mapping an incoming URL path like `/users/123` to the correct application logic (a "handler") and extracting any dynamic parameters (like the user ID `123`). This project will guide you through building a simple but powerful route matcher using the declarative patterns of the uCalc [Transformer](/reference/classes/ucalc.transformer/introduction/).

### The Goal: A Simple Routing DSL

We'll create a Domain-Specific Language (DSL) for defining routes that is common in modern web frameworks like Express.js or Flask. Placeholders for dynamic segments are enclosed in curly braces.

*   `/users/{id}`
*   `/products/{category}/{id}`

### The Strategy: Transformer Rules

The core idea is to treat routing as a text transformation problem. We'll take an incoming URL path and transform it into a string that represents the action to take.

*   **Input**: `/users/42`
*   **Rule**: `FromTo("/users/{id}", "Handler: UserProfile, id: {id}")`
*   **Output**: `"Handler: UserProfile, id: 42"`

The application can then easily parse this output string to call the correct function with the extracted parameters.

--- 

## Step 1: Setting Up the Transformer

First, we need a [Transformer](/reference/classes/ucalc.transformer/introduction/) instance. This will be our router. We will define all our route patterns on this object.

```pseudocode
NewUsing(uCalc::Transformer, router)
    // ... rules will go here ...
End Using
```

## Step 2: Defining the Routes

Each route is a [FromTo](/reference/classes/ucalc.transformer/fromto/) rule. The pattern matches the URL structure, and the replacement string defines the output.

*   **Static Route**: A simple, fixed path.
    [pseudocode]`router.FromTo("/about", "Handler: AboutPage");`

*   **Dynamic Route**: A path with one or more variable placeholders.
    [pseudocode]`router.FromTo("/users/{id}", "Handler: UserProfile, id: {id}");`

## Step 3: Precedence Matters (LIFO)

What happens if you have two similar routes, like `/users/new` and `/users/{id}`? A request for `/users/new` could technically match both patterns. To resolve this, the [Transformer](/reference/classes/ucalc.transformer/introduction/) uses a **LIFO (Last-In, First-Out)** precedence rule: the **most recently defined rule is checked first**.

Therefore, you must define your most specific rules *last* to give them higher priority.

```pseudocode
// General rule defined first (lower priority)
router.FromTo("/users/{id}", "Handler: UserProfile, id: {id}");

// Specific rule defined last (higher priority)
router.FromTo("/users/new", "Handler: CreateUserPage");
```

## Step 4: Matching an Incoming URL

To process a request, simply call [Transform()](/reference/classes/ucalc.transformer/transform/) on the incoming URL string. If the result is different from the original URL, a match was found. If it's unchanged, it's a "404 Not Found."

## ⚖️ Why uCalc? (Comparative Analysis)

*   **vs. Regex**: Building a router with regular expressions is common but can be complex. Each route requires a carefully crafted regex, and managing their precedence can be tricky. uCalc's patterns are more readable (`/users/{id}` vs. `/users/(\w+)`), and the LIFO precedence is a clear, built-in system.
*   **vs. Manual String Splitting**: Splitting the URL by `/` is brittle and doesn't handle complex patterns or constraints well.

uCalc provides a declarative, token-aware, and extensible way to define a routing system that is both powerful and easy to maintain.

**Examples:**

### Example ID: 1435

**Description:** Defining one static and one dynamic route, then matching a URL against each.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, router)
    // Define routes
    router.FromTo("/home", "Handler: HomePage");
    router.FromTo("/users/{id}", "Handler: UserProfile, id: {id}");

    // Test routes
    wl("Matching '/home': ", router.Transform("/home"))
    wl("Matching '/users/42': ", router.Transform("/users/42"))
End Using
```

**Output:**
```
Matching '/home': Handler: HomePage
Matching '/users/42': Handler: UserProfile, id: 42
```

---

### Example ID: 1436

**Description:** A practical example of a router with multiple rules, demonstrating LIFO precedence and handling of a '404 Not Found' case.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, router)
    // --- Define Routes ---
    // General rules first (lower precedence)
    router.FromTo("/products/{category}/{id}", "Handler: ProductDetail, category: {category}, id: {id}");
    router.FromTo("/users/{id}", "Handler: UserProfile, id: {id}");
    
    // Specific rule last (higher precedence)
    router.FromTo("/users/new", "Handler: CreateUserPage");

    // --- Simulate Requests ---
    var(string[], urls) = {"/users/123", "/users/new", "/products/electronics/567", "/contact"};
    
    foreach(var url in urls)
        var originalUrl = url;
        var result = router.Transform(url);

        if (result.@Text() == originalUrl)
            wl("URL: ", originalUrl, " -> 404 Not Found")
        else
            wl("URL: ", originalUrl, " -> ", result)
        end if
    end foreach
End Using
```

**Output:**
```
URL: /users/123 -> Handler: UserProfile, id: 123
URL: /users/new -> Handler: CreateUserPage
URL: /products/electronics/567 -> Handler: ProductDetail, category: electronics, id: 567
URL: /contact -> 404 Not Found
```

---

---

## Project: Implementing a Strict Configuration File Validator - ID: 1026
/doc/tutorials/hands-on-starter-projects/project:-implementing-a-strict-configuration-file-validator/

**Description:** A step-by-step project to build a static analysis tool (validator) for a custom INI-style configuration file using the uCalc Transformer.

**Remarks:**

# 🛡️ Project: Implementing a Strict Configuration File Validator

This project will guide you through building a simple but powerful linter/validator for a custom INI-style configuration file. It's a perfect real-world example of how the declarative power of the [uCalc.Transformer](/Reference/uCalcBase/Transformer/Constructor) can solve complex validation problems more safely and readably than manual string parsing or traditional Regular Expressions.

### The Goal

We'll create a validator that scans a configuration file and reports whether it adheres to a strict set of structural rules.

### The Configuration File Format

Our linter will analyze a simple INI-style format with sections (e.g., `[Server]`), key-value pairs (`Host = db1`), and comments (lines starting with `;`).

**Example `config.ini`:**
```ini
; Main server settings
[Server]
Host = main_server
Port = 8080
```

### The Validation Rules
Our validator must enforce the following rules:
1.  The file **must** contain exactly one `[Server]` section.
2.  The `[Server]` section **must** contain exactly one `Host` key.
3.  The `[Server]` section **must** contain at least one `Port` key.
4.  Lines starting with `;` are comments and should be ignored.

---

## The Strategy: Declarative Validation

Instead of writing complex, imperative code to loop through lines and maintain state, we will use the [Transformer](/Reference/uCalcBase/Transformer/Constructor) to define our rules declaratively.

*   **Hierarchical Parsing**: We'll use a parent [Rule](/Reference/uCalcBase/Rule/Constructor) to find the `[Server]` section and a [LocalTransformer](/Reference/uCalcBase/Rule/LocalTransformer) to validate the keys *only within* that section.
*   **Occurrence Constraints**: We'll use the [Minimum](/Reference/uCalcBase/Rule/Minimum) and [Maximum](/Reference/uCalcBase/Rule/Maximum) properties on our rules to enforce the "exactly one" and "at least one" constraints.
*   **Ignoring Comments**: A simple [SkipOver](/Reference/uCalcBase/Transformer/SkipOver) rule will make comments invisible to our validation logic.

---

## Step-by-Step Implementation

### Step 1: Configure the Transformer
First, we create a [Transformer](/Reference/uCalcBase/Transformer/Constructor) instance. Since INI files are multi-line, we must disable `StatementSensitive` to allow patterns to match across newlines. We also add a rule to ignore comments.

```pseudocode
NewUsing(uCalc::Transformer, validator)
    validator.@DefaultRuleSet().@StatementSensitive(false);
    validator.SkipOver(";{line}");
    // ... rules go here ...
End Using
```

### Step 2: Validate the `[Server]` Section
We define a [Pattern](/Reference/uCalcBase/Transformer/Pattern) to find the `[Server]` section. We then chain the [Minimum(1)](/Reference/uCalcBase/Rule/Minimum) and [Maximum(1)](/Reference/uCalcBase/Rule/Maximum) methods to enforce that it must appear exactly once.

```pseudocode
var serverRule = validator.Pattern("'['Server']' {body}")
    .SetMinimum(1)
    .SetMaximum(1);
```

### Step 3: Validate Keys within the Section
This is where the hierarchy comes in. We get the [LocalTransformer](/Reference/uCalcBase/Rule/LocalTransformer) for our `serverRule`. Any rules defined on this local transformer will only run on the text captured by the `{body}` variable of the parent rule.

```pseudocode
var local_t = serverRule.@LocalTransformer();

// Rule for 'Host' key (must be exactly one)
var hostRule = local_t.Pattern("Host = {@Alpha}")
    .SetMinimum(1)
    .SetMaximum(1);

// Rule for 'Port' key (must be at least one)
var portRule = local_t.Pattern("Port = {@Number}")
    .SetMinimum(1);
```

### Step 4: Run the Validation
With all rules defined, we call [Find()](/Reference/uCalcBase/Transformer/Find) on the transformer. After it runs, we can inspect the [Matches().Count()](/Reference/uCalcBase/Matches/Count) for each rule. Because of our `Minimum` and `Maximum` constraints, a rule's match count will be `0` if its validation condition was not met, making the check simple.

---

## ⚖️ Why uCalc? (Comparative Analysis)

Without uCalc, you would write imperative code:
1.  Read the file line by line.
2.  Use `string.StartsWith()` to check for comments or sections.
3.  Use `string.Split('=')` to parse key-value pairs.
4.  Maintain manual counters and boolean flags (`foundServerSection`, `hostCount`, etc.) to track state.

This approach is brittle, hard to read, and difficult to maintain. uCalc's declarative model is superior because you simply **describe the rules of a valid file**, and the engine handles the complex state management and validation logic for you.

**Examples:**

### Example ID: 1449

**Description:** Checks for the existence of a required header in a string.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
    var text_ok = "Header: OK";
    var text_fail = "Header: ERROR";

    // This rule only matches if the status is "OK"
    t.Pattern("Header: OK");

    // Find() returns the transformer, so we can chain Matches().Count()
    if (t.SetText(text_ok).Find().@Matches().Count() > 0)
        wl("text_ok is valid.")
    end if

    if (t.SetText(text_fail).Find().@Matches().Count() == 0)
        wl("text_fail is invalid.")
    end if
End Using
```

**Output:**
```
text_ok is valid.
text_fail is invalid.
```

---

### Example ID: 1450

**Description:** Validates a configuration file format by enforcing the number of times specific keys must appear.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, validator)
    // 1. Configure the transformer
    validator.@DefaultRuleSet().@StatementSensitive(false);
    validator.SkipOver(";{line}"); // Ignore comments

    // 2. Define rules with validation constraints
    var serverRule = validator.Pattern("'['Server']' {body}").SetMinimum(1).SetMaximum(1);
    serverRule.@Description("Server Section");
    
    var local_t = serverRule.@LocalTransformer();
    var hostRule = local_t.Pattern("Host = {@Alpha}").SetMinimum(1).SetMaximum(1);
    hostRule.@Description("Host Key");
    
    var portRule = local_t.Pattern("Port = {@Number}").SetMinimum(1);
    portRule.@Description("Port Key");

    // --- Test Data ---
    [c]var validConfig = "[Server]\nHost = db1\nPort = 1433";
    var invalidConfig = "Host = web1\nPort = 80"; // Missing [Server] section[/c]
    [vb]var validConfig = "[Server]" & vbNewLine & "Host = db1" & vbNewLine & "Port = 1433";
    var invalidConfig = "Host = web1" & vbNewLine & "Port = 80"; // Missing [Server] section[/vb]

    // --- Validate validConfig ---
    wl("--- Validating valid_config.ini ---")
    validator.SetText(validConfig).Find();
    wl("  Server section check passed: ", bool(serverRule.@Matches().Count() == 1))
    wl("  Host key check passed: ", bool(hostRule.@Matches().Count() == 1))
    wl("  Port key check passed: ", bool(portRule.@Matches().Count() >= 1))
    wl("")

    // --- Validate invalidConfig ---
    wl("--- Validating invalid_config.ini ---")
    validator.SetText(invalidConfig).Find();
    wl("  Server section check passed: ", bool(serverRule.@Matches().Count() == 1))
    // The host and port rules will have 0 matches because their parent rule (serverRule) failed.
    wl("  Host key check passed: ", bool(hostRule.@Matches().Count() == 1))
    wl("  Port key check passed: ", bool(portRule.@Matches().Count() >= 1))
End Using
```

**Output:**
```
--- Validating valid_config.ini ---
  Server section check passed: True
  Host key check passed: True
  Port key check passed: True

--- Validating invalid_config.ini ---
  Server section check passed: False
  Host key check passed: False
  Port key check passed: False
```

---

---

## Project: Building a Custom Chatbot Intent Parser - ID: 1028
/doc/tutorials/hands-on-starter-projects/project:-building-a-custom-chatbot-intent-parser/

**Description:** A step-by-step tutorial on building a simple chatbot intent parser using the uCalc Transformer to extract commands and parameters from natural language.

**Remarks:**

# 🤖 Project: Building a Custom Chatbot Intent Parser

This project will guide you through building a simple but powerful intent parser for a chatbot or voice assistant. It's a perfect real-world example of how the declarative power of the [uCalc.Transformer](/reference/classes/ucalc.transformer/) can solve simple natural language understanding (NLU) problems more effectively than regular expressions and more efficiently than heavyweight machine learning libraries.

### The Goal: Understanding User Commands

Our objective is to parse user commands to determine the user's **intent** (what they want to do) and extract any relevant **entities** (the parameters for that action).

For example, in the command `"set a timer for 5 minutes"`:
*   **Intent**: `SET_TIMER`
*   **Entities**: `duration=5`, `unit=minutes`

We want to transform this natural language string into a structured, machine-readable format that our application can easily act upon.

### The Strategy: Transformer Rules

We will use the [uCalc.Transformer](/reference/classes/ucalc.transformer/) to define a set of rules. Each rule will map a specific command pattern to a structured output string. This approach is ideal for command-and-control applications where the range of user inputs is relatively predictable.

--- 

## Step 1: Setting Up the Transformer

First, we need a [Transformer](/reference/classes/ucalc.transformer/) instance. This will be our parsing engine. Since user commands are typically single lines and case-insensitive, we can configure the default behavior accordingly.

```pseudocode
New(uCalc::Transformer, t)
// Make all rules case-insensitive by default
t.@DefaultRuleSet().@CaseSensitive(false);
```

## Step 2: Defining the Intent Rules

Next, we define our parsing logic using [FromTo()](/reference/classes/ucalc.transformer/fromto/) rules. We'll use pattern variables like `{duration}` and token category matchers like `{@Number}` to capture the dynamic parts of the command.

```pseudocode
// Rule for setting a timer
t.FromTo("set timer for {@Number:duration} {unit}", "INTENT:SET_TIMER DURATION:{duration} UNIT:{unit}");

// Rule for playing music by a specific artist
t.FromTo("play music by {artist}", "INTENT:PLAY_MUSIC ARTIST:{artist}");
```

Note that in the second rule, `{artist}` will greedily capture all text until the end of the line, which is perfect for multi-word artist names.

## Step 3: Processing User Input

With our rules defined, we can now process user input by calling the `Transform()` method. The output is a clean, structured string that is trivial for our application to parse further.

```pseudocode
var command = "play music by The Rolling Stones";
var parsed = t.Transform(command);
wl(parsed);
// Output: INTENT:PLAY_MUSIC ARTIST:The Rolling Stones
```

Your application can then split this string to get the intent and entities and execute the appropriate action.

--- 

## ⚖️ Why uCalc? (Comparative Analysis)

*   **vs. Regular Expressions**: While you could use Regex, patterns quickly become complex and brittle. Handling variations like `"set a 5 minute timer"` vs. `"set timer for 5 minutes"` requires complicated optional groups. uCalc's token-based patterns are more readable and robust.

*   **vs. Machine Learning (ML) / NLP Libraries**: For complex, conversational AI, ML-based solutions (like Rasa, Dialogflow) are necessary. However, for simple command-and-control applications, they are heavyweight, slow, and require training data. uCalc provides a lightweight, high-performance, rule-based solution that is perfect for this middle ground, offering deterministic results without the overhead of a neural network.


**Examples:**

### Example ID: 1454

**Description:** Parsing a simple 'set timer' command to extract its intent and entities.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@DefaultRuleSet().@CaseSensitive(false);

// Define a rule to capture the duration and unit
t.FromTo("set timer for {@Number:duration} {unit}", "INTENT:SET_TIMER DURATION:{duration} UNIT:{unit}");

var command = "set timer for 10 seconds";
wl(t.Transform(command))
```

**Output:**
```
INTENT:SET_TIMER DURATION:10 UNIT:seconds
```

---

### Example ID: 1455

**Description:** A practical example parsing multiple command variations for different intents, such as playing music and setting alarms.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@DefaultRuleSet().@CaseSensitive(false);

// Define multiple rules for different intents
t.FromTo("play music by {artist}", "INTENT:PLAY_MUSIC ARTIST:{artist}");
t.FromTo("play the song {song_title}", "INTENT:PLAY_MUSIC SONG:{song_title}");
t.FromTo("set an alarm for {time}", "INTENT:SET_ALARM TIME:{time}");

wl(t.Transform("play music by Queen"))
wl(t.Transform("play the song Bohemian Rhapsody"))
wl(t.Transform("set an alarm for 7 am"))
```

**Output:**
```
INTENT:PLAY_MUSIC ARTIST:Queen
INTENT:PLAY_MUSIC SONG:Bohemian Rhapsody
INTENT:SET_ALARM TIME:7 am
```

---

---

## Concepts - ID: 666
/doc/concepts/

---

## How Expressions Are Processed - ID: 686
/doc/concepts/how-expressions-are-processed/

**Description:** Explains uCalc's two-stage process for handling expressions: parsing (compilation) and evaluation (execution).

**Remarks:**

# 📜 Expressions and Parsing: The Core of uCalc

At its heart, uCalc is an engine designed to understand and compute **expressions**. An expression is simply a string of text that contains instructions, which can range from simple arithmetic to complex logical and string-based operations.

*   `"5 * (10 + 2)"`
*   `"'Hello' + ' World!'"`
*   `"IIf(x > 0, Sin(x), 0)"`

Understanding how uCalc processes these strings is the key to writing efficient and powerful code. The entire process is a two-stage pipeline: **Parsing** and **Evaluation**.

---

## 1. Stage One: Parsing (The Blueprint)

Parsing is the process of converting a human-readable string into a structured, machine-executable format. This is the most computationally intensive part of the process and is what makes uCalc intelligent. It involves two sub-steps:

*   **Lexical Analysis (Tokenization)**: The engine first scans the string and breaks it into a sequence of meaningful units called **tokens**. For the expression `"x = 10.5"`, the tokens would be `x` (Identifier), `=` (Operator), and `10.5` (Number). This process is configured by the [Tokens](/Reference/uCalcBase/Tokens/Constructor) collection.

*   **Syntactic Analysis (AST Building)**: The stream of tokens is then analyzed to build a hierarchical structure known as an Abstract Syntax Tree (AST). This tree represents the order of operations, respecting operator precedence and parentheses. This tree is the final, compiled blueprint of the expression.

The [Parse](/Reference/uCalcBase/uCalc/Parse) method is the function dedicated to performing this stage. It takes a string and returns a compiled [Expression](/Reference/uCalcBase/Expression/Constructor) object, which contains this blueprint.

---

## 2. Stage Two: Evaluation (The Execution)

Evaluation is the process of walking through the AST created during parsing and performing the specified operations to produce a final result. This step is extremely fast because all the hard analytical work has already been done.

The [Evaluate](/Reference/uCalcBase/Expression/Evaluate) method, called on a parsed [Expression](/Reference/uCalcBase/Expression/Constructor) object, performs this stage.

---

## 🚀 The Performance Strategy: Parse-Once, Evaluate-Many

The single most important concept for writing high-performance code in uCalc is to separate these two stages. While convenience methods like [EvalStr](/Reference/uCalcBase/uCalc/EvalStr) are useful, they perform both parsing and evaluation on every call. In a loop, this is highly inefficient.

The optimal pattern is to **parse once, evaluate many**:

```pseudocode
// Parse the expression ONCE, before the loop begins.
var expr = uc.Parse("x * x + 2");

// Inside the loop, only the fast evaluation step is performed.
for (i = 1 to 1000)
    // Update variable value
    x.Value(i);
    // Evaluate the pre-parsed object
    wl(expr.Evaluate()); 
end for
```

This pattern allows calculations to run at speeds that approach native compiled code, making it suitable for real-time simulations, data processing, and other performance-critical tasks. For a detailed guide, see the [Optimizing Performance](/Tutorials/Getting-Started:-The-Expression-Parser/Optimizing-Performance) tutorial.

---

## Data types and evaluation - ID: 687
/doc/concepts/data-types-and-evaluation/

**Description:** An overview of uCalc's dynamic type system, type inference, and the distinction between single-step evaluation and the high-performance parse-evaluate model.

**Remarks:**

# ⚙️ Data Types and Evaluation in uCalc

The uCalc engine combines the flexibility of a dynamically typed language with the robustness of a strongly typed system. This topic provides an overview of how data types are handled and how expressions are evaluated, two fundamental concepts for using the library effectively.

---

## 1. The uCalc Type System

Unlike statically-compiled languages like C# or C++, where types are fixed at compile time, uCalc's type system is **dynamic at runtime**. However, every value still has a specific, well-defined type.

### 💡 Type Inference (The Default)

For convenience, uCalc automatically infers the data type from the value provided in a definition. This allows for concise, script-like code.

```pseudocode
// uCalc infers the types automatically

uc.DefineVariable("myDouble = 10.5");         // Becomes a Double type
uc.DefineVariable("myString = 'hello'");      // Becomes a String type
uc.DefineVariable("myFlag = 10 > 5");     // Becomes a Boolean type
```

### ✍️ Explicit Typing (`As` Keyword)

You can enforce a specific data type using the `As` keyword in a definition string. This is useful for ensuring type safety, optimizing memory, or when a variable is created without an initial value.

```pseudocode
// Explicitly define a 16-bit integer
uc.DefineVariable("counter As Int16");

// Define a function that must return a String
uc.DefineFunction("GetMessage() As String = 'OK'");
```

### 🎲 The Default Data Type: Double

If a type cannot be inferred (e.g., when defining a variable with no initial value), uCalc assigns the default data type. By default, this is `Double` (a 64-bit floating-point number), which is suitable for a wide range of mathematical calculations.

You can inspect or change this default for any uCalc instance using the [DefaultDataType](/Reference/uCalcBase/uCalc/DefaultDataType) property. This is useful if your application deals primarily with integers or another specific type.

For a list of all available types, see the [BuiltInType](/Reference/Enums/BuiltInType) enumeration.

---

## 2. The Evaluation Model

uCalc offers two primary models for evaluating expressions, designed to balance convenience with performance.

### 🚀 The High-Performance Model: Parse-Once, Evaluate-Many

The single most important concept for performance is the separation of parsing and evaluation.

1.  **Parsing**: The computationally expensive step of analyzing a string and building an executable plan. This is done once with the [Parse](/Reference/uCalcBase/uCalc/Parse) method, which returns an [Expression](/Reference/uCalcBase/Expression/Constructor) object.
2.  **Evaluation**: The extremely fast step of executing that pre-compiled plan. This is done repeatedly by calling methods like [Evaluate](/Reference/uCalcBase/Expression/Evaluate) or [EvaluateStr](/Reference/uCalcBase/Expression/EvaluateStr) on the `Expression` object.

This two-step pattern is critical for any code that runs in a loop and is explained in detail in the [Optimizing Performance](/Tutorials/Getting-Started:-The-Expression-Parser/Optimizing-Performance) tutorial.

### ✅ The Convenience Model: One-Step Evaluation

For one-off calculations where performance is not critical, uCalc provides the [Eval](/Reference/uCalcBase/uCalc/Eval) and [EvalStr](/Reference/uCalcBase/uCalc/EvalStr) methods. These convenient functions perform the parsing and evaluation steps internally in a single call.

*   `Eval()`: Optimized for numeric results, returns a `double`.
*   `EvalStr()`: The universal evaluator. It can return a value of any data type formatted as a string and safely returns error messages as strings, making it ideal for handling user input.

---

## Callback mechanics - ID: 688
/doc/concepts/callback-mechanics/

**Description:** Explains the mechanism for bridging the uCalc engine with native host code (C#, C++, VB.NET) via callback functions, including calling conventions and argument handling.

**Remarks:**

# 🤝 Callback Mechanics: Bridging uCalc and Native Code

Callbacks are the primary mechanism for creating a bridge between the dynamic uCalc scripting environment and your high-performance, native host application code (C#, C++, VB.NET). A callback allows an expression to call a function in your compiled code, pass it arguments, and receive a value back.

This is essential for:
*   Implementing complex logic that is too cumbersome for an expression string.
*   Integrating with existing application code.
*   Accessing system resources like files, databases, or UI elements.

## 1. The `Callback` Object

When you define a function with a callback using [DefineFunction](/Reference/uCalcBase/uCalc/DefineFunction) or [DefineOperator](/Reference/uCalcBase/uCalc/DefineOperator), your native function doesn't receive arguments directly. Instead, it receives a single, special object: the [Callback](/Reference/uCalcBase/Callback/Constructor) object (often referred to as `cb` in examples). This object is the sole interface for communicating with the engine.

Inside your callback, you use the `cb` object to:
1.  **Get Arguments**: Retrieve the values passed from the expression.
2.  **Return a Value**: Send a result back to the expression.
3.  **Access Context**: Get a handle to the parent [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance or the [Item](/Reference/uCalcBase/Item/Constructor) that triggered the call.

## 2. Retrieving Arguments & Returning Values

### Retrieving Arguments

The `Callback` object provides a family of type-safe methods for retrieving arguments.

*   [Arg()](/Reference/uCalcBase/Callback/Arg): The generic default, gets the nth argument as a `double`.
*   [ArgStr()](/Reference/uCalcBase/Callback/ArgStr): Gets the nth argument as a `string`.
*   [ArgInt32()](/Reference/uCalcBase/Callback/ArgInt32): Gets the nth argument as a 32-bit integer.
*   [ArgBool()](/Reference/uCalcBase/Callback/ArgBool): Gets the nth argument as a boolean.

⚠️ **Important**: Argument indexing is **1-based**, not 0-based. The first argument is at index `1`, the second at index `2`, and so on.

### Returning a Value

You do **not** use your language's standard `return` keyword to send a value back to uCalc. You must use the `Return...` methods on the `Callback` object.

*   [Return()](/Reference/uCalcBase/Callback/Return): Returns a `double`.
*   [ReturnStr()](/Reference/uCalcBase/Callback/ReturnStr): Returns a `string`.

## 3. Language-Specific Calling Conventions

How you declare a callback function in your native code depends on the language and platform.

### C# and VB.NET
In .NET, a callback is a delegate. The uCalc library provides a `DELEGATE_CALLBACK` type. You simply create a method with the correct signature and pass its address.
```
public void MyCallback(uCalc.Callback cb) { /* ... */ }
uc.DefineFunction("f()", MyCallback);
```

For more details, see the [C#](/Concepts/Language-specific/Cpp) and [VB](/Concepts/Language-specific/VB) language topics.

### C++
On Windows when compiling for x86 (32-bit), you must use the `ucalc_call` calling convention, which is an alias for `__stdcall`.

```cpp
void ucalc_call MyCallback(uCalc::Callback &cb) { /* ... */ }
```

For Windows x64, or other platforms like Linux and macOS, this calling convention is not necessary and can be omitted.

```cpp
void MyCallback(uCalc::Callback &cb) { /* ... */ }
```
For more details, see the [C++](/Concepts/Language-specific/C%2B%2B) language topic.

**Examples:**

---

## Error handling and control flow - ID: 689
/doc/concepts/error-handling-and-control-flow/

**Description:** Explains uCalc's state-based error handling and its mechanisms for creating custom control-flow structures.

**Remarks:**

# 💣 Error Handling & Control Flow: A Different Approach

uCalc's architecture for handling errors and implementing control flow differs from what developers in traditional compiled languages like C# or C++ might expect. Instead of relying on language-level `try/catch` blocks and `if/for` statements, uCalc provides an integrated, engine-level system designed for the dynamic nature of a parsing environment. This approach prioritizes performance, flexibility, and, most importantly, the ability to **recover** from errors gracefully.

This topic covers the two pillars of this system: uCalc's state-based error model and its lazy-evaluation mechanism for building custom control structures.

---
## 1. Error Handling: Recover, Don't Just Fail

In a parsing context, especially one dealing with user input, errors are not "exceptional" events; they are a normal part of operation. A user might type an incomplete formula or misspell a variable name. A traditional `try/catch` block, which unwinds the call stack, is a heavyweight solution for such common occurrences. uCalc uses a more lightweight, state-based model.

### The Two Methods of Error Handling

#### A. Reactive: Checking the Error State
The simplest way to handle errors is to check the engine's state after an operation. Every uCalc instance has an [Error](/Reference/uCalcBase/uCalc/Error) property that holds information about the last error. If an operation like [EvalStr](/Reference/uCalcBase/uCalc/EvalStr) fails, it doesn't throw an exception; it returns an error message as a string and sets the error state.

```pseudocode
var result = uc.EvalStr("5 * (10 +"); // Invalid syntax

// Reactively check if an error occurred
if (uc.@Error().@Code() != ErrorCode::None)
{
    wl("An error occurred: ", uc.@Error().@Message());
}
```
This approach is simple and effective for many use cases, but you only learn about the error *after* the operation has already aborted.

#### B. Proactive: The Error Handler Callback
For more advanced control, you can register an error handler using [AddHandler](/Reference/uCalcBase/ErrorInfo/AddHandler). This is a callback function that uCalc invokes the moment an error occurs, giving you the power to intercept, inspect, and even recover from it.

### The Power of Recovery with `Resume`
The most powerful feature of an error handler is the ability to control what happens next by setting the [Error.Response](/Reference/uCalcBase/ErrorInfo/Response) property. While the default is to `Abort`, you can set it to `ErrorHandlerResponse::Resume`.

This instructs the engine to **continue execution as if the error never happened**. This is the key to building fault-tolerant and "intelligent" parsers. For example, an error handler can catch an `Undefined_Identifier` error, automatically define the missing variable, and then `Resume` the evaluation, which will now succeed. This is a level of dynamic recovery that is very difficult to achieve with standard `try/catch` blocks.

For a full tutorial, see [Handling Errors](/Tutorials/Getting-Started:-The-Expression-Parser/Handling-Errors).

---
## 2. Control Flow: Lazy Evaluation with `ByExpr`

Just as uCalc avoids language-level `try/catch`, it also provides its own mechanism for control flow structures like `if` statements and loops. This is necessary because of a fundamental concept in expression evaluation: **eager evaluation**.

### The Problem with Eager Evaluation
In most languages, when you call a function like `MyFunc(arg1, arg2)`, both `arg1` and `arg2` are fully calculated *before* `MyFunc` begins to run. This makes it impossible to create a custom `if` function. A call like `MyIf(1 > 0, 100, 1/0)` would crash because the `1/0` in the "else" branch is evaluated eagerly, even though it should never be executed.

### The Solution: `ByExpr`
uCalc solves this with the `ByExpr` parameter modifier. When used in a function signature, it tells the engine not to pass the argument's final value, but to pass an unevaluated [Expression](/Reference/uCalcBase/Expression/Constructor) object instead.

The callback function then has complete control over this [Expression](/Reference/uCalcBase/Expression/Constructor) object. It can:
*   **Evaluate it**: Call `.Evaluate()` to get its result.
*   **Ignore it**: Choose not to evaluate it at all (the key to short-circuiting).
*   **Evaluate it multiple times**: The foundation for creating custom loops.

This mechanism is the core of all control flow in uCalc. It is used to implement the built-in [IIf](/Reference/Functions-and-Operators/Functions/Specialized) function (a ternary operator), as well as looping constructs like [ForLoop](/Reference/Functions-and-Operators/Functions/Specialized) and [DoLoop](/Reference/Functions-and-Operators/Functions/Specialized). It also empowers you to build your own custom control structures, elevating uCalc from a simple calculator to a lightweight scripting engine.

For a detailed guide, see [Lazy Evaluation (ByExpr)](/Tutorials/Beyond-the-Basics---What-Makes-uCalc-Special/Lazy-Evaluation-(ByExpr)).

**Examples:**

### Example ID: 1457

**Description:** Checking the error code for a simple syntax error

**Code:**
```pseudocode
var result = uc.Eval("MyVar * 10");
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
```

**Output:**
```
An error has occurred!
Error #: 258
Error Message: Undefined identifier
Error Location: 0
Error Expression: MyVar * 10
```

---

### Example ID: 410

**Description:** A practical example demonstrating all four related floating-point error configuration methods.

**Code:**
```pseudocode
wl("Divide by Zero (Default): ", uc.EvalStr("1/0"))
uc.@Error().@TrapOnDivideByZero(true);
wl("Divide by Zero (Error Enabled): ", uc.EvalStr("1/0"))

wl("")
wl("Invalid Operation (Default): ", uc.EvalStr("Sqrt(-1)"))
uc.@Error().@TrapOnInvalid(true);
wl("Invalid Operation (Error Enabled): ", uc.EvalStr("Sqrt(-1)"))

wl("")
wl("Overflow (Default): ", uc.EvalStr("5*10^308"))
uc.@Error().@TrapOnOverflow(true);
wl("Overflow (Error Enabled): ", uc.EvalStr("5*10^308"))

wl("")
wl("Underflow (Default): ", uc.EvalStr("10^-308/10000"))
uc.@Error().@TrapOnUnderflow(true);
wl("Underflow (Error Enabled): ", uc.EvalStr("10^-308/10000"))
```

**Output:**
```
Divide by Zero (Default): inf
Divide by Zero (Error Enabled): Division by 0

Invalid Operation (Default): nan
Invalid Operation (Error Enabled): Invalid operation

Overflow (Default): inf
Overflow (Error Enabled): Floating point overflow

Underflow (Default): 0
Underflow (Error Enabled): Floating point underflow
```

---

### Example ID: 1

**Description:** Adding an error handler callback

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Symbol: ", uc.@Error().@Symbol())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);
wl(uc.EvalStr("123+"))
wl("")

uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("5/0"))
```

**Output:**
```
An error has occurred!
Error #: 257
Error Message: Syntax error
Error Symbol: +
Error Location: 3
Error Expression: 123+
Syntax error

An error has occurred!
Error #: 8
Error Message: Division by 0
Error Symbol: 
Error Location: 0
Error Expression: 
Division by 0
```

---

### Example ID: 326

**Description:** Creating an error handler that automatically defines variables on the fly by checking for an 'Undefined Identifier' error.

**Code:**
```pseudocode
[head]
[callback:u AutoDefineHandler]
  // Check if the error is specifically an undefined identifier
  if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
    // If so, define the missing variable and instruct uCalc to resume
    wl("Auto-defining variable: '", uc.@Error().@Symbol(), "'")
    uc.DefineVariable(uc.@Error().@Symbol());
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
  end if
[/callback]

[body]
uc.@Error().AddHandler(AutoDefineHandler);

// 'x' doesn't exist, but the handler will intercept the error and create it.
var Result = uc.EvalStr("x = 10; x * 5");
wl("Result: ", Result)
```

**Output:**
```
Auto-defining variable: 'x'
Result: 50
```

---

### Example ID: 55

**Description:** Error handler order

**Code:**
```pseudocode
[head]
[callback:u ErrorHandlerA]
wl("Handler A called")
[/callback]

[callback:u ErrorHandlerB]
wl("Handler B called")
[/callback]

[callback:u ErrorHandlerC]
wl("Handler C called")
[/callback]

[callback:u ErrorHandlerD]
wl("Handler D called")
[/callback]

[callback:u ErrorHandlerE]
wl("Handler E called")
[/callback]

[body]
uc.@Error().AddHandler(ErrorHandlerA);
uc.@Error().AddHandler(ErrorHandlerB);
uc.@Error().AddHandler(ErrorHandlerC);
uc.@Error().AddHandler(ErrorHandlerD, -1);
uc.@Error().AddHandler(ErrorHandlerE, 3);

wl(uc.EvalStr("10 / "))
```

**Output:**
```
Handler C called
Handler B called
Handler A called
Handler E called
Handler D called
Syntax error
```

---

### Example ID: 483

**Description:** Raises an error with a dynamic message if a validation check fails within a callback.

**Code:**
```pseudocode
[head]
[callback ValidateValue]
    var val = cb.Arg(1);
    if (val > 100)
        // The error message includes the problematic value, making it dynamic.
        cb.@Error().Raise("Value exceeds maximum of 100. Got: " + [cpp]to_string((int)val)[/cpp][NotCpp]val.ToString()[/NotCpp]);
    else
        cb.Return(val);
    end if
[/callback]
[body]
uc.DefineFunction("CheckValue(val)", ValidateValue);
wl(uc.EvalStr("CheckValue(50)"))
wl(uc.EvalStr("CheckValue(123)"))
```

**Output:**
```
50
Value exceeds maximum of 100. Got: 123
```

---

### Example ID: 1190

**Description:** A practical example of a proactive error handler that automatically defines undeclared variables on the fly, allowing the expression to successfully resume execution.

**Code:**
```pseudocode
[head]
// This handler automatically defines variables when they are first used.
[callback:u AutoDefineHandler]
  // Check if the error is specifically an undefined identifier
  if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
    wl("Handler: '", uc.@Error().@Symbol(), "' is undefined. Defining it now.")
    uc.DefineVariable(uc.@Error().@Symbol());
    
    // Tell the engine to resume the operation
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
  end if
[/callback]

[body]
uc.@Error().AddHandler(AutoDefineHandler);

// 'my_var' doesn't exist yet, but the handler will create it.
var result = uc.EvalStr("my_var = 100; my_var = my_var * 2");

wl("Final result: ", result)
```

**Output:**
```
Handler: 'my_var' is undefined. Defining it now.
Final result: 200
```

---

---

## Thread safety - ID: 690
/doc/concepts/thread-safety/

**Description:** Explains uCalc's thread safety model and the best practices for using the library in multi-threaded applications.

**Remarks:**

# 🧵 Thread Safety in uCalc

This guide covers the principles and best practices for using the uCalc library in multi-threaded applications, such as web servers, parallel data processors, or applications with responsive user interfaces.

## 1. The Core Principle: Instance Isolation

A single `uCalc` instance is **not** thread-safe. An instance is a stateful engine containing variables, functions, error states, and configuration settings. Attempting to access or modify a single instance from multiple threads concurrently without external locking will lead to race conditions, corrupted state, and unpredictable behavior.

**Do not share a single `uCalc` instance across multiple threads.**

## 2. ✅ The Recommended Solution: One Instance Per Thread

The correct and most performant approach is to provide each thread with its own dedicated `uCalc` instance. The recommended pattern is to:

1.  **Create a Master Instance**: Configure a single, master `uCalc` object with all the required functions, operators, variables, and settings during your application's startup phase.
2.  **Clone for Each Thread**: When a new thread or task begins, create a local copy for that thread by calling [Clone()](/Reference/uCalcBase/uCalc/Clone) on the master instance. Cloning is a highly optimized operation designed for this exact purpose.
3.  **Use and Release**: The thread performs its work using its private clone. When the work is complete, the cloned instance should be released.

This pattern ensures complete thread isolation, allowing for maximum parallelism without any risk of state corruption.

## 3. ✨ The Exception: The Thread-Local Default Instance

A key architectural feature of uCalc is that the **default instance stack is thread-local**. The static [DefaultInstance](/Reference/uCalcBase/uCalc/DefaultInstance) property does not return a single global object; it returns the default instance for the *currently executing thread*.

This means:
*   If Thread A calls [myInstance.IsDefault(true)](/Reference/uCalcBase/uCalc/IsDefault), it only affects the default instance for Thread A.
*   Thread B's default instance remains completely unaffected.

This makes the default instance mechanism surprisingly robust and safe for use in multi-threaded environments, allowing different components or threads to work with their own ambient contexts without conflict.

## 4. ❌ The Anti-Pattern: External Locking

A developer's first instinct might be to wrap all calls to a shared `uCalc` instance in a lock or mutex. While this would prevent race conditions, it is strongly discouraged as an anti-pattern.

```pseudocode
// ANTI-PATTERN: Do not do this!
lock (sharedCalc) {
  result = sharedCalc.Eval("...");
}
```

Using locks serializes access to the `uCalc` engine, creating a major performance bottleneck that completely negates the benefits of multi-threading. The 'one instance per thread' model allows for true parallel execution and is significantly more scalable.

## 💡 Why uCalc? (Comparative Analysis)

*   **Instance-Based vs. Static**: Many simpler libraries provide only static evaluation functions, making them unsuitable for multi-threading due to shared global state. uCalc's instance-based design provides natural encapsulation, making it a perfect fit for parallel processing.
*   **Efficient Cloning**: The [Clone()](/Reference/uCalcBase/uCalc/Clone) method is lightweight and optimized. It avoids the high cost of creating a new instance and re-running dozens of `Define` calls from scratch for every thread.
*   **Built-in Thread-Local Default**: The thread-safe default instance is a sophisticated feature that simplifies working with ambient contexts in multi-threaded code, a task that would otherwise require manual implementation of thread-local storage patterns.

**Examples:**

---

## Performance considerations - ID: 691
/doc/concepts/performance-considerations/

**Description:** A guide to the key architectural patterns and best practices for writing high-performance code with the uCalc engine.

**Remarks:**

# ⚡ Writing High-Performance uCalc Code

While the uCalc engine is highly optimized out of the box, understanding its core architecture is essential for achieving maximum performance in demanding applications. This guide summarizes the most important patterns and best practices for writing efficient code.

For a step-by-step guide on the most critical optimization, see the [Optimizing Performance](/Tutorials/Getting-Started:-The-Expression-Parser/Optimizing-Performance) tutorial.

---

## The Core Principle: Parse vs. Evaluate

The single most important concept for performance is the separation of **parsing** from **evaluation**.

*   **Parsing**: The computationally expensive step of analyzing a string, tokenizing it, and building an executable plan (an abstract syntax tree). This is done by methods like [Parse](/Reference/uCalcBase/uCalc/Parse).
*   **Evaluation**: The extremely fast step of executing that pre-compiled plan to produce a result. This is done by methods like [Evaluate](/Reference/uCalcBase/Expression/Evaluate).

Convenience methods like [Eval](/Reference/uCalcBase/uCalc/Eval) and [EvalStr](/Reference/uCalcBase/uCalc/EvalStr) combine both steps, which is perfectly acceptable for one-off calculations but inefficient for repeated use.

---

## Key Performance Strategies

### 1. The "Parse-Once, Evaluate-Many" Pattern
This is the most critical optimization for any expression that is executed more than once, especially inside a loop. By parsing the expression string *outside* the loop and evaluating the resulting [Expression](/Reference/uCalcBase/Expression) object *inside* the loop, you avoid the redundant cost of parsing the same structure repeatedly. Execution speed can approach that of native compiled code.

### 2. Zero-Copy Updates with Host Variable Binding
For frequently updated variables, even calling `myVar.Value(i)` inside a loop has some overhead. For maximum performance, you can bind a uCalc variable directly to a memory address in your host application using an optional parameter in [DefineVariable](/Reference/uCalcBase/uCalc/DefineVariable). This creates a zero-copy "live link," allowing the uCalc engine to read from and write to your native variable's memory directly, eliminating all method call overhead for updates.

### 3. Prefer Specialized, Type-Safe Methods
When possible, use type-specific accessors and evaluation methods. For example:

*   Use `ValueInt32(5)` instead of `Value("5")`. The former is a direct memory write; the latter involves string parsing.
*   If an expression is guaranteed to return a boolean, use `EvaluateBool()` instead of `Evaluate()`. This avoids a potential type conversion from boolean to double, making the operation more direct and efficient.

### 4. Reuse Objects with Reset()
Creating new objects like a [Transformer](/Reference/uCalcBase/Transformer/Constructor) incurs setup costs (memory allocation, copying default token sets, etc.). For repetitive tasks that use the same configuration, it is far more performant to create a single `Transformer` instance and call [Reset()](/Reference/uCalcBase/Transformer/Reset) between operations. This clears the transformer's state (input text, matches) but reuses the existing object and its configuration, avoiding repeated setup overhead.

### 5. Transformer Performance
*   **`{@Eval}` vs. `{@@Eval}`**: In replacement strings, the static `{@Eval}` directive is much faster than the dynamic `{@@Eval}`. `{@Eval}` parses its expression once when the rule is created. `{@@Eval}` re-parses its expression every time a match is found. Use `{@Eval}` whenever the formula is fixed and only the variable values change.
*   **`TokenTransformer` vs. `ExpressionTransformer`**: The [TokenTransformer](/Reference/uCalcBase/uCalc/TokenTransformer) is more efficient than the [ExpressionTransformer](/Reference/uCalcBase/uCalc/ExpressionTransformer). It is only triggered when a specific token type (`TokenType::TokenTransform`) is encountered, whereas the `ExpressionTransformer` runs on every single expression passed to the parser.

---

## ⚖️ How uCalc Compares: A Performance Perspective

uCalc's architectural model provides significant performance advantages over common alternatives for runtime evaluation.

*   **vs. Scripting `eval()` & .NET `DataTable.Compute`**: These tools are notoriously slow because they must re-parse the expression string on every single call. This makes them completely unsuitable for performance-critical loops where uCalc's two-step model excels.

*   **vs. C# Expression Trees**: Compiling a C# `Expression` into a delegate provides similar high performance for evaluation. However, building that expression tree from a raw string at runtime is a complex, multi-step process that often requires writing your own parser. uCalc's [Parse()](/Reference/uCalcBase/uCalc/Parse) method provides a simple, one-step way to get a high-performance compiled object from a string, offering the best of both worlds.

---

## Properties / Getters / Setters - ID: 858
/doc/concepts/properties-/-getters-/-setters/

**Description:** Explains the different syntaxes for accessing uCalc properties, including native C#/VB property syntax, C++ method calls, and universal Get/Set methods.

**Remarks:**

# ⚙️ Properties, Getters, and Setters

uCalc is designed with a consistent cross-platform API, but it also embraces idiomatic language features to provide a natural developer experience. Many members documented as "properties" can be accessed in several ways, depending on the language and coding style.

## 1. Native C# and VB.NET Properties

For C# and VB.NET developers, properties can be accessed using the familiar assignment (`=`) syntax. The uCalc engine maps these property accesses to the underlying getter and setter methods.

#### C#
```csharp
// Getter
var value = myObject.PropertyName;
// Setter
myObject.PropertyName = "new value";
```

#### VB.NET
```vb.net
' Getter
Dim value = myObject.PropertyName
' Setter
myObject.PropertyName = "new value"
```

## 2. C++ Method Calls

C++ does not have a direct equivalent to C#/VB.NET properties. Instead, all property interactions are performed through explicit method calls. The getter is a parameterless method, and the setter is a method with one parameter.

```cpp
// Getter
auto value = myObject.PropertyName();
// Setter
myObject.PropertyName("new value");
```

## 3. Universal Get/Set Methods (All Languages)

For complete cross-platform consistency, every property also has explicit `Get...` and `Set...` methods. These are available in all languages and are useful for library authors or teams working in multiple languages.

#### C#
```csharp
var value = myObject.GetPropertyName();
myObject.SetPropertyName("new value");
```

#### VB.NET
```vb.net
Dim value = myObject.GetPropertyName()
myObject.SetPropertyName("new value")
```

#### C++
```cpp
auto value = myObject.GetPropertyName();
myObject.SetPropertyName("new value");
```

### ✨ The Fluent Interface Advantage

The `Set...` methods have a special feature: they return the object instance itself. This enables a **fluent interface**, allowing you to chain multiple setter calls together into a single, readable statement.

```csharp
// C# Example of chaining multiple Set... calls on DefaultRuleSet
t.GetDefaultRuleSet()
 .SetBracketSensitive(false)
 .SetCaseSensitive(false)
 .SetQuoteSensitive(false);
```

## Summary of Syntax

| Feature         | C#                     | VB.NET                     | C++                     |
| :-------------- | :--------------------- | :------------------------- | :---------------------- |
| **Getter**      | `var x = t.MyProp;`      | `Dim x = t.MyProp`       | `auto x = t.MyProp();`  |
| **Setter**      | `t.MyProp = "v";`        | `t.MyProp = "v"`         | `t.MyProp("v");`        |
| **Prefixed getter** | `var x = t.GetMyProp();` | `Dim x = t.GetMyProp()` | `auto x = t.GetMyProp();` |
| **Fluent Setter** | `t.SetMyProp("v");`     | `t.SetMyProp("v")`       | `t.SetMyProp("v");`     |

## 💡 Why uCalc? (Comparative Analysis)

This multi-faceted API design reflects a pragmatic approach. Instead of forcing a single "one-size-fits-all" method, uCalc provides:
*   **Idiomatic APIs** for C# and C++ developers, reducing the learning curve.
*   A **consistent, cross-platform API** (`Get`/`Set` methods) for library authors or teams working in multiple languages.
*   A **fluent interface** for setters, which promotes clean and readable configuration code.

This is a distinct advantage over libraries that either expose a C-style method-only API (which feels unnatural in C#) or a property-only API (which is unusable in C++). uCalc's translation layer provides the best of all worlds.

**Examples:**

### Example ID: 1160

**Description:** Demonstrates the basic getter and setter syntax for a property

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// Set the description using the property setter syntax
t.@Description("My Transformer");

// Get the description using the property getter syntax
wl("Description: ", t.@Description())
```

**Output:**
```
Description: My Transformer
```

---

### Example ID: 1161

**Description:** A practical example using the fluent interface of `Set...` methods to configure multiple properties of a rule in a single chained statement.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var rule = t.FromTo("A", "B");

// Chain multiple Set... methods for a clean configuration
rule.SetCaseSensitive(true)[c]
    [/c].SetWhitespaceSensitive(false)[c]
    [/c].SetQuoteSensitive(false);

// Verify the properties were set using their corresponding getters
wl("Case Sensitive: ", bool(rule.@CaseSensitive()))
wl("Whitespace Sensitive: ", bool(rule.@WhitespaceSensitive()))
wl("Quote Sensitive: ", bool(rule.@QuoteSensitive()))
```

**Output:**
```
Case Sensitive: True
Whitespace Sensitive: False
Quote Sensitive: False
```

---

---

## Shortcut notations - ID: 859
/doc/concepts/shortcut-notations/

**Description:** Explains how implicit operators in C#, VB.NET, and C++ allow for more natural and concise code by treating uCalc objects like native strings.

**Remarks:**

# 🪄 Shortcut Notations

uCalc leverages language features like operator overloading to provide syntactic sugar. This allows certain uCalc objects—specifically [Expression](/Reference/uCalcBase/Expression), [String](/Reference/uCalcBase/String), and [Transformer](/Reference/uCalcBase/Transformer)—to be treated as if they were native strings, significantly reducing boilerplate code and improving readability.

These shortcuts are made possible by the ability in C#, VB.NET, and C++ to define custom, implicit conversions to and from the `string` type.

### 1. `Expression` Shortcuts

The [Expression](/Reference/uCalcBase/Expression) object has the most powerful set of shortcuts, simplifying both parsing and evaluation.

*   **Implicit `Parse` on Assignment**: When you assign a string to an `Expression` variable, uCalc automatically calls the object's [Parse](/Reference/uCalcBase/Expression/Parse) method behind the scenes.

    *   **Verbose Way**: [pseudocode]`expr.Parse("5+4");`
    *   **Shortcut**: [pseudocode]`expr = "5+4";`

*   **Implicit `EvaluateStr` on `ToString()`**: When an `Expression` object is used in a context that requires a string (like `wl()` or string concatenation), its `ToString()` method is implicitly called, which in turn executes [EvaluateStr()](/Reference/uCalcBase/Expression/EvaluateStr).

    *   **Verbose Way**: [pseudocode]`wl(expr.EvaluateStr());`
    *   **Shortcut**: [pseudocode]`wl(expr);`

### 2. `String` and `Transformer` Shortcuts

For [String](/Reference/uCalcBase/String) and [Transformer](/Reference/uCalcBase/Transformer) objects, assignment to and from a string literal acts as a shortcut for accessing the object's primary text property.

*   **Assignment to Object**: Assigning a string to the object variable is equivalent to setting its [Text](/Reference/uCalcBase/Transformer/Text) property.

    *   **Verbose Way**: [pseudocode]`t.Text = "Hello World";`
    *   **Shortcut**: [pseudocode]`t = "Hello World";`

*   **Assignment from Object**: Assigning the object to a string variable is equivalent to getting its [Text](/Reference/uCalcBase/Transformer/Text) property.

    *   **Verbose Way**: [pseudocode]`var result = t.Text;`
    *   **Shortcut**: [pseudocode]`var result = t;`

## 💡 Why uCalc? (Comparative Analysis)

This API design demonstrates a focus on developer experience. Most classes in standard libraries require explicit property access (e.g., `StringBuilder.ToString()`, `StreamReader.ReadToEnd()`). By providing implicit conversions, uCalc's objects feel more like built-in language primitives. This thoughtful design choice makes code more intuitive and less verbose, allowing developers to focus on their logic rather than on API boilerplate.

**Examples:**

### Example ID: 803

**Description:** Demonstrates implicit parsing on assignment and implicit evaluation when writing to the console.

**Code:**
```pseudocode
New(uCalc::Expression, expr("3+4"))
wl("Initial: ", expr) // Implicit EvaluateStr

expr = "20+100"; // Implicit Parse
wl("Reassigned: ", expr) // Implicit EvaluateStr
```

**Output:**
```
Initial: 7
Reassigned: 120
```

---

### Example ID: 804

**Description:** Shows how implicit conversions simplify using uCalc objects for text manipulation.

**Code:**
```pseudocode
[vb]New(uCalc::Transformer, t)
New(uCalc::String, s)[/vb][c]uCalc::Transformer t;
uCalc::String s;[/c]

// Implicitly set the Text property
t = "Source text with foo.";
s = "bar";

// Use the objects in a standard way
t.FromTo("foo", s.@Text());
t.Transform();

// Implicitly get the Text property
wl(t)
```

**Output:**
```
Source text with bar.
```

---

### Example ID: 805

**Description:** Internal Test: Verifies error handling with implicit parsing and evaluation.

**Code:**
```pseudocode
New(uCalc::Expression, expr)

// Implicitly parse an invalid expression. This sets an error state.
expr = "5 * (10 +";

// Implicit EvaluateStr should not throw but return the error message.
wl("Error Message: ", expr)

// Verify the error code is set.
wl("Error Code: ", [c](int)[/c][vb]CInt([/vb]expr.@uCalc().@Error().@Code()[vb])[/vb])

// Now, assign a valid expression.
expr = "10 + 20";

// The new assignment should clear the error state.
wl("Valid Result: ", expr)
wl("Error Code after success: ", [c](int)[/c][vb]CInt([/vb]expr.@uCalc().@Error().@Code()[vb])[/vb])
```

**Output:**
```
Error Message: Bracket delimiter error
Error Code: 265
Valid Result: 30
Error Code after success: 0
```

---

---

## Memory Management - ID: 867
/doc/concepts/memory-management/

**Description:** Explains uCalc's memory management model and best practices for object lifetime to prevent resource leaks.

**Remarks:**

# ⚙️ Memory Management

A [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance is more than just an object; it's a complete, sandboxed parsing and evaluation engine. Because the core engine is written in high-performance C++, proper management of its memory and lifetime is a critical aspect of using the library correctly.

This guide explains why lifetime management is necessary and covers the recommended strategies for preventing resource leaks.

---
## 1. The Core Concept: Managed Handle vs. Unmanaged Engine

When you create a `uCalc` object in a managed language like C# or VB.NET, the variable you hold is a lightweight **handle**. This handle points to the substantial, underlying C++ engine instance where the real work happens. The garbage collector (GC) in .NET only knows about the handle, not the unmanaged C++ engine.

If you simply let a `uCalc` handle go out of scope, the GC will clean up the handle, but the C++ engine instance will remain in memory, causing a resource leak.

Therefore, you must explicitly tell the engine when an instance is no longer needed.

---
## 2. Automatic Lifetime Management (Recommended)

The best practice is to tie the lifetime of a `uCalc` instance to a specific lexical scope. This is achieved using language-idiomatic patterns that guarantee cleanup when the object is no longer needed. This pattern is often referred to as RAII (Resource Acquisition Is Initialization).

### 💎 For C# and VB.NET: The `using` Statement
All major uCalc objects implement the `IDisposable` interface, making them compatible with the `using` statement. This is the safest and most recommended pattern in .NET.

```pseudocode
NewUsing(uCalc, tempCalc)
    wl("Inside scope, instance is active.");
End Using // tempCalc is automatically released here.
wl("Outside scope, instance has been released.");
```
For more language-specific details, see the [C#](/Concepts/Language-specific/C%23) and [VB](/Concepts/Language-specific/VB) topics.

### 💎 For C++: RAII and the `Owned()` Method
C++ developers should leverage the RAII pattern by creating `uCalc` objects on the stack. Calling the [Owned()](/Reference/uCalcBase/uCalc/Owned) method instructs the object's destructor to automatically call [Release()](/Reference/uCalcBase/uCalc/Release) when it goes out of scope.

```pseudocode
[cpp]
{
    uCalc scopedCalc;
    scopedCalc.Owned(); // Marks for auto-release
    
    // ... use scopedCalc ...

} // scopedCalc's destructor is called here, automatically calling Release().
[/cpp]
```
For more details, see the [C++](/Concepts/Language-specific/C%2B%2B) language topic.

---
## 3. Manual Lifetime Management with `Release()`

If an object's lifetime is not tied to a specific scope (e.g., a long-lived global or application-wide instance), you must manage its lifecycle manually by calling the [Release()](/Reference/uCalcBase/uCalc/Release) method when you are finished with it.

```pseudocode
// Create a new instance.
var myInstance = uc.Clone();

// ... use the instance throughout the application ...

// Manually release it during application shutdown to prevent a leak.
myInstance.Release();
wl("Instance has been manually released.");
```
Forgetting to call `Release()` on objects that are not managed by a `using` block or RAII is the most common cause of resource leaks.

**Examples:**

### Example ID: 255

**Description:** Quick Start

**Code:**
```pseudocode
// Create a new instance
NewUsing(uCalc, calc)

// Evaluate an expression
wl(calc.Eval("2 + 3"))
End Using
```

**Output:**
```
5
```

---

### Example ID: 256

**Description:** Creating isolated evaluation contexts.

**Code:**
```pseudocode
New(uCalc, main)
main.DefineVariable("rate = 0.05");

var scenarioA = main.Clone();
var scenarioB = main.Clone();

scenarioA.DefineVariable("rate = 0.10");
scenarioB.DefineVariable("rate = 0.20");

wl("A: ", scenarioA.Eval("1000 * rate"))
wl("B: ", scenarioB.Eval("1000 * rate"))
wl("Main: ", main.Eval("1000 * rate"))
main.Release();
scenarioA.Release();
scenarioB.Release();

```

**Output:**
```
A: 100
B: 200
Main: 50
```

---

### Example ID: 31

**Description:** Illustrates the core relationship between the uCalc engine, an Item (variable), and a compiled Expression.

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");
var Expression = "x^2 * 10"; // Replace this with your expression

wl("--- Efficient: Parse() once, then Evaluate() in a loop ---")
var ParsedExpr = uc.Parse(Expression);
for(double x = 1 to 10)
   VariableX.Value(x);
   wl(ParsedExpr.Evaluate())
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
--- Efficient: Parse() once, then Evaluate() in a loop ---
10
40
90
160
250
360
490
640
810
1000
```

---

### Example ID: 564

**Description:** Shows how the constructor's context (default vs. specific instance) affects variable resolution during parsing.

**Code:**
```pseudocode
// Set up two different uCalc contexts with the same variable name 'x'.
uCalc::@DefaultInstance().DefineVariable("x = 1.2");
uc.DefineVariable("x = 10");

wl("--- Testing Expression Contexts ---")

// 1. Expression created in the *default* context uses x = 1.2
NewUsing(uCalc::Expression, exprDefault("x + 5"))
wl("Default context (x=1.2): ", exprDefault.Evaluate())

// 2. Expression created in a *specific* context ('uc') uses x = 10
NewUsing(uCalc::Expression, exprSpecific(uc, "x + 5"))
wl("Specific context (x=10):  ", exprSpecific.Evaluate())

// 3. Create empty, then parse later (uses default context for the Parse call)
NewUsing(uCalc::Expression, exprEmpty)
exprEmpty.Parse("x * 10");
wl("Empty then parsed (x=1.2):", exprEmpty.Evaluate())
End Using
End Using
End Using
```

**Output:**
```
--- Testing Expression Contexts ---
Default context (x=1.2): 6.2
Specific context (x=10):  15
Empty then parsed (x=1.2):12
```

---

### Example ID: 1144

**Description:** A simple find-and-replace transformation to replace all occurrences of a word.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
// Define a simple replacement rule
t.FromTo("Hello", "Greetings");

// Execute the transformation on an input string
wl(t.Transform("Hello World, and Hello again."))
End Using
```

**Output:**
```
Greetings World, and Greetings again.
```

---

---

## Best Practices - ID: 954
/doc/concepts/best-practices/

**Description:** A guide to the most important principles for writing efficient, safe, and maintainable code with the uCalc library.

**Remarks:**

# ✅ uCalc Best Practices: A Developer's Guide

Welcome to the guide for writing effective, high-performance, and maintainable code with uCalc. While the library is designed to be flexible, adhering to these core principles will help you leverage its full power, avoid common pitfalls, and build robust applications.

This guide consolidates the most important concepts into five key areas.

---

## 1. 🚀 Performance First: The "Parse-Once, Evaluate-Many" Rule

This is the single most important principle for performance. While convenience methods like [EvalStr](/Reference/uCalcBase/uCalc/EvalStr) are great for one-off calculations, they are inefficient in loops because they re-parse the expression string on every call.

*   **The Wrong Way**: Calling [Eval()](/Reference/uCalcBase/uCalc/Eval) or [EvalStr()](/Reference/uCalcBase/uCalc/EvalStr) inside a loop.
*   **The Right Way**: Call [Parse()](/Reference/uCalcBase/uCalc/Parse) **once** before the loop to create a compiled [Expression](/Reference/uCalcBase/Expression/Constructor) object. Then, call [Evaluate()](/Reference/uCalcBase/Expression/Evaluate) on that object inside the loop.

This pattern separates the expensive parsing step from the lightning-fast evaluation step, allowing your code to run at speeds approaching native execution.

**➡️ Learn More**: [Optimizing Performance](/Tutorials/Getting-Started:-The-Expression-Parser/Optimizing-Performance)

---

## 2. 🛡️ Safety & Security: Sandbox and Structure

#### A. Trust the Sandbox
uCalc is a secure sandbox by default. Unlike `eval()` functions in scripting languages, a uCalc expression has no intrinsic access to the file system, network, or operating system. Leverage this safety by default, especially when processing untrusted user input. Be extremely cautious about creating [callbacks](/Concepts/Callback-mechanics) that expose risky OS-level functions.

#### B. Prefer the Transformer over Regex for Code
For transforming structured text like source code or configuration files, always use the token-aware [Transformer](/Reference/uCalcBase/Transformer/Constructor) instead of regular expressions. Regex is character-aware and can easily corrupt text inside string literals or comments. The [Transformer](/Reference/uCalcBase/Transformer/Constructor) understands these structures and is safe by default.

**➡️ Learn More**: [Structural Awareness (Tokens vs. Regex)](/Tutorials/Beyond-the-Basics-What-Makes-uCalc-Special/Structural-Awareness-Tokens-vs-Regex)

---

## 3. 🧩 Readability & Maintainability: Build a DSL

Don't just write complex formulas; build a Domain-Specific Language (DSL). Instead of embedding a long, cryptic expression in your code, create custom functions and operators that make the logic human-readable.

*   **Instead of This**: [pseudocode]`(principal * (rate/12)) / (1 - (1 + rate/12)^-(years*12))`
*   **Do This**: [pseudocode]`LoanPayment(principal, rate, years)`

Use [DefineFunction()](/Reference/uCalcBase/uCalc/DefineFunction) for new functions and [DefineOperator()](/Reference/uCalcBase/uCalc/DefineOperator) for new operators. For multi-word syntax, use the [ExpressionTransformer](/Reference/uCalcBase/uCalc/ExpressionTransformer). This makes your expressions cleaner, easier to debug, and more maintainable.

**➡️ Learn More**: [Creating Custom Functions](/Tutorials/Getting-Started-The-Expression-Parser/Creating-Custom-Functions) and [Dynamic Syntax](/Tutorials/Beyond-the-Basics-What-Makes-uCalc-Special/Dynamic-Syntax)

---

## 4. ⚙️ Memory Management: Embrace Scoping

uCalc objects wrap powerful C++ resources and must be released to prevent memory leaks. While you can call [Release()](/Reference/uCalcBase/uCalc/Release) manually, the best practice is to use language-idiomatic scoping mechanisms.

*   **C# / VB.NET**: Always create uCalc objects within a `using` block.
*   **C++**: Use RAII by creating objects on the stack and calling [Owned()](/Reference/uCalcBase/uCalc/Owned).

This guarantees that resources are cleaned up automatically when an object goes out of scope, making your code safer and more robust.

**➡️ Learn More**: [Managing Parser Instances & Lifetime](/Tutorials/Advanced-Integration/Managing-Parser-Instances-Lifetime)

---

## 5. 💣 Error Handling: Recover, Don't Just Crash

For parsing user input, errors are normal, not exceptional. uCalc's state-based error handling model is more lightweight and flexible than traditional `try/catch` blocks.

Embrace this by creating an error handler with [AddHandler()](/Reference/uCalcBase/ErrorInfo/AddHandler). The most powerful pattern is to use the `Resume` response to build self-healing parsers. For example, if a `Undefined_Identifier` error occurs, your handler can automatically define the variable and instruct the engine to continue, providing a seamless user experience.

**➡️ Learn More**: [Handling Errors](/Tutorials/Getting-Started-The-Expression-Parser/Handling-Errors)

---

## Common Gotchas - ID: 955
/doc/concepts/common-gotchas/

**Description:** A guide to the most common mistakes and misunderstandings developers encounter when using uCalc, with solutions and best practices.

**Remarks:**

# ⚠️ Common uCalc Gotchas & Pitfalls

This guide covers the most frequent mistakes developers make when working with uCalc. Understanding these points will save you significant debugging time and help you write more efficient, robust code.

---

## 1. 🐌 Performance: Using `Eval()` Inside a Loop
**The Pitfall**: Calling [Eval()](/Reference/uCalcBase/uCalc/Eval) or [EvalStr()](/Reference/uCalcBase/uCalc/EvalStr) inside a high-frequency loop.

**Why it's a problem**: Every call to `Eval()` performs two steps: parsing the string into an executable plan (slow) and then evaluating that plan (fast). In a loop, you're repeating the slow parsing step unnecessarily for every iteration.

**The Solution**: Use the **"Parse-Once, Evaluate-Many"** pattern.

```pseudocode
// Correct, High-Performance Way
var x_var = uc.DefineVariable("x");
// 1. Parse ONCE, outside the loop.
var expr = uc.Parse("x * x + 2");

// 2. Evaluate MANY times, inside the loop. This is very fast.
for(i = 1 to 1000)
    x_var.Value(i);
    wl(expr.Evaluate());
end for
```
For more details, see the [Optimizing Performance](/Tutorials/Getting-Started:-The-Expression-Parser/Optimizing-Performance) tutorial.

---

## 2. 🧠 Transformer Rules: Precedence is LIFO
**The Pitfall**: Assuming transformer rules are applied in the order they are defined.

**Why it's a problem**: uCalc uses a **LIFO (Last-In, First-Out)** stack for rule precedence. The **last rule defined is checked first**. This is often counter-intuitive.

```pseudocode
// Incorrect Assumption
New(uCalc::Transformer, t)
t.FromTo("An apple", "FRUIT"); // Defined first (lower priority)
t.FromTo("An {item}", "ITEM");  // Defined last (higher priority)

// This will output "ITEM" because the general rule was defined last.
wl(t.Transform("An apple"))
```

**The Solution**: Always define your **most specific rules last** to give them the highest priority.

```pseudocode
// Correct Way
New(uCalc::Transformer, t)
t.FromTo("An {item}", "ITEM");  // General rule first
t.FromTo("An apple", "FRUIT"); // Specific rule last

// This will correctly output "FRUIT".
wl(t.Transform("An apple"))
```

---

## 3. 💧 Memory Management: Forgetting to `Release()`
**The Pitfall**: Not releasing uCalc objects in non-RAII environments.

**Why it's a problem**: The uCalc core is C++. In managed languages like C#, the garbage collector only cleans up the .NET handle, not the underlying C++ engine instance. This causes a **memory leak**.

**The Solution**: Use language-idiomatic resource management.
*   **C# / VB.NET**: Always wrap object creation in a `using` block.
*   **C++**: Use stack-allocated objects and call `Owned()` to enable RAII.
*   **Manual**: If an object's lifetime is not scoped, you **must** call [Release()](/Reference/uCalcBase/uCalc/Release) when you are done with it.

```pseudocode
[cs]
// Correct C# Way
using (var t = uc.NewTransformer())
{
    // ... use t ...
} // t.Release() is called automatically here.
[/cs]
[cpp]
// Correct C++ Way
{
    uCalc::Transformer t;
    t.Owned();
    // ... use t ...
} // t's destructor automatically calls Release() here.
[/cpp]
```
See the [Memory Management](/Concepts/Memory-Management) guide for more information.

---

## 4. 🔢 Types in `{@Eval}`: Forgetting String Conversion
**The Pitfall**: Trying to perform math on a captured variable inside an [{@Eval}](/Reference/Patterns/Pattern-Methods/{@Eval}) block without converting it to a number.

**Why it's a problem**: All variables captured from a pattern, even from `{@Number:val}`, are **strings**. An expression like `val * 2` will result in string concatenation, not multiplication.

**The Solution**: Explicitly cast the string to a numeric type using functions like `Double()` or `Int()`.

```pseudocode
New(uCalc::Transformer, t)
// Incorrect: "10" * 2 would result in repeating the string twice resulting in "1010".
// Correct: Use Double() to convert the string '10' to a number.
t.FromTo("{@Number:val}", "{@Eval: Double(val) * 2}");

wl(t.Transform("Value: 10"))
```
For details, see [Executing Logic in Replacements](/Tutorials/Text-Transformation:-The-Transformer/Executing-Logic-in-Replacements).

---

## 5. 🔀 Alternation Order: Longest Match First
**The Pitfall**: In an [alternation](/Reference/Patterns/Introduction/Alternation) `|`, placing a shorter, partial match before a longer, more specific one.

**Why it's a problem**: The engine checks alternatives from **left to right** and stops at the first successful match.

```pseudocode
// Incorrect Order
New(uCalc::Transformer, t)
// "Apple" will match first, so "Apple Pie" is never checked.
t.FromTo("{ Apple | Apple Pie }", "MATCH");

wl(t.Transform("An Apple Pie")) // Incorrectly matches only "Apple"
```

**The Solution**: Always place the longest, most specific patterns first in an alternation.

```pseudocode
// Correct Order
New(uCalc::Transformer, t)
t.FromTo("{ Apple Pie | Apple }", "MATCH");

wl(t.Transform("An Apple Pie")) // Correctly matches "Apple Pie"
```

---

## 6. 📝 Indexing: 1-based vs. 0-based
**The Pitfall**: Confusing 1-based and 0-based indexing.

**Why it's a problem**: Different parts of the uCalc API use different conventions.
*   **1-based**: Arguments in a [Callback](/Reference/uCalcBase/Callback/Constructor) (e.g., `cb.Arg(1)`).
*   **0-based**: Most collections, like [Matches](/Reference/uCalcBase/Matches/Constructor) (`myMatches[0]`) and [Tokens](/Reference/uCalcBase/Tokens/Constructor) (`myTokens.At(0)`).

**The Solution**: Be mindful of the context. When in a callback interacting with arguments, think 1-based. When iterating a collection of results, think 0-based.

---

## FAQ - ID: 956
/doc/concepts/faq/

---

## Language-specific - ID: 868
/doc/concepts/language-specific/

---

## C# - ID: 870
/doc/concepts/language-specific/c#/

**Description:** Covers C#-specific features, syntax, and lifetime management patterns when using the uCalc library.

**Remarks:**

While uCalc is designed with a consistent cross-platform API, it offers several features that integrate seamlessly with C# idioms, providing a more natural and productive development experience.

## 💎 Idiomatic C# Features

### 1. Properties vs. Methods
Many uCalc members documented as properties (getters/setters) can be accessed using C# property syntax (`=`) instead of method calls (`()`). This provides cleaner, more readable code.

| Feature | C# Syntax | C++ Syntax |
| :--- | :--- | :--- |
| **Setter** | uc.Description = "text"; | uc.Description("text"); |
| **Getter** | d = uc.Description; | var d = uc.Description(); |

For a detailed overview, see the [Properties / Getters / Setters](/Concepts/Properties-Getters-Setters) topic.

### 2. Indexers (`[]`)
Collections like [Tokens](/Reference/uCalcBase/Tokens/Constructor) and [Matches](/Reference/uCalcBase/Matches/Constructor) support C# indexers (`[]`) for direct access to elements. This is a convenient shortcut for methods like `ByName()` or `At()`.

```pseudocode
// Instead of this:
var token = uc.ExpressionTokens.ByName("_token_alphanumeric");

// You can write this:
var token = uc.ExpressionTokens["_token_alphanumeric"];
```

### 3. `foreach` Loop Integration
All uCalc collection objects (e.g., [Matches](/Reference/uCalcBase/Matches/Constructor), [Tokens](/Reference/uCalcBase/Tokens/Constructor), [Items](/Reference/uCalcBase/ItemsAccessor)) implement `IEnumerable`. This means you can iterate over them directly using a standard C# `foreach` loop, which is simpler and safer than a manual `for` loop with an index.

```pseudocode
[CS]
foreach (var rule in myTransformer.Rules)
{
    wl(rule.Name);
}
[/CS]
```

### 4. Lifetime Management with `using`
**This is the most critical C#-specific pattern.** Most uCalc objects hold unmanaged resources and must be released to prevent memory leaks. While you can call [Release()](/Reference/uCalcBase/uCalc/Release) manually, the idiomatic C# approach is to wrap object creation in a `using` statement. All major uCalc objects implement `IDisposable`, which guarantees that `Release()` will be called automatically when the object goes out of scope.

```pseudocode
[CS]
// The transformer 't' will be released automatically at the end of the block.
using (var t = uc.NewTransformer())
{
    wl(t.Transform("input"));
} // t.Release() is called here.
[/CS]
```
This is the C# equivalent of the C++ RAII pattern using [Owned()](/Reference/uCalcBase/uCalc/Owned).

### 5. Implicit Conversions & Constructors
For convenience, several uCalc classes provide implicit conversions from `string`, allowing for more concise initialization.

*   **`uCalc.String`**: `uCalc.String s = "initial text";`
*   **`uCalc.Expression`**: `uCalc.Expression expr = "1 + 1";`
*   **`uCalc.Transformer`**: `t.Text = "input";` can be shortened to `t = "input";`

The `Expression` and `String` classes also have constructors that accept a string, which provides a familiar C# object creation pattern that implicitly uses the default `uCalc` instance.

```pseudocode
[CS]
// These two are equivalent, using the default uCalc instance.
var expr1 = uc.Parse("5 * 2");
var expr2 = new uCalc.Expression("5 * 2");
[/CS]
```

## 🆚 Comparative Analysis: Why uCalc in C#?

While C# is a powerful language, uCalc provides specialized capabilities not available natively:

*   **Runtime Parsing vs. `DataTable.Compute`**: The common C# workaround for evaluating strings, `DataTable.Compute`, is slow, limited to simple arithmetic, and lacks features like custom functions or operators. uCalc is a high-performance, full-featured parsing engine.

*   **Dynamic Language Definition**: C# is statically compiled. uCalc allows you to define new functions, operators, and even token syntax at **runtime**, enabling the creation of dynamic scripting environments and Domain-Specific Languages (DSLs) within your C# application.

*   **Token-Aware Transformations**: C#'s `Regex` is powerful for character-level patterns but struggles with nested structures and language context. uCalc's [Transformer](/Reference/uCalcBase/Transformer/Constructor) operates on tokens, making it inherently aware of code structure (parentheses, strings, comments), which is far more robust for code transformation and analysis.

**Examples:**

### Example ID: 806

**Description:** Demonstrates the core C# idioms: `using` for lifetime management, property syntax for setters/getters, and implicit string conversions.

**Code:**
```pseudocode
[CS]
// 1. Automatic resource management with 'using'
using (var u = new uCalc()) {
    // 2. Property syntax for setting the description
    u.Description = "My C# uCalc instance";
    wl("Description: ", u.Description)

    // 3. Implicit string conversion for Transformer.Text
    New(uCalc::Transformer, t) 
    t.Text = "Hello World"; // Standard assignment
    t = "Hello Again";    // Implicit conversion assignment
    wl("Transformer Text: ", t.Text)

}
[/CS]
[NotCS]
// This example is meant for C# only
wl("Description: My C# uCalc instance")
wl("Transformer Text: Hello Again")
[/NotCS]
```

**Output:**
```
Description: My C# uCalc instance
Transformer Text: Hello Again
```

---

---

## C++ - ID: 869
/doc/concepts/language-specific/c++/

**Description:** Covers C++-specific features, syntax, and best practices for lifetime management when using the uCalc library.

**Remarks:**

While uCalc is designed with a consistent cross-platform API, it offers several features that integrate seamlessly with C++ idioms, providing a more natural and productive development experience.

## 💎 Idiomatic C++ Features

### 1. Lifetime Management with RAII and `Owned()`
**This is the most critical C++-specific pattern.** Most uCalc objects hold unmanaged resources and must be released to prevent memory leaks. The idiomatic C++ approach is to leverage RAII (Resource Acquisition Is Initialization), where an object's lifetime is bound to the scope of a stack-allocated variable.

To bridge uCalc's memory model with RAII, you use the [Owned()](/Reference/uCalcBase/uCalc/Owned) method. When called on a stack-allocated uCalc object, it ensures that [Release()](/Reference/uCalcBase/uCalc/Release) is automatically called in the object's destructor when it goes out of scope.

```
{
    // Create a transformer on the stack.
    uCalc::Transformer t;
    // Mark it as 'owned' to enable automatic release.
    t.Owned();

    wl(t.Transform("input"));

} // t's destructor is called here, which automatically calls Release().
```
This pattern is essential for managing objects returned by methods like [Clone()](/Reference/uCalcBase/uCalc/Clone), which are allocated on the heap.

### 2. Operator Overloading & Implicit Conversions
For convenience, several uCalc classes provide implicit conversions to and from `std::string`, allowing for more concise and natural code.

*   **`uCalc::Expression`**: An `Expression` object can be assigned from a string literal, which implicitly calls `Parse()`. It can also be converted to a string, which implicitly calls `EvaluateStr()`.

    ```
    uCalc::Expression expr;
    expr = "5 + 4"; // Implicitly calls expr.Parse("5+4")
    wl(expr);     // Implicitly calls expr.EvaluateStr()
    ```

*   **`uCalc::String` & `uCalc::Transformer`**: Assignment to and from a string acts as a shortcut for the object's primary text property.

    ```
    uCalc::Transformer t;
    t = "some text"; // Equivalent to t.Text("some text")
    std::string result = t; // Equivalent to result = t.Text()
    ```

### 3. Method-Based Syntax
C++ does not have native property syntax like C#. Therefore, all interactions, including those documented as properties, are performed through method calls. This provides a consistent, predictable API.

*   **C# Syntax**: `uc.Description = "text";`
*   **C++ Syntax**: [pseudocode]`uc.Description("text");`

### 4. Range-Based `for` Loop Integration
All uCalc collection objects (e.g., [Matches](/Reference/uCalcBase/Matches/Constructor), [Tokens](/Reference/uCalcBase/Tokens/Constructor), [Items](/Reference/uCalcBase/ItemsAccessor)) are compatible with C++11's range-based `for` loops. This provides a modern, safe, and readable way to iterate over collections.

```
// Assume 'myTransformer' has run and has matches
for (const auto& match : myTransformer.Matches())
{
    wl(match.Text());
}
```

### 5. Callback Calling Convention
When defining a callback function in C++ for Windows x86 (32-bit) builds, you must use the `ucalc_call` convention (`__stdcall`). This is not required for x64 builds or other platforms like Linux. For more details, see [Callback mechanics](/Concepts/Callback-mechanics).

## 🆚 Comparative Analysis: Why uCalc in C++?

While C++ offers powerful libraries, uCalc provides specialized parsing capabilities that are simpler and more dynamic than traditional alternatives.

*   **vs. Parser Generators (Boost.Spirit, Flex/Bison)**: These tools are extremely powerful but require a separate grammar definition file, a code generation step, and a full recompile to make changes. uCalc is **fully dynamic**. You can define new tokens, functions, and operators at runtime through its C++ API, without any external tools or build steps. This makes it ideal for applications requiring user-configurable syntax or dynamic DSLs.

*   **vs. `std::regex` and String Manipulation**: C++'s standard regex is powerful for character-level patterns but struggles with nested structures and language context. uCalc's [Transformer](/Reference/uCalcBase/Transformer/Constructor) operates on **tokens**, making it inherently aware of code structure (parentheses, strings, comments). This is far more robust for code transformation and analysis than manual string splitting or fragile regex patterns.

*   **vs. Embedded Scripting Engines (Lua, ChaiScript)**: Full scripting engines are often heavy and can be complex to integrate. uCalc is a lightweight, specialized component focused on expression evaluation and transformation. Its API is designed for tight, high-performance integration with C++ code, allowing you to expose native functions as callbacks with minimal overhead.

**Examples:**

### Example ID: 812

**Description:** Demonstrates automatic resource management in C++ using RAII and the Owned() method.

**Code:**
```pseudocode
[cpp]
// Create a uCalc object on the stack.
New(uCalc, myCalc)
// Flag it as 'owned' to enable automatic cleanup.
myCalc.Owned();

myCalc.DefineVariable("x=10");
w("Evaluating in scope: ", myCalc.Eval("x*2"))

// When 'myCalc' goes out of scope at the end of the block,
// its destructor is called, which automatically calls Release().
[/cpp]
[NotCpp]
// This example is meant only for C++
w("Evaluating in scope: 20")
[/NotCpp]
```

**Output:**
```
Evaluating in scope: 20
```

---

---

## VB - ID: 871
/doc/concepts/language-specific/vb/

**Description:** Covers VB.NET-specific features, syntax, and lifetime management patterns when using the uCalc library.

**Remarks:**

# 💎 Idiomatic VB.NET Features

While uCalc is designed with a consistent cross-platform API, it offers several features that integrate seamlessly with VB.NET idioms, providing a more natural and productive development experience.

## 1. Properties vs. Methods
Many uCalc members documented as properties (getters/setters) can be accessed using standard VB.NET property syntax (`=`) instead of method calls (`()`). This provides cleaner, more readable code.

| Feature | VB.NET Syntax |  C++ Syntax |
| :--- | :--- | :--- |
| **Setter** | `uc.Description = "text"` | `uc.Description("text");` |
| **Getter** | `Dim d = uc.Description` | `var d = uc.Description();` |

For a detailed overview, see the [Properties / Getters / Setters](/Concepts/Properties-Getters-Setters) topic.

## 2. Indexers (`()`)
Collections like [Tokens](/Reference/uCalcBase/Tokens/Constructor) and [Matches](/Reference/uCalcBase/Matches/Constructor) support VB.NET indexers (`()`) for direct access to elements. This is a convenient shortcut for methods like `ByName()` or `At()`.

```
' Instead of this:
Dim token = uc.ExpressionTokens.ByName("_token_alphanumeric")

' You can write this:
Dim token = uc.ExpressionTokens("_token_alphanumeric")
```

## 3. `For Each` Loop Integration
All uCalc collection objects (e.g., [Matches](/Reference/uCalcBase/Matches/Constructor), [Tokens](/Reference/uCalcBase/Tokens/Constructor), [Items](/Reference/uCalcBase/ItemsAccessor)) implement `IEnumerable`. This means you can iterate over them directly using a standard VB.NET `For Each` loop, which is simpler and safer than a manual `For` loop with an index.

```
For Each rule In myTransformer.Rules
    wl(rule.Name)
Next
```

## 4. Lifetime Management with `Using`
**This is the most critical VB.NET-specific pattern.** Most uCalc objects hold unmanaged resources and must be released to prevent memory leaks. While you can call [Release()](/Reference/uCalcBase/uCalc/Release) manually, the idiomatic VB.NET approach is to wrap object creation in a `Using` block. All major uCalc objects implement `IDisposable`, which guarantees that `Release()` will be called automatically when the object goes out of scope.

```
' The transformer 't' will be released automatically at the end of the block.
Using t = uc.NewTransformer()
    wl(t.Transform("input"))
End Using ' t.Release() is called here.
```
This is the VB.NET equivalent of the C++ RAII pattern using [Owned()](/Reference/uCalcBase/uCalc/Owned).

## 5. Implicit Conversions & Constructors
For convenience, several uCalc classes provide implicit conversions from `String`, allowing for more concise initialization.

*   **`uCalc.String`**: `Dim s As uCalc.String = "initial text"`
*   **`uCalc.Expression`**: `Dim expr As uCalc.Expression = "1 + 1"`
*   **`uCalc.Transformer`**: `t.Text = "input"` can be shortened to `t = "input"`.

The `Expression` and `String` classes also have constructors that accept a string, which provides a familiar VB.NET object creation pattern that implicitly uses the default `uCalc` instance.

```
' These two are equivalent, using the default uCalc instance.
Dim expr1 = uc.Parse("5 * 2")
Dim expr2 = New uCalc.Expression("5 * 2")
```

## 6. XML Literals
VB.NET's unique support for XML Literals provides a highly readable way to construct the complex strings often used in [Define](/Reference/uCalcBase/uCalc/Define) calls. Because XML can be multi-line and handles quotes automatically, it's an excellent way to define functions with embedded documentation or complex transformer rules.

```
Dim funcDef = <define>
                  Function: LogWithTimestamp(msg As String) =
                      '[' + Now() + '] ' + msg
              </define>.Value

' The .Value property extracts the inner text of the XML literal.
uc.Define(funcDef)
```

## 🆚 Comparative Analysis: Why uCalc in VB.NET?

While VB.NET is a powerful language, uCalc provides specialized capabilities not available natively:

*   **Runtime Parsing vs. `DataTable.Compute`**: The common .NET workaround for evaluating strings, `DataTable.Compute`, is slow, limited to simple arithmetic, and lacks features like custom functions or operators. uCalc is a high-performance, full-featured parsing engine.

*   **Dynamic Language Definition**: VB.NET is statically compiled. uCalc allows you to define new functions, operators, and even token syntax at **runtime**, enabling the creation of dynamic scripting environments and Domain-Specific Languages (DSLs) within your VB.NET application.

*   **Token-Aware Transformations**: VB.NET's `Regex` class is powerful for character-level patterns but struggles with nested structures and language context. uCalc's [Transformer](/Reference/uCalcBase/Transformer/Constructor) operates on tokens, making it inherently aware of code structure (parentheses, strings, comments), which is far more robust for code transformation and analysis.

**Examples:**

### Example ID: 815

**Description:** Core VB.NET idioms: `Using` for lifetime management, property syntax, and implicit string conversions.

**Code:**
```pseudocode
[VB]
' 1. Automatic resource management with 'Using'
Using u = New uCalc()
    ' 2. Property syntax for setting the description
    u.Description = "My VB.NET uCalc instance"
    wl("Description: ", u.Description)

    ' 3. Implicit string conversion for Transformer.Text
    New(uCalc::Transformer, t)
    t.Text = "Hello World" ' Standard assignment
    t = "Hello Again"    ' Implicit conversion assignment
    wl("Transformer Text: ", t.Text)
    wl("Transformer Text: ", t)
End Using
[/VB]
[NotVB]
// This example is meant for VB.NET only
wl("Description: My VB.NET uCalc instance")
wl("Transformer Text: Hello Again")
wl("Transformer Text: Hello Again")
[/NotVB]
```

**Output:**
```
Description: My VB.NET uCalc instance
Transformer Text: Hello Again
Transformer Text: Hello Again
```

---

---

## uCalc vs. Other Technologies - ID: 947
/doc/concepts/ucalc-vs.-other-technologies/

---

## Comparison with Regular Expressions - ID: 948
/doc/concepts/ucalc-vs.-other-technologies/comparison-with-regular-expressions/

**Description:** Explains the fundamental differences between uCalc's token-aware Transformer and traditional character-based Regular Expressions.

**Remarks:**

# ⚖️ uCalc Transformer vs. Regular Expressions

Regular Expressions (Regex) are an indispensable tool for pattern matching in raw, unstructured text. However, when working with structured or semi-structured data—such as source code, configuration files, or markup languages like HTML and XML—their character-based nature reveals significant limitations that can lead to fragile and unsafe code.

uCalc's [Transformer](/Reference/uCalcBase/Transformer/Constructor) offers a fundamentally different, **token-based** approach that is safer, more readable, and more powerful for these tasks. This topic explores the key distinctions.

---

## The Core Difference: Character-Aware vs. Token-Aware

This is the single most important concept to understand:

*   **Regex is character-aware**: It sees text as a flat, undifferentiated stream of characters.
*   **uCalc is token-aware**: It first runs a tokenizer (lexer) to see text as a structured sequence of meaningful units called **tokens** (words, numbers, string literals, operators, etc.).

This structural awareness prevents the most common and dangerous bugs associated with using regex for code manipulation.

### The Classic Refactoring Problem

Imagine you want to rename the variable `rate` to `annual_rate` in this line of code:

```pseudocode
rate = 0.05; // Current rate
print("The rate is: " + rate);
```

A simple regex find-and-replace for the word `\brate\b` would incorrectly change it *everywhere*, including inside the comment and the string literal, corrupting your code and output.

**The uCalc Solution**

Because the uCalc [Transformer](/Reference/uCalcBase/Transformer/Constructor) tokenizes the text first, it knows that `"The rate is: "` is a single, atomic string token and `// Current rate` is a whitespace token (provided you have defined it as such). By default, a rule to replace the **identifier** `rate` will not even look inside them, ensuring a safe and correct transformation.

```pseudocode
annual_rate = 0.05; // Current rate
print("The rate is: " + annual_rate);
```

This safety-by-default is a core architectural advantage.

---

## Comparison at a Glance

| Feature | Regular Expressions | uCalc Transformer |
| :--- | :--- | :--- |
| **Core Unit** | Character | Token (word, number, symbol) |
| **Safety** | 🔴 **Unsafe** for code; can corrupt string literals and comments. | 🟢 **Safe by default**; respects structural boundaries ([QuoteSensitive](/Reference/uCalcBase/Rule/QuoteSensitive), [BracketSensitive](/Reference/uCalcBase/Rule/BracketSensitive)). |
| **Readability** | 🔴 **Often cryptic** (e.g., `(?<=\s)\d+`). Difficult to maintain. | 🟢 **Readable** (e.g., [{@Number}](/Reference/Patterns/Matching-by-token-category/{@Number})). Self-documenting patterns. |
| **Nested Data** | 🔴 **Fails** on recursive structures like balanced parentheses. | 🟢 **Natively handles** nesting and recursion. |
| **Extensibility**| 🔴 **Fixed syntax** (`\d`, `\w`). | 🟢 **Dynamic syntax**. Define new token types at runtime via [Tokens.Add()](/Reference/uCalcBase/Tokens/Add). |
| **Backreferences**| 🔴 **Numeric** (`$1`, `\1`). Prone to indexing errors. | 🟢 **Named** (`{myVar}`). More readable and robust. |

---

## When is Regex Still the Right Tool?

Despite the uCalc [Transformer](/Reference/uCalcBase/Transformer/Constructor)'s advantages for structured data, regular expressions remain the superior tool for low-level, character-based pattern matching in unstructured text. uCalc acknowledges this by allowing you to embed raw regex directly inside a pattern when you need that level of control.

```pseudocode
// Match a variable that must be exactly three uppercase letters.
t.FromTo("{code:'[A-Z]{3}'}", "...");
```

This hybrid approach gives you the best of both worlds: the high-level structural awareness of the uCalc [Transformer](/Reference/uCalcBase/Transformer/Constructor) and the low-level precision of regex when you need it.

### Conclusion

Choose the right tool for the job. For searching arbitrary character streams, use regex. For safely and reliably parsing or transforming code, configuration, or any other structured data, uCalc's token-aware [Transformer](/Reference/uCalcBase/Transformer/Constructor) is the superior choice.

---

## Comparison with eval() and Scripting Engines - ID: 949
/doc/concepts/ucalc-vs.-other-technologies/comparison-with-eval-void-and-scripting-engines/

**Description:** Compares the uCalc engine to the `eval()` function and embedded scripting languages like Lua or Python, highlighting differences in security, performance, and extensibility.

**Remarks:**

# ⚖️ uCalc vs. `eval()` and Scripting Engines

For developers needing to execute dynamic code from a string, the built-in `eval()` function found in many scripting languages (like Python and JavaScript) is often the first tool they reach for. For more complex needs, embedding a full scripting engine like Lua, ChaiScript, or Python is a common solution. 

uCalc offers a powerful alternative that is more secure, often faster, and better integrated for tasks centered on expression evaluation and Domain-Specific Language (DSL) creation. This topic explores the key trade-offs.

---

## Comparison at a Glance

| Feature | `eval()` / Scripting Engines | uCalc Engine |
| :--- | :--- | :--- |
| **Security** | 🔴 **High Risk**. Can execute arbitrary code, accessing the OS. | 🟢 **Secure by Default**. Operates in a sandbox with no intrinsic OS access. |
| **Performance** | 🟡 **Slower in loops**. Typically re-parses expressions on every call. | 🟢 **High Performance**. Supports a "[Parse](/Reference/uCalcBase/uCalc/Parse)-once, [Evaluate](/Reference/uCalcBase/Expression/Evaluate)-many" pattern. |
| **Extensibility**| 🔴 **Fixed Syntax**. Language grammar is static. | 🟢 **Dynamic Syntax**. Define new functions and operators at runtime. |
| **Lazy Evaluation**| 🔴 **Not Supported** in simple `eval()`. | 🟢 **Supported** via the `ByExpr` modifier for custom control structures. |
| **Integration** | 🟡 **Heavyweight**. Often requires complex binding libraries and a full VM. | 🟢 **Lightweight**. A specialized component with a simple callback API for native code binding. |

---

## 1. 🛡️ Security: The Sandbox Advantage

This is the most critical difference. Functions like `eval()` are notoriously dangerous because they execute their input string with the full permissions of the application. An `eval()` call that processes unsanitized user input can lead to severe security vulnerabilities, as a malicious user could execute code to delete files, access the network, or exfiltrate data.

**The uCalc Solution**

The uCalc engine is a **secure sandbox**. An expression can **only** access the functions, operators, and variables that you have explicitly defined within its instance. It has no intrinsic ability to interact with the host operating system, which prevents code injection vulnerabilities and ensures that user-provided formulas can be evaluated safely. Any interaction with the outside world must be explicitly provided by you through a native [callback](/Reference/Concepts/Callback-mechanics).

## 2. ⚡ Performance: Parse-Once, Evaluate-Many

Simple `eval()` functions and most scripting interpreters re-parse the expression string on every single call. This is highly inefficient for calculations that are performed repeatedly, such as inside a loop.

**The uCalc Solution**

uCalc's architecture separates the expensive parsing step from the fast evaluation step. By calling [Parse()](/Reference/uCalcBase/uCalc/Parse) once before a loop and then calling [Evaluate()](/Reference/uCalcBase/Expression/Evaluate) repeatedly inside it, you can achieve execution speeds that approach native compiled code. This makes uCalc ideal for performance-critical applications like scientific simulations or real-time data processing.

## 3. 🔧 Extensibility: Building Your Own Language

A scripting engine provides a powerful but fixed grammar. You can define new functions within that language, but you cannot change the language's syntax itself—you cannot invent a new operator.

**The uCalc Solution**

uCalc's grammar is fully dynamic. Using [DefineFunction()](/Reference/uCalcBase/uCalc/DefineFunction) and [DefineOperator()](/Reference/uCalcBase/uCalc/DefineOperator), you can extend the engine's syntax at runtime. This allows you to create expressive, human-readable Domain-Specific Languages (DSLs) tailored to your application's needs, a capability that goes far beyond what a standard scripting engine offers.

## 4. 💤 Lazy Evaluation and Metaprogramming

Standard `eval()` functions are almost always eager, meaning all arguments are computed before a function is called. This prevents you from creating custom control structures (like conditional statements) where an argument should only be executed if a condition is met.

**The uCalc Solution**

uCalc supports **lazy evaluation** through the `ByExpr` parameter modifier. When used, an argument is passed not as a value, but as an unevaluated [Expression](/Reference/uCalcBase/Expression/Constructor) object. Your callback function can then decide when, or even if, to execute it. This elevates uCalc from a simple calculator to a lightweight language construction kit.

### Conclusion

uCalc is not a general-purpose replacement for a full scripting language like Lua or Python. Those are better choices when you need complex application logic, extensive libraries, and general-purpose programming constructs.

However, uCalc is the superior choice when your primary goal is to:
*   Safely evaluate mathematical, logical, or string-based expressions from user input.
*   Achieve high performance for repeated calculations in a loop.
*   Create a custom, human-readable Domain-Specific Language (DSL) embedded within your application.

---

## Comparison with Parser Generators (ANTLR, etc.) - ID: 950
/doc/concepts/ucalc-vs.-other-technologies/comparison-with-parser-generators--antlr,-etc./

**Description:** Compares uCalc's dynamic, runtime approach to language creation with the static, compile-time workflow of traditional parser generators like ANTLR.

**Remarks:**

# ⚖️ uCalc vs. Parser Generators (ANTLR, Flex/Bison)

For developers needing to build a parser for a custom language, traditional tools like ANTLR, Yacc/Bison, and Boost.Spirit are the industry standard. These are incredibly powerful **parser generators** that can create highly efficient parsers for virtually any language.

uCalc, while also a parser, operates on a fundamentally different philosophy. It is not a parser generator but an **embeddable, dynamic parsing engine**. This distinction has profound implications for workflow, flexibility, and use case.

---

## The Core Difference: Dynamic Runtime vs. Static Compile-Time

This is the single most important difference:

*   **Parser Generators (ANTLR, etc.)**: You define a language's grammar in a separate file (e.g., a `.g4` file). An external tool processes this file to **generate source code** for a lexer and parser in your target language (C#, C++, etc.). You then compile this generated code into your application. The grammar is **static** and fixed at compile-time.

*   **uCalc Engine**: You interact with an existing parsing engine through a programmatic API. You define and modify the grammar—including tokens, functions, and operators—by calling methods **at runtime**. The grammar is **dynamic** and can be changed while your application is running.

### Comparison at a Glance

| Feature | Parser Generators (ANTLR, etc.) | uCalc Engine |
| :--- | :--- | :--- |
| **Workflow** | Define grammar → Generate code → Compile | Write code that calls the uCalc API. | 
| **Extensibility**| 🔴 **Static**. Changes require modifying the grammar file and recompiling. | 🟢 **Dynamic**. Define new syntax at runtime with API calls. |
| **Integration** | 🟡 **Complex**. Involves an external toolchain and managing generated files. | 🟢 **Simple**. It's just a library/dependency. No build steps. |
| **Use Case** | Building full compilers or parsers for complex, static languages. | Embedded expression evaluation, dynamic DSLs, user-configurable syntax. |
| **Performance** | 🟢 **Very High**. Generates optimized, special-purpose parsers. | 🟢 **High**. Optimized for expression evaluation, especially with the parse-once model. |
| **Learning Curve**| 🔴 **Steep**. Requires learning grammar notation and the generator's specific workflow. | 🟡 **Moderate**. Requires learning the uCalc API. |

---

## 1. 🚀 Runtime Dynamism

This is uCalc's most significant advantage. With a parser generator, the language's syntax is frozen at compile time. To add a new keyword or operator, you must go through the entire generate-and-compile cycle.

**The uCalc Solution**

uCalc's grammar is fully mutable at runtime. Your application can:
*   Add new token definitions using [Tokens.Add()](/Reference/uCalcBase/Tokens/Add).
*   Create new functions with [DefineFunction()](/Reference/uCalcBase/uCalc/DefineFunction).
*   Invent new operators with custom precedence using [DefineOperator()](/Reference/uCalcBase/uCalc/DefineOperator).

This allows an application to adapt its own syntax on the fly, based on user configuration, different file dialects, or plugins. For more details, see the [Dynamic Syntax](/Tutorials/Beyond-the-Basics---What-Makes-uCalc-Special/Dynamic-Syntax) topic.

## 2. 🧩 Simplicity and Integration

Using a parser generator introduces an external dependency into your build process. You need to configure your build system to run the generator tool, and you must manage the generated source files, which should not be edited by hand. This adds complexity to your project.

**The uCalc Solution**

uCalc is simply a library. You add it as a dependency (e.g., via NuGet or vcpkg), and you interact with it entirely through its API. There is no code generation step and no external toolchain to manage. This results in a cleaner, more streamlined development workflow.

## When Are Parser Generators a Better Choice?

For all its advantages in dynamism, uCalc is not designed to replace tools like ANTLR for every task. A parser generator is the superior choice when:

*   **Building a Full Compiler**: If you are creating a new, general-purpose programming language, the power, performance, and rich ecosystem of a tool like ANTLR (including its tree-walking and visitor patterns) are essential.
*   **Parsing Complex, Static Grammars**: For parsing existing, well-defined, and complex languages like C++, Java, or SQL, a parser generator with a pre-existing grammar file is often the most robust solution.
*   **Maximum Performance is Critical**: Because a parser generator creates highly specialized code tailored to a specific grammar, the resulting parser is often slightly faster than a more general-purpose engine like uCalc.

### Conclusion

Choose **uCalc** when your primary need is for an embedded, runtime-configurable engine for **expression evaluation** or for creating a lightweight, **Domain-Specific Language (DSL)** where flexibility and ease of integration are paramount.

Choose a **parser generator** when you need to build a complete compiler or a high-performance parser for a complex, **statically-defined language**.

---

## Comparison with .NET's DataTable.Compute - ID: 951
/doc/concepts/ucalc-vs.-other-technologies/comparison-with-.net's-datatable.compute/

**Description:** Compares the high-performance, feature-rich uCalc engine with the limited and slow DataTable.Compute method in .NET.

**Remarks:**

# ⚖️ uCalc vs. .NET's DataTable.Compute

For .NET developers needing to evaluate a mathematical expression from a string without adding a third-party dependency, `System.Data.DataTable.Compute` often seems like a convenient, built-in solution. While it can work for the most trivial cases, it has critical limitations in performance and functionality that make it unsuitable for any serious application.

uCalc, as a purpose-built parsing engine, is designed to overcome all of these limitations. This topic provides a direct comparison.

---

## 1. ⚡ The Performance Trap: Re-Parsing on Every Call

The single biggest drawback of `DataTable.Compute` is that it **must parse the expression string from scratch on every single call**. This makes it catastrophically slow for any calculation that needs to be performed more than once, especially inside a loop.

**The uCalc Solution**

uCalc's architecture is built on the "**[Parse-Once, Evaluate-Many](/Tutorials/Getting-Started-The-Expression-Parser/Optimizing-Performance)**" pattern. You separate the computationally expensive parsing step from the extremely fast evaluation step. 

```csharp
// The DataTable.Compute approach - SLOW in a loop
var dt = new DataTable();
for (int i = 0; i < 1000; i++)
{
    // The string must be parsed on every iteration.
    var result = dt.Compute(i.ToString() + " * 2", string.Empty);
}
```

```pseudocode
// The uCalc approach - FAST in a loop
var x = uc.DefineVariable("x");

// 1. Parse the expression ONCE.
var expr = uc.Parse("x * 2");

for (int i = 0; i < 1000; i++)
{
    x.Value(i);
    // 2. Evaluate the pre-compiled object - extremely fast.
    var result = expr.Evaluate();
}
```

For any performance-critical application, this architectural difference makes uCalc the only viable choice.

---

## 2. 🧩 The Feature Gap: Simple Calculator vs. Full Language Engine

`DataTable.Compute` is not a true expression engine; it is a feature of a data-table component. Its capabilities are extremely limited.

| Feature | `DataTable.Compute` | uCalc Engine |
| :--- | :--- | :--- |
| **Custom Functions** | 🔴 No | 🟢 Yes ([DefineFunction()](/Reference/uCalcBase/uCalc/DefineFunction)) |
| **Custom Operators** | 🔴 No | 🟢 Yes ([DefineOperator()](/Reference/uCalcBase/uCalc/DefineOperator)) |
| **Rich Built-in Library** | 🟡 Limited (basic math and aggregates like `SUM`, `AVG`) | 🟢 Extensive (full trig, string manipulation, logic, etc.) |
| **Control Structures**| 🔴 No | 🟢 Yes (custom loops and conditionals via [ByExpr](/Tutorials/Beyond-the-Basics-What-Makes-uCalc-Special/Lazy-Evaluation-ByExpr)) |
| **Extensible Syntax** | 🔴 No | 🟢 Yes (custom tokens and transformers) |
| **Data Types** | 🟡 Limited (standard .NET primitives) | 🟢 Extensive (Complex numbers, pointers, user-defined types) |


`DataTable.Compute` can handle `5 * 2`, but it cannot be taught new tricks. uCalc is a complete, sandboxed language environment that you can extend and customize at runtime.

---

## Conclusion: When to Use Which

*   **Use `DataTable.Compute` when:** You need to perform a single, one-off, trivial arithmetic calculation and cannot add any external dependencies to your project.

*   **Use uCalc when:** You need any of the following:
    *   Performance for expressions evaluated in a loop.
    *   A rich library of built-in math and string functions.
    *   The ability to define custom functions or operators.
    *   Advanced control structures or lazy evaluation.
    *   A professional-grade, fully-featured parsing and evaluation engine.

---

## The uCalc Object Model - A High-Level Overview - ID: 976
/doc/concepts/the-ucalc-object-model---a-high-level-overview/

**Description:** A high-level guide to the key classes in the uCalc library and how they interact to provide parsing, evaluation, and transformation capabilities.

**Remarks:**

# 🏛️ The uCalc Object Model: A High-Level Overview

The uCalc library is more than just a collection of functions; it's a structured ecosystem of interconnected objects. Understanding this object model is key to leveraging the full power of the library, from high-performance expression evaluation to complex text transformation. This guide provides a high-level map of the core classes and their relationships.

## 1. 👑 The Core Engine: `uCalc` and `Item`

At the center of everything are two fundamental concepts:

*   **[uCalc](/Reference/uCalcBase/uCalc/Constructor)**: This is the main engine instance. Think of it as a self-contained, sandboxed environment. It acts as the primary **factory** for creating other objects and holds the complete **context** for all operations, including all defined symbols.
*   **[Item](/Reference/uCalcBase/Item/Constructor)**: This is the universal, polymorphic handle for any **symbol** defined within a `uCalc` instance. Whether it's a variable, a function, an operator, a data type, or even a transformer rule, it is represented internally as an `Item`. This unified model simplifies introspection and management.

## 2. 🚀 The Expression Parser System

This subsystem is responsible for evaluating mathematical and logical expressions.

*   **[uCalc](/Reference/uCalcBase/uCalc/Constructor)**: The starting point. You use its methods like [Parse](/Reference/uCalcBase/uCalc/Parse), [Eval](/Reference/uCalcBase/uCalc/Eval), and [EvalStr](/Reference/uCalcBase/uCalc/EvalStr) to process expression strings. It's also where you define symbols with [DefineFunction](/Reference/uCalcBase/uCalc/DefineFunction), [DefineVariable](/Reference/uCalcBase/uCalc/DefineVariable), etc.
*   **[Expression](/Reference/uCalcBase/Expression/Constructor)**: The result of a `Parse` operation. It represents a pre-compiled, reusable execution plan, which is the key to the "Parse-Once, Evaluate-Many" performance pattern.
*   **[Callback](/Reference/uCalcBase/Callback/Constructor)**: The bridge object. When you bind a custom function to your native code, your function receives a `Callback` object, which it uses to get arguments and return a value to the engine.

## 3. 🧠 The Text Transformation System

This subsystem provides powerful, token-aware find-and-replace capabilities.

*   **[Transformer](/Reference/uCalcBase/Transformer/Constructor)**: The rule-based engine for transforming text. It is more powerful and safer than regular expressions for structured data.
*   **[Tokens](/Reference/uCalcBase/Tokens/Constructor)**: A collection of lexical rules (regular expressions) that defines how the `Transformer` breaks raw text into meaningful tokens (words, numbers, symbols).
*   **[Rule](/Reference/uCalcBase/Rule/Constructor)**: A single, compiled pattern-to-action definition within a `Transformer`. You create rules with methods like [FromTo](/Reference/uCalcBase/Transformer/FromTo) and [Pattern](/Reference/uCalcBase/Transformer/Pattern).
*   **[Matches](/Reference/uCalcBase/Matches/Constructor)**: The collection of results from a `Find` or `Transform` operation. Each individual `Match` object contains the text, position, and the `Rule` that generated it.

## 4. 🧵 The Fluent String Library

*   **[uCalc.String](/Reference/uCalcBase/String/Constructor)**: A mutable, high-performance string class with a fluent, chainable API. It's designed for "one-liner" transformations and acts as a `StringBuilder`, lightweight `Transformer`, and list processor all in one. It operates using a "live view" model, where modifications to a substring directly affect the parent.

## 🗺️ Relationship Diagram

The following diagram illustrates the primary relationships and ownership within the object model:

```text
                   ┌─────────────────┐
                   │      uCalc      │ (The Engine/Context)
                   └─────────────────┘
                           │
         ┌─────────────────┴─────────────────┐
         │ (Owns/Manages)                    │
  ┌──────▼──────┐   ┌────────────┐   ┌──────▼─────┐
  │    Items    │   │ DataTypes  │   │   Tokens   │ (Symbol Tables)
  └─────────────┘   └────────────┘   └────────────┘
         │
┌────────┴─────────┐
│ (Creates)        │
▼                  ▼                  ▼
┌────────────┐   ┌─────────────┐   ┌────────────┐
│ Expression │   │ Transformer │   │ uCalc.String │
└────────────┘   └─────────────┘   └────────────┘
      │                 │
      │ (Evaluates)     │ (Owns)
      │                 │
      ▼                 ▼
┌──────────┐      ┌─────────┐
│ Callback │      │  Rules  │
└──────────┘      └─────────┘
                        │
                        │ (Produces)
                        │
                        ▼
                    ┌─────────┐
                    │ Matches │
                    └─────────┘
```

**Examples:**

### Example ID: 31

**Description:** Illustrates the core relationship between the uCalc engine, an Item (variable), and a compiled Expression.

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");
var Expression = "x^2 * 10"; // Replace this with your expression

wl("--- Efficient: Parse() once, then Evaluate() in a loop ---")
var ParsedExpr = uc.Parse(Expression);
for(double x = 1 to 10)
   VariableX.Value(x);
   wl(ParsedExpr.Evaluate())
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
--- Efficient: Parse() once, then Evaluate() in a loop ---
10
40
90
160
250
360
490
640
810
1000
```

---

### Example ID: 1335

**Description:** Demonstrates how a Transformer is created from a uCalc instance and used to apply Rules to text.

**Code:**
```pseudocode

// 1. The uCalc instance (uc) is the factory

// 2. Create a Transformer from the instance
NewUsing(uCalc::Transformer, t(uc))
  // 3. Define a Rule on the transformer
  t.FromTo("apple", "FRUIT");

  // 4. Process text and get the result
  wl(t.Transform("An apple a day."))
End Using;
```

**Output:**
```
An FRUIT a day.
```

---

### Example ID: 1336

**Description:** Shows the creation of a uCalc.String and its use of a fluent, token-aware API to modify text in-place.

**Code:**
```pseudocode
// 1. Create a uCalc.String with a parent uCalc instance
NewUsing(uCalc::String, s(uc, "The user is <admin>."))
  // 2. Use the fluent, token-aware API
  s.After("is").Between("<", ">").ToUpper();

  // 3. The original string is modified in-place
  wl(s)
End Using;
```

**Output:**
```
The user is <ADMIN>.
```

---

---

## The Complete uCalc Processing Pipeline - ID: 977
/doc/concepts/the-complete-ucalc-processing-pipeline/

**Description:** A comprehensive overview of uCalc's multi-stage processing model, detailing how text is transformed from a raw string into a final, evaluated result.

**Remarks:**

[revisit]
# ⚙️ The Complete uCalc Processing Pipeline

Understanding how uCalc processes a string from input to output is key to leveraging its full power. It's not a single, monolithic `eval()` function but a sophisticated, multi-stage pipeline where each step is configurable. This allows you to intercept and modify the process at various points, enabling the creation of custom syntax, domain-specific languages (DSLs), and complex transformation logic.

This topic provides a high-level overview of the entire end-to-end pipeline.

---

## 🌊 The Processing Flow

At its core, the uCalc engine follows a five-stage process. The diagram below illustrates the path an expression takes from a raw string to a final result.

**[ Expression Parser Pipeline ]**
```
Raw String ────► [ 1. Pre-Processing ] ────► Tokenizer ────► [ 2. Token Transformation ] ────► Token Stream ────► [ 3. Syntactic Analysis (Parsing) ] ────► Executable Plan (AST) ────► [ 4. Evaluation ] ────► Raw Result ────► [ 5. Post-Processing (Formatting) ] ────► Final String
```

**[ Transformer Pipeline ]**
```
Raw String ────► Tokenizer ────► Token Stream ────► [ 3. Syntactic Analysis (Matching) ] ────► Match Results ────► [ 4. Replacement ] ────► Final String
```
*Note: The [Transformer](/Reference/uCalcBase/Transformer/Constructor) follows a simplified pipeline that branches off after tokenization.*

Let's break down each stage for the expression parser.

### 1. Stage 1: Pre-Processing (`ExpressionTransformer`)

Before the parser even sees the individual tokens, the **entire raw string** is passed to the [ExpressionTransformer](/Reference/uCalcBase/uCalc/ExpressionTransformer). This is a meta-transformer that allows you to define high-level rewrite rules.

*   **Purpose**: To create syntactic sugar or transpile multi-word syntax into a format the standard parser can understand.
*   **Example**: Transforming a custom `100 USD to EUR` syntax into a standard function call like `ConvertCurrency(100, "USD", "EUR")`.

### 2. Stage 2: Lexical Analysis & Token Transformation

#### A. Tokenization (`Tokens`)
The string (either the original or the pre-processed version) is fed into the tokenizer, also known as a lexer. The lexer uses a set of regular-expression-based rules defined in a [Tokens](/Reference/uCalcBase/Tokens/Constructor) collection to break the string into a stream of meaningful units: numbers, identifiers, operators, string literals, etc.

*   **Purpose**: To convert a flat stream of characters into a structured stream of categorized symbols.

#### B. Token Transformation (`TokenTransformer`)
During tokenization, if the lexer finds a token that has been specially marked with `TokenType::TokenTransform`, it pauses and sends that single token to the [TokenTransformer](/Reference/uCalcBase/uCalc/TokenTransformer).

*   **Purpose**: To implement new low-level syntax for literals. This is a surgical, high-performance transformation.
*   **Example**: Transforming a custom C-style hexadecimal literal `0xFF` into an expression the engine understands, like `BaseConvert("FF", 16)`.

### 3. Stage 3: Syntactic Analysis (`Parse`)

The final stream of tokens is fed into the syntactic analyzer, or parser. The parser uses the grammar rules (operator precedence, function signatures) to build a hierarchical structure called an **Abstract Syntax Tree (AST)**. This tree represents the expression's logic and order of operations.

*   **Purpose**: To create a machine-readable, executable plan from the token stream.
*   **Output**: This stage is represented by the [Parse](/Reference/uCalcBase/uCalc/Parse) method and results in a compiled [Expression](/Reference/uCalcBase/Expression/Constructor) object.

### 4. Stage 4: Evaluation (`Evaluate` / `Execute`)

The AST contained within the [Expression](/Reference/uCalcBase/Expression/Constructor) object is executed. The engine walks the tree, performing the specified calculations, calling functions, and retrieving variable values.

*   **Purpose**: To compute the final value of the expression.
*   **Trigger**: This stage is initiated by methods like [Evaluate](/Reference/uCalcBase/Expression/Evaluate) (for getting a value) or [Execute](/Reference/uCalcBase/Expression/Execute) (for side effects).

### 5. Stage 5: Post-Processing (`Format`)

If the evaluation was triggered by a method that returns a string (like [EvalStr](/Reference/uCalcBase/uCalc/EvalStr) or [EvaluateStr](/Reference/uCalcBase/Expression/EvaluateStr)), the raw string result is passed through a final, optional formatting pipeline.

*   **Purpose**: To apply consistent, declarative formatting to output values.
*   **Example**: Automatically formatting all `Double` results as currency (e.g., `123.45` becomes `$123.45`).
*   **Configuration**: This stage is controlled by rules defined with the [Format](/Reference/uCalcBase/uCalc/Format) method.

---
## 💡 Why uCalc? (Comparative Analysis)

Most evaluation tools are a "black box". You provide a string and get a result.
*   **`eval()` in Scripting Languages**: A single, non-configurable step.
*   **Regular Expressions**: Primarily focused on a single stage: pattern matching.

uCalc's key advantage is its **transparent and configurable pipeline**. It gives you hooks at every major stage of processing, transforming it from a simple evaluator into a powerful language construction toolkit. You can control high-level syntax, low-level literals, and final output formatting, all within a single, cohesive engine.

**Examples:**

---

## State, Scoping, and Context Management - ID: 978
/doc/concepts/state,-scoping,-and-context-management/

**Description:** An overview of how uCalc manages state, isolation, and context through instances, the default instance stack, and hierarchical parsing.

**Remarks:**

# ⚙️ State, Scoping, and Context Management

The uCalc engine is not a collection of static functions; it is a stateful, object-oriented system. Understanding how it manages state, scope, and context is crucial for building robust, scalable, and memory-safe applications. This topic provides a high-level overview of the core architectural concepts that govern the uCalc environment.

Mastering these concepts will allow you to leverage the full power of the library, from creating isolated sandboxes for parallel processing to building sophisticated, multi-layered parsers.

---

## 1. 📦 The `uCalc` Instance: An Isolated Sandbox

Each instance of the [`uCalc`](/Reference/uCalcBase/uCalc/Constructor) class is a self-contained "world." It maintains its own isolated symbol table, which includes all defined [variables](/Tutorials/Getting-Started-The-Expression-Parser/Working-with-Variables), [functions](/Tutorials/Getting-Started-The-Expression-Parser/Creating-Custom-Functions), and [operators](/Tutorials/Beyond-the-Basics-What-Makes-uCalc-Special/Dynamic-Syntax). 

This instance-based architecture ensures that different parser configurations do not interfere with each other, making it ideal for applications with plugins or multiple concurrent tasks. For details on managing the memory of these instances, see the [Managing Parser Instances & Lifetime](/Tutorials/Advanced-Integration/Managing-Parser-Instances-Lifetime) tutorial.

---

## 2. 🌍 The Default Instance Stack: A Scoped Global Context

For convenience, uCalc provides a globally accessible context via the static [`DefaultInstance`](/Reference/uCalcBase/uCalc/DefaultInstance) property. However, this is not a single, rigid global object; it is a **LIFO (Last-In, First-Out) stack**.

*   You can push any `uCalc` instance onto the stack using [`IsDefault(true)`](/Reference/uCalcBase/uCalc/IsDefault), making it the new "ambient" context.
*   When that instance is released or popped from the stack (e.g., via `IsDefault(false)`), the previous default instance is automatically restored.

This provides the benefits of a global singleton without the rigidity, enabling temporary, scoped overrides for different parts of an application.

---

## 3. 🧵 Thread Safety: Clone for Parallelism

*   **Core Rule**: A single `uCalc` instance is **not thread-safe**. Do not share one instance across multiple threads without external locking (which is an anti-pattern).
*   **The Solution**: The "One Instance Per Thread" pattern is the recommended approach. You create a master, pre-configured instance at startup, and for each new thread or task, you create a local copy using the highly optimized [`Clone()`](/Reference/uCalcBase/uCalc/Clone) method.
*   **Thread-Local Default**: The default instance stack is managed using thread-local storage. This means each thread has its **own independent default instance stack**, preventing cross-thread interference automatically.

For a detailed explanation, see the [Thread safety](/Concepts/Thread-safety) topic.

---

## 4. 🌳 Hierarchical Scopes: Parsing and Data

In addition to instance-level isolation, uCalc provides two powerful mechanisms for managing nested scopes within a single operation.

#### A. Syntactic Scoping (`LocalTransformer`)
A `Rule` can have its own [`LocalTransformer`](/Reference/uCalcBase/Rule/LocalTransformer), which is a nested [`Transformer`](/Reference/uCalcBase/Transformer/Constructor) that operates *only* on the text matched by its parent rule. This is the primary mechanism for hierarchical parsing of structured languages like HTML or XML. See the [Hierarchical Parsing (LocalTransformer)](/Tutorials/Beyond-the-Basics-What-Makes-uCalc-Special/Hierarchical-Parsing-LocalTransformer) topic for more details.

#### B. Data Scoping (Live Views)
The [`uCalc.String`](/Reference/uCalcBase/String/Constructor) class uses "live views." Methods like [`After()`](/Reference/uCalcBase/String/After), [`Before()`](/Reference/uCalcBase/String/Before), and [`Between()`](/Reference/uCalcBase/String/Between) return new `uCalc.String` objects that are modifiable windows into the parent. Any change to a child view directly affects the parent, enabling powerful, in-place editing of sub-sections. See [Chaining Fluent Operations](/Tutorials/The-uCalc.String-Library/Chaining-Fluent-Operations).

---

## ⚖️ Comparative Analysis

uCalc's state and context management model provides distinct advantages over common paradigms:

*   **vs. Global Singletons**: uCalc's stack-based default is safer and more flexible for modular applications than a typical static singleton, as it allows for temporary, scoped overrides.
*   **vs. Dependency Injection**: While DI is a powerful pattern, uCalc's default instance provides a simpler "ambient context" model that can reduce boilerplate for ubiquitous components like a parser engine.
*   **vs. Manual Substring Manipulation**: The `LocalTransformer` and live views automate complex scoping and coordinate-mapping tasks that would require verbose, error-prone manual implementation with standard string and regex libraries.

---

## Reference - ID: 662
/doc/reference/

---

## Patterns - ID: 750
/doc/reference/patterns/

---

## Introduction - ID: 751
/doc/reference/patterns/introduction/

---

## Syntax Definitions - ID: 763
/doc/reference/patterns/introduction/syntax-definitions/

**Description:** Defines the recognition rules -- using literals, variable types, or complex syntax -- that the parser uses to identify and process input tokens.

**Remarks:**

uCalc Patterns provide a high-level, token-based syntax for defining search criteria and text transformations. Unlike traditional string searches that match exact characters, or Regular Expressions (Regex) that rely on complex character-level syntax, uCalc patterns operate primarily on **Tokens** (words, numbers, symbols). This approach allows for more readable definitions that naturally respect word boundaries and structure.

A pattern string is the fundamental argument passed to methods such as `Transformer.Pattern()` and `Transformer.FromTo()`. These patterns define the criteria for `Transformer.Find()` and `Transformer.Transform()` operations.

#### Key Concepts & Syntax

| Syntax Element | Description | Example |
| :--- | :--- | :--- |
| **Anchors** | Literal text that must exist in the source string. | `Error Code:` |
| **Variables** | Named placeholders enclosed in curly braces. Captures variable content. | `{ErrorCode}` |
| **Alternatives** | Vertical bars inside curly braces denote "OR" logic. | `{ High | Medium | Low }` |
| **Optionals** | Square brackets denote text that may or may not exist. | `[Detailed] Report` |
| **Backreferences** | Reusing a variable name enforces equality. | `<{tag}>...</{tag}>` |
| **Token Constraints** | Colon followed by a number limits the capture length. Can be named or anonymous. | `{word:4}` (named)<br>`{4}` (anonymous) captures exactly 4 tokens |
| **Quoted Text** | Captures an entire block of quoted text as a single unit using `{@String}` or `{@s}`. | `Test {@String}` matches `Test 'foo'` or `Test "bar"` |
| **RegEx Embedding** | Single quotes inside curly braces allow raw Regex. Can be named or anonymous. | `{MyRegex:'[0-9]+'}` (named)<br>`{'[0-9]+'}` (anonymous) |

#### Crucial Syntax Rules

1.  **Variable Naming & Spacing:**
    To assign a variable name to a group, the name must immediately follow the opening curly brace **without spaces**.
    * **Correct:** `{Type: Error | Warning}` captures `Error` or `Warning` into the variable `Type`.
    * **Incorrect:** `{ Type: Error | Warning}` matches the literal text `Type: Error` OR `Warning`. It does not create a variable named `Type`.

2.  **Escaping Special Characters:**
    Characters like `[` and `{` have special meaning. To match them literally, enclose them in quotes.
    * *Example:* `['['{timestamp}']']` defines an **optional** section (outer brackets) containing a **literal** opening bracket (quoted `'['`), a variable, and a **literal** closing bracket.

#### Handling Quoted Text (`{@String}`)

By default, uCalc is `QuoteSensitive`, meaning it treats a block of text enclosed in quotes (e.g., `'hello world'` or `"hello world"`) as a single token. The `{@String}` method (or shortcut `{@s}`) allows you to explicitly capture these blocks.

* **Syntax:** `{@String}` or `{@s}` (`string` and `s` are case-insensitive).
* **Variable Assignment:** Add a colon followed by the name (no spaces). E.g., `{@s:MyText}`.
* **Replacement Access:**
    * `{MyText}` or `{MyText(1)}`: Returns the content *inside* the quotes.
    * `{MyText(0)}`: Returns the content including the surrounding quotes.

#### Why uCalc? (Comparative Analysis)

* **vs. Regular Expressions (Regex):**
    * **Readability:** Regex is often described as "write-once, read-never" due to its dense, cryptic syntax (e.g., `(?<=\s)\d+(?=\s))`. uCalc patterns use human-readable tokens or methods (e.g., `{@Number}`).
    * **Tokenization:** Regex requires explicit boundaries (e.g., `\bword\b`). uCalc variables like `{x}` automatically respect token boundaries, preventing partial matches within words.
    * **Backreferences:** Matching an opening tag to a closing tag in Regex (e.g., `<(\w+)>.*<\/\1>`) is fragile and complex. In uCalc, simply reusing the variable name `<{tag}>...<{/tag}>` handles the logic automatically.
* **vs. Native Code (C#/C++):**
    * **Dynamic:** uCalc patterns can be defined and modified at runtime, whereas native parsing logic is often hard-coded and requires recompilation.
* **vs. AI (LLMs):**
    * **Deterministic:** uCalc patterns provide 100% deterministic matching. An LLM might hallucinate a match or miss a pattern based on probability; uCalc will always find exactly what is defined.


**Examples:**

### Example ID: 173

**Description:** Pattern: Simple Variable Capture

**Code:**
```pseudocode
var t = uc.NewTransformer();
t = "Here is the temperature: 98.6 F";

// Define the pattern first
t.Pattern("Temperature: {temp} F");

// Then execute the search
t.Find();

wl(t.@Matches()[0][cpp].@Text()[/cpp])
```

**Output:**
```
temperature: 98.6 F
```

---

### Example ID: 174

**Description:** Converting from Celsius to Fahrenheit with the Transformer

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Define the pattern first
t.FromTo("Temperature: {temp} C", "temperature: {@Eval: Double(temp) * 1.8 + 32} F");

// Perform the Transform() operation
wl(t.Transform("Here is the temperature: 22.5 C"))
```

**Output:**
```
Here is the temperature: 72.5 F
```

---

### Example ID: 191

**Description:** More concurrent patterns

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.Pattern("This {etc} a");
t.Pattern("{@String}");
t.Pattern("{ big | small }");
t.Pattern("Only {words:2}");

wl(t.Filter("This is just a small Test to see 'how' patterns work. Only a test!").@Matches().@Text())
```

**Output:**
```
This is just a
small
'how'
Only a test
```

---

### Example ID: 199

**Description:** Using the same pattern variable multiple times in a pattern

**Code:**
```pseudocode
var t = uc.NewTransformer();

// When a variable is used multiple times in a pattern,
// such as {tag} in this case, the matching text must be the same

t.FromTo("<{tag}> {words:2} {more} </{tag}>",
"tag={tag}, 2 words={words}, text={more}");

wl(t.Transform("<div>abc xyz more words<b>bold</b></div>").@Text())
```

**Output:**
```
tag=div, 2 words=abc xyz, text=more words<b>bold</b>
```

---

### Example ID: 197

**Description:** Optional part

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a [simple] test", "<{@Self}>");

wl(t.Transform("Is this a simple test, or a hard test, or just a test?"))
```

**Output:**
```
Is this <a simple test>, or a hard test, or just <a test>?
```

---

### Example ID: 224

**Description:** A simple "Hello World" transformation demonstrating variable capture.

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Define a rule to swap the name into a greeting
t.FromTo("Hello {name}", "Greetings, {name}!");
wl(t.Transform("Hello World"))
```

**Output:**
```
Greetings, World!
```

---

---

## Whitespace - ID: 766
/doc/reference/patterns/introduction/whitespace/

**Description:** Whitespace behavior

**Remarks:**

In uCalc, **whitespace (spaces and tabs) is ignored by default**. This means `A + B` matches `A+B` or `A   +   B`.

**Important Distinction:** unlike many other languages, uCalc defines **Newlines** by default as *Statement Separators*, not generic whitespace.

* **Spaces/Tabs:** Ignored/Skipped by default. You can change this behavior using the `WhitespaceSensitive` property or the `$` variable directive.
* **Newlines:** Treated as a "stop" or "separator" (like a semicolon `;` in C#). To treat them as spaces, you must redefine the token type.

#### Key Concepts

| Concept | Behavior | Example |
| :--- | :--- | :--- |
| **Default (Insensitive)** | Spaces in the pattern match *any amount* of horizontal whitespace (including none). | `Key : Value` matches `Key:Value` and `Key   :   Value` |
| **Newline Behavior** | Newlines separate statements. By default they are *not* consumed by standard space characters in a pattern. | `A B` matches `A B` but **not** `A \n B` (unless configured). |
| **{@Whitespace}** | Explicitly captures a block of whitespace into a variable. | `{@Whitespace}` captures whitespace characters such as spaces and tabs. |
| **WhitespaceSensitive** | If set to `True`, block of whitespace in your pattern matches exactly one token in the source. | `A B` matches `A B` but fails on `A  B`. |

#### Why uCalc? (Comparative Analysis)

* **vs. Regular Expressions:**
    * **Readability:** In Regex, handling variable spacing requires cluttering your pattern with `\s*`. uCalc handles the "flexibility" automatically.
    * **Structure:** uCalc distinguishes between "formatting" (spaces) and "structure" (newlines), making it easier to parse line-based data formats (like CSV or Config files) without accidental matches across lines.
    * **Configurability:** It's easy to reconfigure newlines to behave as whitespace with `t.Tokens["_token_newline"].TypeOfToken = TokenType::Whitespace;`, for dealing with XML or HTML.

**Examples:**

### Example ID: 189

**Description:** Whitespace

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("Hello World", "<{@Self}>");
wl(t.Transform("Hello World. HelloWorld. Hello     World. Hello, World."))
```

**Output:**
```
<Hello World>. HelloWorld. <Hello     World>. Hello, World.
```

---

### Example ID: 142

**Description:** WhitespaceSensitive()

**Code:**
```pseudocode
var t = uc.NewTransformer();
var Text = "This is a test.";
var p = t.FromTo("This {words:3}", "[{words}]");

wl("Input: ", Text)
wl("Pattern: ", p.@Pattern())
wl("")

wl("3 captured tokens are in brackets")
wl("")

wl("WhitespaceSensitive = ", bool(t.@DefaultRuleSet().@WhitespaceSensitive()))
wl(t.Transform(Text))
wl("")

t.@DefaultRuleSet().@WhitespaceSensitive(true);
wl("WhitespaceSensitive = ", bool(t.@DefaultRuleSet().@WhitespaceSensitive()))
wl(t.Transform(Text))

```

**Output:**
```
Input: This is a test.
Pattern: This {words:3}

3 captured tokens are in brackets

WhitespaceSensitive = False
[is a test].

WhitespaceSensitive = True
[ is ]a test.
```

---

### Example ID: 155

**Description:** Transformer: Matching by tokens vs match by character; also whitespace sensitivity

**Code:**
```pseudocode
// This examples shows the default match by
// token mode, as well as how to reconfigure
// it in order to do match by character
// along with a whitespace variation

var t = uc.NewTransformer();
var txt = "This is an island test, I said.";
t.FromTo("is", "<is>");

wl(t.Transform(txt))
wl("")

t.@Tokens().@Description("Match by character");
t.@Tokens().Add("."); // This overrides existing tokens
t.FromTo("is", "<is>");
wl(t.@Tokens().@Description())
wl(t.Transform(txt))
wl("")

// Note: whitespace sensitivity is off by default
// Whitespace token is re-introduced
// (after being overridden in the previous Token Add())
t.@Tokens().@Description("By char + whitespace ignored");
t.@Tokens().Add("[\\t\\v ]+", TokenType::Whitespace);
t.FromTo("is", "<{@Self}>");
wl(t.@Tokens().@Description())
wl(t.Transform(txt))
```

**Output:**
```
This <is> an island test, I said.

Match by character
Th<is> <is> an <is>land test, I said.

By char + whitespace ignored
Th<is> <is> an <is>land test, <I s>aid.
```

---

### Example ID: 220

**Description:** Change newline from statement separator to whitespace

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.Str([verbatim]
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
[/verbatim]);

t.Pattern("<div>{body}</div>");

wl("Newline as statement separator (default)")
wl("----------------------------------------")
wl(t.Find().@Matches().@Text())
wl("")

wl("Newline as whitespace")
wl("---------------------")
t.@Tokens()["_token_newline"].@TypeOfToken(TokenType::Whitespace);
wl(t.Find().@Matches().@Text())
```

**Output:**
```
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>

Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
```

---

### Example ID: 221

**Description:** Change newline from statement separator to whitespace using TypeOfToken

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.Str([verbatim]
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
[/verbatim]);

t.Pattern("<div>{body}</div>");
var NewLineToken = t.@Tokens()["_token_newline"];

wl("Newline as statement separator (default)")
wl("----------------------------------------")
wl(t.Find().@Matches().@Text())
wl("")

wl("Newline as whitespace")
wl("---------------------")
NewLineToken.@TypeOfToken(TokenType::Whitespace);
wl(t.Find().@Matches().@Text())
```

**Output:**
```
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>

Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
```

---

### Example ID: 175

**Description:** Turn new line into whitespace with Tokens.Add

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("<{tag}>{code}</{tag}>", "[{tag}]{code}[/{tag}]");
var MyStr = [verbatim]<div>Single line</div>
<div>Line 1
Line 2
Line 3
Line 4</div>[/verbatim];

wl("New line as statement separator (default)")
wl("")
wl(t.Transform(MyStr).@Text())
wl("")

wl("New line as whitespace")
wl("")
t.@Tokens().Add([c]"[\\r\\n]+"[/c][vb]"[\r\n]+"[/vb], TokenType::Whitespace);
wl(t.Transform(MyStr).@Text())



```

**Output:**
```
New line as statement separator (default)

[div]Single line[/div]
<div>Line 1
Line 2
Line 3
Line 4</div>

New line as whitespace

[div]Single line[/div]
[div]Line 1
Line 2
Line 3
Line 4[/div]
```

---

### Example ID: 223

**Description:** Using {@Whitespace} and {@Exec} to Count Indentation (for Python or YAML-like text)

**Code:**
```pseudocode
// Using {@Whitespace} to Count Indentation
// A common use case for parsing structured text (like Python or YAML)
// is capturing the exact whitespace at the start of a line.

uc.DefineVariable("IndentLen");

var t = uc.NewTransformer();
t.@Text("    Item 1"); // Indented by 4 spaces

// Capture the leading whitespace into 'w' and evaluate its length
t.FromTo("{@Whitespace:w} Item {id}", "<{@Self}>{@Exec: IndentLen = Length(w)}");
t.Transform();
// We can now analyze the captured whitespace
wl("Indentation length: ", uc.EvalStr("IndentLen"))
```

**Output:**
```
Indentation length: 4
```

---

---

## Multi-Pattern Search - ID: 764
/doc/reference/patterns/introduction/multi-pattern-search/

**Description:** Simultaneously evaluating multiple distinct search patterns within a single input stream

**Remarks:**

Standard string searching typically looks for one specific sequence of characters at a time. uCalc's **Concurrent Patterns** allow you to define multiple distinct patterns and search for **all of them simultaneously** in a single pass through the text.

**Precedence & Order Rules:**
1.  **Text Position Priority:** Matches are returned in the order they appear in the source string.
2.  **Definition Priority (LIFO):** If multiple patterns match starting at the *same* position (e.g., overlapping anchors), the **most recently defined** pattern takes precedence.
3.  **Fallback Mechanism:** If the highest-priority pattern fails to match the subsequent tokens, uCalc automatically backtracks and attempts the next most recently defined pattern that shares the same start anchor.

This architecture makes `Concurrent Patterns` ideal for tokenizers, lexers, or keyword highlighters where different definitions (like keywords vs. identifiers) might compete for the same text.

### Comparative Analysis: Why uCalc?

* **vs. Regex:**
    * **Parallelism:** To search for multiple distinct Regex patterns simultaneously (e.g., a date OR an email OR a specific keyword), you typically have to join them with `|` into a massive, hard-to-read "super-pattern" or run multiple passes. uCalc lets you add them as separate, clean lines of code that run in one efficient pass.
    * **Prioritization:** Managing precedence in a giant Regex alternation `(PatternA|PatternB)` relies strictly on left-to-right ordering and can be tricky to adjust dynamically. uCalc handles precedence via definition order, allowing runtime re-prioritization.
* **vs. Native Code (String.IndexOf):**
    * **Single Pass:** Native searches like `IndexOf` generally find one string. Finding multiple different strings requires a loop and complex index management to ensure you don't count the same text twice or process overlaps incorrectly. uCalc handles the cursor advancement automatically.

**Examples:**

### Example ID: 190

**Description:** Searching for two different words in parallel.

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Define concurrent patterns
t.FromTo("Mango", "[Fruit]");
t.FromTo("Car", "[Vehicle]");

wl(t.Transform("I have a Mango and a Car.")) 

```

**Output:**
```
I have a [Fruit] and a [Vehicle].
```

---

### Example ID: 228

**Description:** A simple Lexer/Tokenizer that categorizes content into numbers, operators, or keywords.

**Code:**
```pseudocode
// Note how the definition order matters if patterns overlap (though here they are distinct).
var t = uc.NewTransformer();

// Define patterns for a simple math language
t.FromTo("{d: {@Number}}", "[NUM:{d}]");
t.FromTo("{op: + | - | * | / }", "[OP:{op}]");
t.FromTo("print", "[CMD:PRINT]"); // Specific keyword

var code = "print 10 + 20";
wl(t.Transform(code))
```

**Output:**
```
[CMD:PRINT] [NUM:10] [OP:+] [NUM:20]
```

---

### Example ID: 229

**Description:** Testing the "Last In, First Out" precedence rule with overlapping anchors.

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Priority Test: All start with "An"
// 1. Defined first (lowest priority for same start)
t.FromTo("An {item}", "Match1: {item}"); 

// 2. Defined second
t.FromTo("An {item}.", "Match2: {item}");

// 3. Defined last (Highest priority for same start)
t.FromTo("An orange.", "Match3: orange");

// Input text
var txt = "An orange. An apple. An elephant.";

// "An orange." matches Rule 3 (Specific, defined last)
// "An apple." fails Rule 3, matches Rule 2 (Ending in dot)
// If input is "An elephant" (no dot), it falls back to Rule 1.

wl(t.Transform("An orange."))   // Match3: Orange
wl(t.Transform("An apple."))    // Match2: apple
wl(t.Transform("An elephant"))  // Match1: elephant
```

**Output:**
```
Match3: orange
Match2: apple
Match1: elephant
```

---

### Example ID: 191

**Description:** More concurrent patterns

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.Pattern("This {etc} a");
t.Pattern("{@String}");
t.Pattern("{ big | small }");
t.Pattern("Only {words:2}");

wl(t.Filter("This is just a small Test to see 'how' patterns work. Only a test!").@Matches().@Text())
```

**Output:**
```
This is just a
small
'how'
Only a test
```

---

### Example ID: 192

**Description:** Order of concurrent patterns

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Note: Since the patterns start the same,
//       the order in which they're defined matters.
t.FromTo("An {item}", "<{@Self}>");
t.FromTo("An {item}.", "[{@Self}]");
t.FromTo("An {item:2}.", "({@Self})");
t.FromTo("An orange.", "{{@Self}}");

wl(t.Transform("An apple. An orange. An elephant."))
wl(t.Transform("An angry bear. An extremely big dog!"))
```

**Output:**
```
[An apple.] {An orange.} [An elephant.]
(An angry bear.) <An extremely big dog!>
```

---

---

## Variables and Anchors - ID: 767
/doc/reference/patterns/introduction/variables-and-anchors/

**Remarks:**

uCalc patterns are constructed using two fundamental building blocks: **Anchors** and **Variables**. While effective patterns often combine both to define structure and capture data, a valid pattern may consist of **only** anchors, **only** variables, or a mixture of both.

* **Anchors (Literals):** Text that *must* appear in the source string.
    * *Example:* In the pattern `Code: {val}`, the text `Code:` serves as the anchor. A pattern like `Error` consists solely of an anchor.
    * *Tokenization Note:* Because uCalc is token-based, a sequence like `Code:` actually represents two distinct anchors: `Code` and `:`. Unless `WhitespaceSensitive` is explicitly enabled, `Code:` will match both `Code:` and `Code    :` equally.
* **Variables (Captures):** Named placeholders enclosed in curly braces `{...}`.
    * *Example:* In the pattern `Code: {val}`, the variable `{val}` captures the dynamic content immediately following the anchors.
    * *Pure Variable Patterns:* Patterns can be purely dynamic. For instance, `{mytoken:1}` captures exactly one token of any kind, while `{groupA:2}{groupB:3}` captures 2 tokens followed by 3 tokens.
    * *Stop Condition:* An unconstrained variable captures content until:
        1.  The **Next Anchor** defined in the pattern is found.
        2.  The **End of the String** is reached.
        3.  A **Statement Separator** is encountered (e.g., a newline or semicolon).
        * *Note:* For the default list of statement separators, see the topic **Matching by token category -> Introduction**.
        * *Customizing Separators:* If you need newlines to be treated as whitespace rather than separators, you can modify the token definitions. (See the **Whitespace** topic for details on releasing tokens like `_token_newline` or redefining them).

**Escaping Characters:**
Because `{` and `}` are reserved for variable definitions, if you need to match them as literal anchors, you must enclose them in single quotes.
* **Correct:** `func '{' {body} '}'` (Matches `func { ... }`)
* **Incorrect:** `func { {body} }` (This does not generate a syntax error, but it fails to capture literal braces. Instead, it interprets the inner structure as a variable definition or nested expression, leading to unexpected matching behavior.)

### Comparative Analysis: Why uCalc?

* **vs. Regex (Named Groups):**
    * **Simplicity:** In Regex, defining a named capture and an anchor requires complex syntax escaping: `Code:\s*(?<val>.*)`. In uCalc, it is simply `Code: {val}`.
    * **Implicit Boundaries:** Regex is greedy by default. uCalc variables are "smart-lazy"—they automatically stop at the next anchor or statement separator without requiring complex look-ahead assertions.
* **vs. String.Split (Native Code):**
    * **Structure:** Using `Split(':')` relies on array indices (`parts[1]`). uCalc Variables preserve context and allow you to access data by **Name** (e.g., referencing `{val}` in replacements or callbacks) rather than fragile numeric indices.

**Examples:**

### Example ID: 193

**Description:** Variables and anchors

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("is {etc} see", "({@Self})");
wl(t.Transform("This is a test to see how anchors/variables work"))
```

**Output:**
```
This (is a test to see) how anchors/variables work
```

---

### Example ID: 194

**Description:** More on variables and anchors

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Variables are {etc} and {ch}
// Anchors are "This", either "a small" or "an easy", and "Test"

t.FromTo("This {etc} {ch: a small | an easy } Test", "<{etc}> ({ch}) experiment");
wl(t.Transform("This is such an easy test."))
```

**Output:**
```
<is such> (an easy) experiment.
```

---

### Example ID: 199

**Description:** Using the same pattern variable multiple times in a pattern

**Code:**
```pseudocode
var t = uc.NewTransformer();

// When a variable is used multiple times in a pattern,
// such as {tag} in this case, the matching text must be the same

t.FromTo("<{tag}> {words:2} {more} </{tag}>",
"tag={tag}, 2 words={words}, text={more}");

wl(t.Transform("<div>abc xyz more words<b>bold</b></div>").@Text())
```

**Output:**
```
tag=div, 2 words=abc xyz, text=more words<b>bold</b>
```

---

### Example ID: 218

**Description:** Test: Complex Nesting & Backreferences

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("Start A ( 1 2 3 ) End A ... Start B ( 9 ) End B");

// {id} captures "A". {content} captures the block.
// The final {id} MUST match the first {id} ("A" == "A").
// If the text was "Start A ... End B", this pattern would NOT match.
t.Pattern("Start {id} ( {content} ) End {id:1}");

// +++ w/o 1 in {id:1} it tries to capture more than one token at
// position.  Investigate if it should logically be possible without 1

t.Find();
wl("Matches: ", t.@Matches().Count())
wl(t.@Matches().@Text())
```

**Output:**
```
Matches: 2
Start A ( 1 2 3 ) End A
Start B ( 9 ) End B
```

---

### Example ID: 219

**Description:** Test: Complex Nesting & Backreferences using XML-style tags.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<section> <item> A </item> </section>");

// {tag} captures "section". {content} captures the inner content.
// The closing </{tag}> MUST match the opening <{tag}>.
t.Pattern("<{tag}> {content} </{tag}>");

wl(t.Find().@Matches().@Text())
// This will match the outer <section> block.
// If the text was "<section> ... </div >", it would NOT match.

wl("-----")
t.Str([verbatim]
<br><section> <item> A </item> </section>
<br><br><div> <item> A b c </item> </div>
<br> <div> <item> <div>x y z</div> </item> </div>
[/verbatim]);
wl(t.Find().@Matches().@Text())
```

**Output:**
```
<section> <item> A </item> </section>
-----
<section> <item> A </item> </section>
<div> <item> A b c </item> </div>
<div> <item> <div>x y z</div> </item> </div>
```

---

### Example ID: 230

**Description:** Basic Key-Value extraction using a colon as an anchor.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// "ID" and ":" are Anchors. "{id}" is the Variable.
t.FromTo("ID: {id}", "Found ID: {id}");
wl(t.Transform("ID: 12345").@Text()) 
```

**Output:**
```
Found ID: 12345
```

---

### Example ID: 231

**Description:** Parsing a standard connection string. Note how the semicolon acts as both an anchor and a natural statement separator.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Anchors: "Server", "=", ";", "Database"
// Variables: {srv}, {db}
t.FromTo("Server={srv};Database={db};", 
         "Connecting to database '{db}' on server '{srv}'...");

var connStr = "Server = LocalHost; Database = MyData;";
wl(t.Transform(connStr).@Text())
// Note: Spaces around '=' handled automatically by default tokenization.
```

**Output:**
```
Connecting to database 'MyData' on server 'LocalHost'...
```

---

### Example ID: 232

**Description:** Testing **Statement Separators** vs **Constraints**.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// 1. Separator Stop: {v} stops at newline (default separator)
t.FromTo("Value: {v}", "Captured: [{v}]");
wl(t.Transform([verbatim]Value: 100
Value: 200[/verbatim]).@Text())

// 2. Constraint vs Ambiguity: 
// {a}{b} is currently ambiguous (usually {a} eats everything).
// {a:2}{b:1} is deterministic.
t.FromTo("{a:2}{b:1}", "A:[{a}], B:[{b}]");
wl(t.Transform("one two three"))
```

**Output:**
```
Captured: [100]
Captured: [200]
A:[one two], B:[three]
```

---

---

## Replacement - ID: 762
/doc/reference/patterns/introduction/replacement/

**Remarks:**

In a `FromTo(pattern, replacement)` rule, the **Replacement** string defines how the matched text should be reconstructed.

**Key Components:**
* **Literals:** Text that is inserted exactly as written.
* **Variables:** `{name}` acts as a placeholder *if and only if* `{name}` was defined as a capturing variable in the Pattern.
* **Evaluations:** `{@Eval: expression}` executes logic during replacement (e.g., `{@Eval: 2 + 2}` inserts `4`).

**Conditional Replacements (Optional Blocks):**
When a variable corresponds to an **optional** part of the pattern (e.g., `Start [{opt}] End`), you can control the output based on whether a match occurred.
* **Standard `{opt}`:** Inserts the captured text if found, or an empty string if not found.
* **Conditional `{opt: ...}`:** Inserts the entire block of text following the colon *only if* the variable captured content.
    * *Syntax:* `{varName: text to display}`
    * *Behavior:* If `varName` captured text, the block is displayed (and can include the variable itself). If `varName` is empty/missing, the entire block is suppressed.

**Implicit Behavior:**
* **Verbatim Braces:** You do *not* need to escape curly braces in the replacement string. If `{Hello}` appears in the replacement but `{Hello}` was **not** defined as a variable in the pattern, it is treated as literal text.

### Comparative Analysis: Why uCalc?

* **vs. Regex:**
    * **Conditionals:** Standard Regex replacements cannot easily say "Insert 'Label: ' only if Group 1 matched." You typically need complex code callbacks. uCalc handles this natively with `{var: Label: {var}}`.
    * **Readability:** uCalc uses named variables (`{name}`) instead of numeric backreferences (`$1`), making complex rearrangements intuitive.
    * **Logic:** `{@Eval}` allows mathematical transformation directly in the replacement string.

**Examples:**

### Example ID: 190

**Description:** Searching for two different words in parallel.

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Define concurrent patterns
t.FromTo("Mango", "[Fruit]");
t.FromTo("Car", "[Vehicle]");

wl(t.Transform("I have a Mango and a Car.")) 

```

**Output:**
```
I have a [Fruit] and a [Vehicle].
```

---

### Example ID: 194

**Description:** More on variables and anchors

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Variables are {etc} and {ch}
// Anchors are "This", either "a small" or "an easy", and "Test"

t.FromTo("This {etc} {ch: a small | an easy } Test", "<{etc}> ({ch}) experiment");
wl(t.Transform("This is such an easy test."))
```

**Output:**
```
<is such> (an easy) experiment.
```

---

### Example ID: 195

**Description:** Named optional part

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a [{option: small | big }] test",
         "a sample test{option: categorized as '{option}'}");

wl(t.Transform("This is a test."))
wl(t.Transform("This is a big test."))
wl(t.Transform("This is a small test."))
wl(t.Transform("This is a random test."))
```

**Output:**
```
This is a sample test.
This is a sample test categorized as 'big'.
This is a sample test categorized as 'small'.
This is a random test.
```

---

### Example ID: 152

**Description:** RewindOnChange

**Code:**
```pseudocode
var ExprT = uc.@ExpressionTransformer();  // Transformer used for Eval() and Evaluate()

ExprT.@DefaultRuleSet().@RewindOnChange(true);

ExprT.FromTo("AddUp({x})", "{x}");
ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

ExprT.FromTo("ArgCount({x})", "1");
ExprT.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))");

ExprT.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})");

var Expression = "Average(1, 2, 3, 4)";
wl("Input: ", Expression)
wl("Transform: ", ExprT.Transform(Expression))
wl("Eval: ", uc.Eval(Expression))
```

**Output:**
```
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
```

---

### Example ID: 199

**Description:** Using the same pattern variable multiple times in a pattern

**Code:**
```pseudocode
var t = uc.NewTransformer();

// When a variable is used multiple times in a pattern,
// such as {tag} in this case, the matching text must be the same

t.FromTo("<{tag}> {words:2} {more} </{tag}>",
"tag={tag}, 2 words={words}, text={more}");

wl(t.Transform("<div>abc xyz more words<b>bold</b></div>").@Text())
```

**Output:**
```
tag=div, 2 words=abc xyz, text=more words<b>bold</b>
```

---

### Example ID: 234

**Description:** Using **Conditional Blocks** to format an optional title.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Pattern: Name followed optionally by a Title in parens.
t.FromTo("Name: {n} [({title})]", 
         "User: {n} {title:[Title: {title}]}");

// Case 1: Title exists
wl(t.Transform("Name: Alice (Manager)")) 

// Case 2: Title missing
wl(t.Transform("Name: Bob"))
// (The entire "[Title: ...]" block is omitted)
```

**Output:**
```
User: Alice [Title: Manager]
User: Bob
```

---

---

## Alternation - ID: 797
/doc/reference/patterns/introduction/alternation/

**Description:** Defines multiple acceptable token sequences for a single position in a pattern using the '|' (OR) operator.

**Remarks:**

Alternation allows you to define a set of choices for a single position in your pattern. The parser will attempt to match each choice in order until one succeeds. It uses the vertical bar `|` as the "OR" operator.

**Syntax:** `{ Option1 | Option2 | Option3 }`

### Key Concepts

*   **Left-to-Right Precedence**: The parser is "greedy" and evaluates alternatives from left to right. It stops at the **first** successful match that allows the rest of the pattern to also match. If you have overlapping alternatives (e.g., `Apple` and `Apple Pie`), you must list the longest and most specific one first to ensure it gets matched correctly. See the internal test example for a demonstration of this common pitfall.

*   **Grouping and Scope**: The curly braces `{...}` define the scope of the alternation. Any anchors outside the braces apply to the entire group. For example, in `Set { On | Off }`, the `Set` anchor is required, followed by either `On` or `Off`.

*   **Tokens vs. Sub-Patterns**: Alternatives can be single tokens (e.g., `{ Red | Blue }`) or more complex sequences of tokens, which can themselves contain groups (e.g., `{ Color | {Size {Big | Small}} }`).

*   **Alternation with "Nothing"**: To create a choice that includes an empty option (e.g., "match A or B or nothing"), combine alternation with an [Optional parts](/Reference/Patterns/Introduction/Optional-parts) block: `[{ A | B }]`.

### 💎 Conditional Replacements with Alternation

When an alternation contains multiple branches that capture different variables, only the variables in the branch that successfully matches will contain a value. The variables from all other branches will be empty. This allows you to use conditional replacement blocks to create a dynamic output based on which alternative was matched.

| Syntax | Name | Behavior |
| :--- | :--- | :--- |
| `{var: ...}` | **Positive Condition** | The content after the colon is inserted **only if** `{var}` captured a value. |
| `{!var: ...}`| **Fallback Content** | The content after the colon is inserted **only if** `{var}` is empty (did not capture a value). |

This is extremely powerful for normalizing different input formats into a single, consistent output format.

### Comparative Analysis: Why uCalc?

*   **vs. Regex (`(A|B|C)`)**:
    *   **Readability:** uCalc's syntax `{ Red | Blue }` is cleaner and doesn't require the often-confusing parentheses-grouping of Regex `(Red|Blue)`.
    *   **Token Awareness:** A Regex alternation like `(in|to)` can match inside words like "b**in**" or "**to**p" unless you explicitly add word boundaries (`\b`). uCalc defaults to whole-token matching, preventing these common false positives automatically.

*   **vs. C# Switch/Case:**
    *   **Conciseness:** Handling multiple string alternatives in native C# code often requires a `switch` statement or a `List.Contains()` check after parsing. uCalc handles the branching logic directly within the pattern string, making the code more declarative.

**Examples:**

### Example ID: 794

**Description:** Matching one of several status keywords.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("Status: { OK | Error | Pending }", "Found Valid Status");

wl(t.Transform("Status: OK"))
wl(t.Transform("Status: Error"))
wl(t.Transform("Status: Fail"))
```

**Output:**
```
Found Valid Status
Found Valid Status
Status: Fail
```

---

### Example ID: 795

**Description:** Normalizing various boolean representations to a standard format.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Normalize 'true-like' and 'false-like' values
t.FromTo("{ True | Yes | On }", "TRUE");
t.FromTo("{ False | No | Off }", "FALSE");

wl(t.Transform("System is On and Power is False"))
wl(t.Transform("Access: Yes, Admin: No"))
```

**Output:**
```
System is TRUE and Power is FALSE
Access: TRUE, Admin: FALSE
```

---

### Example ID: 196

**Description:** Alternative parts

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("This is a {adjective: simple | small | nice } test",
         "The adjective in '{@Self}' is: {adjective}.");

wl(t.Transform("This is a test"))
wl(t.Transform("This is a simple test"))
wl(t.Transform("This is a small test"))
wl(t.Transform("This is a nice test"))
wl(t.Transform("This is a random test"))

```

**Output:**
```
This is a test
The adjective in 'This is a simple test' is: simple.
The adjective in 'This is a small test' is: small.
The adjective in 'This is a nice test' is: nice.
This is a random test
```

---

### Example ID: 236

**Description:** Matching one of several keywords.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("Status: { OK | Error | Pending }", "Found Status");

wl(t.Transform("Status: OK"))    // Output: Found Status
wl(t.Transform("Status: Error")) // Output: Found Status
wl(t.Transform("Status: Fail"))  // No Match (Output unchanged)
```

**Output:**
```
Found Status
Found Status
Status: Fail
```

---

### Example ID: 237

**Description:** Parsing boolean values that might be represented differently.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Normalize "True/Yes/On" to "TRUE" and "False/No/Off" to "FALSE"
t.FromTo("{ True | Yes | On }", "TRUE");
t.FromTo("{ False | No | Off }", "FALSE");

wl(t.Transform("System is On"))    // Output: System is TRUE
wl(t.Transform("Power is False"))  // Output: Power is FALSE
```

**Output:**
```
System is TRUE
Power is FALSE
```

---

### Example ID: 238

**Description:** Nested alternatives and variable capture.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Pattern: "Set" followed by (Color OR (Size followed by Big/Small))
// Note: Nesting syntax { A | { B | C } } validation
t.FromTo("Set { Color | Size { Big | Small } }", "Matched");

wl(t.Transform("Set Color"))      // Match
wl(t.Transform("Set Size Big"))   // Match
wl(t.Transform("Set Size Medium"))// No Match
```

**Output:**
```
Matched
Matched
Set Size Medium
```

---

---

## Optional parts - ID: 796
/doc/reference/patterns/introduction/optional-parts/

**Description:** Defines sections of a pattern that may or may not exist, and provides syntax for conditional replacements based on whether a match occurred.

**Remarks:**

Optional parts allow you to define sections of a pattern that may or may not exist in the source string. These are enclosed in square brackets `[...]`.

**Syntax:** `Start [ Optional ] End`

### Behavior

*   **Matching:** The parser attempts to match the content inside the brackets. If the match succeeds, it consumes the tokens. If it fails (e.g., the tokens don't match or are missing), the parser ignores the optional part and continues matching the rest of the pattern.
*   **Variable Capture:** If you define a variable inside an optional block (e.g., `[{val}]`), and the block is *not* matched, the variable will be empty.

### 💎 Conditional Replacements

When a variable is defined within an optional block, you can use special syntax in the replacement string to conditionally display content.

| Syntax | Name | Behavior |
| :--- | :--- | :--- |
| `{var: ...}` | **Positive Condition** | The content after the colon is inserted **only if** `{var}` captured a value. |
| `{!var: ...}`| **Fallback Content** | The content after the colon is inserted **only if** `{var}` is empty (did not capture a value). |

This provides a powerful, declarative way to handle default values and conditional formatting without needing complex callbacks.

### ⚠️ Syntax Warning (Escaping)

Because square brackets `[` and `]` are reserved for defining optional parts, if you need to match a **literal** square bracket in your text (e.g., a JSON array `[1,2]`), you must enclose the brackets in single quotes: `'['` and `']'`. This is a common requirement when parsing structured data formats.

### Comparative Analysis: Why uCalc?

*   **vs. Regex (`?`)**:
    *   **Block Scope:** In Regex, making a whole block optional requires parentheses and a question mark: `(optional part)?`. uCalc's square brackets `[optional part]` are visually cleaner and mimic standard documentation syntax (like Backus-Naur Form).
    *   **Nesting:** Nesting optional blocks in Regex can become a soup of punctuation `((inner)?outer)?`. uCalc uses intuitive nesting `[ outer [ inner ] ]` that clearly delineates hierarchy.
    *   **Conditionals:** Standard Regex replacements cannot easily say "Insert 'Label: ' only if Group 1 matched." You typically need complex code callbacks. uCalc handles this natively with `{var: Label: {var}}` and `{!var: Default}`.

*   **vs. Native Code (If/Else)**:
    *   **Logic Reduction:** Parsing optional data (like a middle name) manually requires multiple `if` checks or `Split` logic. uCalc handles the branching internally in a single declarative line.

**Examples:**

### Example ID: 790

**Description:** A simple optional word.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("This is a [very] important test", "MATCHED");

// Matches with the optional word
wl(t.Transform("This is a very important test"))

// Also matches without the optional word
wl(t.Transform("This is a important test"))
```

**Output:**
```
MATCHED
MATCHED
```

---

### Example ID: 791

**Description:** A practical example using a fallback content block to provide a default status for log entries.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Pattern: Match "Log:", an optional level (Warning or Error), and the message.
// Replacement: Use `{!level:OK}` to insert 'OK' if no level was captured.
t.FromTo("Log: [{level: Warning | Error}] {msg}", "Status: {!level:OK}{level} | Message: {msg}");

wl(t.Transform("Log: This is a standard entry"))
wl(t.Transform("Log: Warning A potential issue was found"))
wl(t.Transform("Log: Error System failure detected"))
```

**Output:**
```
Status: OK | Message: This is a standard entry
Status: Warning | Message: A potential issue was found
Status: Error | Message: System failure detected
```

---

### Example ID: 792

**Description:** A practical example of parsing names with an optional middle name, using a positive conditional block.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Pattern: Capture first, optional middle, and last names.
// Replacement: The block `{middle: {middle}}` ensures a leading space is only added if a middle name exists.
t.FromTo("Name: {first:1} [{middle:1}] {last:1}", 
         "User: {last}, {first}{middle: {middle}}");

wl(t.Transform("Name: John Doe"))
wl(t.Transform("Name: John Quincy Adams"))
```

**Output:**
```
User: Doe, John
User: Adams, John Quincy
```

---

### Example ID: 197

**Description:** Optional part

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a [simple] test", "<{@Self}>");

wl(t.Transform("Is this a simple test, or a hard test, or just a test?"))
```

**Output:**
```
Is this <a simple test>, or a hard test, or just <a test>?
```

---

### Example ID: 198

**Description:** Optional part; value when optional part not used

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("This is a [{adj: simple}] test",
         "Let's take the {adj}{!adj:short} test");

wl(t.Transform("This is a test"))
wl(t.Transform("This is a simple test"))
```

**Output:**
```
Let's take the short test
Let's take the simple test
```

---

### Example ID: 195

**Description:** Named optional part

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a [{option: small | big }] test",
         "a sample test{option: categorized as '{option}'}");

wl(t.Transform("This is a test."))
wl(t.Transform("This is a big test."))
wl(t.Transform("This is a small test."))
wl(t.Transform("This is a random test."))
```

**Output:**
```
This is a sample test.
This is a sample test categorized as 'big'.
This is a sample test categorized as 'small'.
This is a random test.
```

---

### Example ID: 239

**Description:** Handling an optional trailing semicolon.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("Statement: {val} [;]", "Found: {val}");

wl(t.Transform("Statement: x = 1;")) // Output: Found: x = 1
wl(t.Transform("Statement: y = 2"))  // Output: Found: y = 2
```

**Output:**
```
Found: x = 1
Found: y = 2
```

---

### Example ID: 240

**Description:** Parsing names with an optional middle name.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Matches "First Last" OR "First Middle Last"
// Constraint Note: We use {name:1} to ensure each variable captures exactly one token.
// Replacement Note: We use {middle: {middle}} instead of just {middle} to prepend
// a space only if the middle name exists.
t.FromTo("Name: {first:1} [{middle:1}] {last:1}",
         "User: {last}, {first}{middle: {middle}}"); 

wl(t.Transform("Name: John Doe")) 
wl(t.Transform("Name: John Quincy Adams")) 
```

**Output:**
```
User: Doe, John
User: Adams, John Quincy
```

---

### Example ID: 241

**Description:** Nested optional blocks.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Pattern: A, optionally followed by B, which is optionally followed by C.
// Valid inputs: "A", "A B", "A B C". Invalid: "A C" (since C requires B).
t.FromTo("A [ B [ C ] ]", "Matched");

wl(t.Transform("A"))     // Matched
wl(t.Transform("A B"))   // Matched
wl(t.Transform("A B C")) // Matched
wl(t.Transform("A C"))   // Matched C
```

**Output:**
```
Matched
Matched
Matched
Matched C
```

---

### Example ID: 789

**Description:** Optional part in the Transformer

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("a [{txt}] b", "a, {txt:{txt}, }b");
wl(t.Transform("a b"))
wl(t.Transform("a x b"))


```

**Output:**
```
a, b
a, x, b
```

---

---

## Nested Patterns - ID: 765
/doc/reference/patterns/introduction/nested-patterns/

**Remarks:**

uCalc allows you to group segments of a pattern using curly braces `{ ... }`. This is primarily used to delimit the scope of **Alternative Parts** (`|`) or to create complex structures inside variables.

**Recursive Nesting:**
Patterns can be nested arbitrarily deep. For example:
* An **Alternation** `{ A | B }` can contain an **Optional** part `[ ... ]`.
* That **Optional** part can contain another **Alternation** or group.
* This flexibility allows you to model complex grammar structures like `Menu { Open [ Recent { File | Project } ] | Save }`.

**Syntax:**
* **Anonymous Grouping:** `Start { OptionA | OptionB } End`
    * The braces define where the alternation begins and ends.
* **Named Grouping (Capture):** `{name: OptionA | OptionB }`
    * Matches the pattern inside and captures the result into the variable `{name}`.

**Ambiguity Resolution:**
Since `{name}` denotes a variable and `{ pattern }` denotes a group, uCalc distinguishes them based on content:
1.  **Variable:** A simple name (e.g., `{x}`).
2.  **Group:** Contains structure like alternatives `|` or multiple tokens (e.g., `{ A | B }`).

### Comparative Analysis: Why uCalc?

* **vs. Regex Groups `(...)`:**
    * **Consistency:** Regex uses parentheses `()` for grouping and capturing. uCalc uses curly braces `{}` for everything—variables, groups, and blocks. This creates a unified syntax where "everything dynamic is in braces."
    * **Non-Capturing by Default:** In Regex, `(A|B)` captures automatically (Group 1). You have to use `(?:A|B)` to avoid capturing. In uCalc, `{ A | B }` is purely structural (non-capturing) unless you explicitly name it `{val: A | B}`. This avoids "index shifting" bugs.
* **vs. EBNF:**
    * **Familiarity:** uCalc's syntax is very close to EBNF (Extended Backus-Naur Form), making it intuitive for developers familiar with language grammar definitions.

**Examples:**

### Example ID: 242

**Description:** Grouping alternatives to limit scope.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Matches "File Open" or "File Close". 
// Capture needs explicit naming.
t.FromTo("File {cmd: Open | Close }", "Command: {cmd}");

wl(t.Transform("File Open"))
wl(t.Transform("File Close"))
```

**Output:**
```
Command: Open
Command: Close
```

---

### Example ID: 243

**Description:** Nested grouping for complex commands.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Pattern: "Set" followed by (Color OR (Size followed by Big/Small))
t.FromTo("Set {prop: Color | Size { Big | Small } }", "Property: {prop}");

wl(t.Transform("Set Color"))
wl(t.Transform("Set Size Big"))
wl(t.Transform("Set Size Small"))
```

**Output:**
```
Property: Color
Property: Size Big
Property: Size Small
```

---

### Example ID: 244

**Description:** Recursive Nesting: Alternation -> Optional -> Alternation.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Structure:
// 1. Alternation: "Open" OR "Save"
// 2. Inside "Open": Optional "Recent"
// 3. Inside "Recent": Alternation "File" OR "Project"
var pattern = "Menu { Open [ Recent {type: File | Project } ] | Save }";

t.FromTo(pattern, "Action Detected");

wl(t.Transform("Menu Save"))                 // Match (Simple Alternation)
wl(t.Transform("Menu Open"))                 // Match (Optional omitted)
wl(t.Transform("Menu Open Recent File"))     // Match (Deep nesting)
wl(t.Transform("Menu Open Recent Project"))  // Match (Deep nesting alt)
```

**Output:**
```
Action Detected
Action Detected
Action Detected
Action Detected
```

---

---

## Tokens - ID: 758
/doc/reference/patterns/introduction/tokens/

**Remarks:**

uCalc uses a **tokenizer** (also known as a lexer) to split raw text into meaningful units called **tokens**. Unlike Regex which sees a stream of characters, uCalc sees a stream of words, numbers, and symbols.

**Token Categories:**
Every token in uCalc belongs to a specific category (defined in `TokenType` Enum). These categories dictate parsing behavior:

* **Generic:** The default category if a token is defined without a specific type.
* **Alphanumeric:** Standard identifiers and words (e.g., `Variable`, `Function_Name`).
* **Literal:** Represents data with an associated type (e.g., Numbers, Quoted Strings). These allow the parser to interpret values (integer vs float) immediately.
* **Bracket / BracketMatch:** Defined in pairs (e.g., `(` and `)`). If `BracketSensitive` is enabled (default), uCalc enforces nesting rules automatically.
* **StatementSep:** (Statement Separator) Acts as a "Stop" condition for variable captures and delimits statements (e.g., `;` or `\n`).
* **ArgSeparator:** Separates items in a list (e.g., `,`).
* **MemberAccess:** Used for object navigation (e.g., `.` in `Object.Property`).
* **Whitespace:** Ignored by default during parsing (e.g., Space, Tab).
* **TokenTransform:** Special tokens that modify interpretation, such as String Interpolation markers or Hex/Binary prefixes (`0x`).
* **Reducible:** Tokens capable of reduction logic (See Topic 802).
* **Eof:** Matches the end of the input string.
* **Empty:** Not a real token in text, but returned by API calls when querying a non-existent token definition.

**Core Token Concepts:**
* **Category:** As listed above, this defines behavior.
* **Token Name:** While categories group tokens, you can also match a specific token by its unique name (e.g., `_token_newline` or `_token_myCustomSymbol`). Names always start with `_token_`. For details, see **Matching by token name**.
* **Value:** The actual text content (e.g., `123`, `Hello`, `"my text"`).

**Why Tokenization Matters:**
* **Precision:** Matching `{@Alpha}` ensures you match `Apple` but not the `App` inside `Apple`.
* **Speed:** The parser operates on integer token IDs rather than scanning string characters repeatedly.
* **Statefulness:** Literals like strings (`"my string"`) are handled as single units, preventing "partial matches" inside quotes.

### Comparative Analysis: Why uCalc?

* **vs. Regex (Character-Based):**
    * **Boundary Hell:** In Regex, matching a word requires `\bword\b`. In uCalc, `{@Alpha}` automatically respects boundaries defined by the language's syntax, making patterns safer by default.
    * **Stateful Parsing:** Regex doesn't know that `123` inside a quote `"123"` is a string. uCalc's tokenizer handles quotes first, allowing you to distinguish `{@Number}` from `{@String}` reliably without complex look-aheads.
    * **Context Awareness:** Regex struggles to distinguish a parenthesis used for grouping `(a+b)` from a literal parenthesis in a string `"(a+b)"`. uCalc's **Literal** and **Bracket** categories handle this distinction natively.
* **vs. String.Split - Intelligence:**
    * `Split(' ')` breaks on spaces inside quotes (`"New York"` -> `New`, `York`). uCalc's tokenizer respects quotes, keeping `"New York"` as a single token.
    * `Split(',')` breaks inside function calls `fn(a,b)`. uCalc's logic respects the nesting depth of **Brackets**, splitting only at the top level (depending on the uCalc.Rule.BracketSensitive configuration)



**Examples:**

### Example ID: 155

**Description:** Transformer: Matching by tokens vs match by character; also whitespace sensitivity

**Code:**
```pseudocode
// This examples shows the default match by
// token mode, as well as how to reconfigure
// it in order to do match by character
// along with a whitespace variation

var t = uc.NewTransformer();
var txt = "This is an island test, I said.";
t.FromTo("is", "<is>");

wl(t.Transform(txt))
wl("")

t.@Tokens().@Description("Match by character");
t.@Tokens().Add("."); // This overrides existing tokens
t.FromTo("is", "<is>");
wl(t.@Tokens().@Description())
wl(t.Transform(txt))
wl("")

// Note: whitespace sensitivity is off by default
// Whitespace token is re-introduced
// (after being overridden in the previous Token Add())
t.@Tokens().@Description("By char + whitespace ignored");
t.@Tokens().Add("[\\t\\v ]+", TokenType::Whitespace);
t.FromTo("is", "<{@Self}>");
wl(t.@Tokens().@Description())
wl(t.Transform(txt))
```

**Output:**
```
This <is> an island test, I said.

Match by character
Th<is> <is> an <is>land test, I said.

By char + whitespace ignored
Th<is> <is> an <is>land test, <I s>aid.
```

---

### Example ID: 200

**Description:** Matching a certain number of tokens

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("is {TokenCount:4}", "is <{TokenCount}>");
wl("This example captures 4 tokens")
wl(t.Transform("This is just a small token match test"))

// Quoted text counts as one token
wl(t.Transform("This is a 'really really' small test with quoted text"))
```

**Output:**
```
This example captures 4 tokens
This is <just a small token> match test
This is <a 'really really' small test> with quoted text
```

---

### Example ID: 70

**Description:** Displays the complete list of default token definitions, showing their type, internal name, and regex pattern.

**Code:**
```pseudocode
// Lists all tokens currently defined for the expression evaluator.

wl("Token Count: ", uc.@ExpressionTokens().@Count())
wl("")
wl("Index  Type  Name: regex")
wl("========================")
var Tokens = uc.@ExpressionTokens();
foreach (var token in Tokens)
   w(Tokens.IndexOf(token))
   wl("  ", token.@Description(), "  ", token.@Name(), ": ", token.@Regex())
end for

// Note that the expression evaluator token list has a few extra tokens,
// related to hex/bin/oct notation, string interpolation, and imaginary number
// notation, which are not found in the default Transformer token list.
```

**Output:**
```
Token Count: 30

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
27  literal  _token_imaginaryunit: #i
28  tokentransform  _token_binaryhexoctalnotation: #[bho][0-9A-F]+
29  tokentransform  _token_stringinterpolationquote: \$['"]
```

---

### Example ID: 245

**Description:** Matching tokens by category.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Match a word (Alpha) followed by equals and a Number (Literal)
t.FromTo("{@Alpha} = {@Number}", "Assignment Detected");

wl(t.Transform("x = 10")) 
```

**Output:**
```
Assignment Detected
```

---

### Example ID: 246

**Description:** Customizing token definitions (e.g., treating hyphens as part of a word).

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Now capture it using the {@Alpha} category
t.FromTo("{@Alpha:w}", "<{w}>");

wl("Before:")
wl(t.Transform("1. Start-Up 'big ideas' well-knwon."))

// Define a new token pattern for hyphenated words
// We assign it to the 'AlphaNumeric' category so it behaves like a word
t.@Tokens().Add("[a-zA-Z-]+", TokenType::AlphaNumeric);
wl("After:")
wl(t.Transform("1. Start-Up 'big ideas' well-knwon."))
```

**Output:**
```
Before:
1. <Start>-<Up> 'big ideas' <well>-<knwon>.
After:
1. <Start-Up> 'big ideas' <well-knwon>.
```

---

### Example ID: 247

**Description:** Handling Brackets and Literals.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Capture a function call. 
// {@Alpha} matches the name. 
// '(' and ')' are Bracket tokens that ensure the content is captured correctly.
t.FromTo("{@Alpha:func} ( {args} )", "Call: {func} with {args}");

wl(t.Transform("myfunc('Hello World', (x + y) * 2 )"))
```

**Output:**
```
Call: myfunc with 'Hello World', (x + y) * 2
```

---

---

## Escapes - ID: 768
/doc/reference/patterns/introduction/escapes/

**Remarks:**

uCalc patterns reserve certain characters for syntax (`{`, `}`, `[`, `]`, `|`). To match these characters literally in your text, you use the **Escape Token** mechanism.

**User-Defined Escape System:**
Unlike Regex which forces `\` as the escape character, uCalc allows you to define *any* token pattern as an escape mechanism by assigning it the `TokenType.Escape` category.

**How it Works:**
1.  **Define:** Register a token definition (e.g., `\` or `'...'`) with `TokenType.Escape`.
2.  **Match:** When the parser encounters this token, it "neutralizes" the special meaning of the text immediately following it (or captured within it).
3.  **Output:** The neutralized text is treated as a literal token.

**Configuration Strategies:**
* **Backslash Style:** Define `\\` (matches `\`) as an escape. `\{` becomes literal `{`.
* **Smart Quote Style (Recommended):** Define a pattern like `'([\{\}\[\]\|])'` to only escape specific characters inside quotes.
    * *Advantage:* This solves the "Apostrophe Conflict." Since the pattern only matches specific symbols inside quotes, natural language like `User's` is ignored by the escape token and treated as a standard word, while `'{'` is treated as an escape.

**Capture Group Logic:**
If your escape token definition contains a capture group (parentheses in Regex), uCalc uses the content of the *first group* (`$1`) as the unescaped literal. If there are no groups, it uses the whole matched string.

### Comparative Analysis: Why uCalc?
* **vs. Regex:** Regex imposes `\` as the escape. uCalc lets you adapt. If you are parsing file paths (lots of `\`), you can switch your escape char to `^` or `%` to keep patterns readable.
* **vs. SQL/Legacy:** Traditional SQL uses double-quotes (`''`) for everything, which breaks natural language. uCalc's granular configuration allows precise targeting of reserved chars only.

**Examples:**

### Example ID: 201

**Description:** {@Eval}, {@@Eval}, and escaping special characters in a pattern

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("'['{word}']'", "{@Eval: UCase(word)}");
t.FromTo("'{'{expr}'}'", "{@@Eval: expr}");

wl(t.Transform("Words like [this] and [that]."))
wl(t.Transform("Is {5*3} bigger than {5^3}?"))
```

**Output:**
```
Words like THIS and THAT.
Is 15 bigger than 125?
```

---

---

## Rules - ID: 757
/doc/reference/patterns/introduction/rules/

**Remarks:**

In uCalc, a **Rule** is the compiled object that binds a specific **Pattern** to an action (such as a replacement string or a callback function).

When you call definition methods like `FromTo()` or `Pattern()`, the Transformer creates a `Rule` object internally. Capturing this object allows you to manipulate the rule's behavior dynamically at runtime.

*Note: The properties and methods listed below are a sample of the most common functionality. For a complete list, browse the subtopics under **uCalc -> Rules**.*

**Core Properties:**
* **`Active(bool)`**: Enables or disables the rule. Setting this to `False` effectively removes the rule from consideration without deleting it.
* **`Name()`**: (Read-Only) Returns the identifier of the rule.
* **`Description(text)`**: Gets or sets a descriptive string. This is useful for storing metadata or comments associated with the rule.

**Configuration Methods:**
These methods allow you to override global transformer settings for this specific rule.
* **`CaseSensitive(bool)`**: Determines if text matching is case-sensitive (e.g., `Apple` vs `apple`).
* **`WhitespaceSensitive(bool)`**: Determines if spaces are treated as tokens or ignored.
* **`BracketSensitive(bool)`**: Determines if brackets `()` `[]` `{}` enforce nesting logic.
* **`QuoteSensitive(bool)`**: Determines if quotes are respected as string delimiters.
* **`RewindOnChange(bool)`**: Determines whether the parser should "rewind" and re-scan the text after a replacement occurs. This is useful for recursive patterns or cascading replacements.

**Advanced Methods:**
* **`LocalTransformer()`**: Returns a `Transformer` object restricted to the scope of the match found by this rule. This allows you to "zoom in" and perform secondary searches *only* within the text matched by this rule.
* **`Release()`**: Manually destroys the rule object and frees resources.

### Comparative Analysis: Why uCalc?

* **vs. Regex (Stateless):**
    * **Dynamics:** A Regex is typically a static string. To make it case-insensitive, you often have to recompile it. In uCalc, `Rule.CaseSensitive(false)` is a runtime property toggle.
* **vs. Standard Iteration:**
    * **Rewind Logic:** Implementing "Find, Replace, then Re-scan from the start" in standard string manipulation often requires `while` loops and index management. `RewindOnChange(true)` handles this complexity declaratively.


**Examples:**

### Example ID: 190

**Description:** Searching for two different words in parallel.

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Define concurrent patterns
t.FromTo("Mango", "[Fruit]");
t.FromTo("Car", "[Vehicle]");

wl(t.Transform("I have a Mango and a Car.")) 

```

**Output:**
```
I have a [Fruit] and a [Vehicle].
```

---

### Example ID: 152

**Description:** RewindOnChange

**Code:**
```pseudocode
var ExprT = uc.@ExpressionTransformer();  // Transformer used for Eval() and Evaluate()

ExprT.@DefaultRuleSet().@RewindOnChange(true);

ExprT.FromTo("AddUp({x})", "{x}");
ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

ExprT.FromTo("ArgCount({x})", "1");
ExprT.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))");

ExprT.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})");

var Expression = "Average(1, 2, 3, 4)";
wl("Input: ", Expression)
wl("Transform: ", ExprT.Transform(Expression))
wl("Eval: ", uc.Eval(Expression))
```

**Output:**
```
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
```

---

### Example ID: 885

**Description:** Toggling a rule on and off.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var r = t.FromTo("Hello", "Hi");

// Disable
r.@Active(false);
wl(t.Transform("Hello").@Text()) // Output: Hello (No change)

// Enable
r.@Active(true);
wl(t.Transform("Hello").@Text()) // Output: Hi
```

**Output:**
```
Hello
Hi
```

---

---

## Token Category Operators - ID: 833
/doc/reference/patterns/introduction/token-category-operators/

**Description:** Explains the operators used within pattern syntax to match tokens by their category (`@`) or to exclude tokens by category (`!`).

**Remarks:**

# 🎯 Token Category Operators: The `@` and `!` Prefixes

[not implemented yet]

The `@` and `!` operators are powerful prefixes used inside pattern variable syntax (`{...}`) to match tokens based on their lexical category rather than their literal text. This is the core mechanism that makes uCalc's [Transformer](/Reference/uCalcBase/Transformer/Constructor) **token-aware**, giving it a structural understanding of text that traditional regular expressions lack.

---

## The `@` Operator: Matching by Category

The `@` operator is the standard way to match a token based on its type. Instead of looking for a specific word like `"if"`, you can look for any alphanumeric identifier using `{@Alphanumeric}`.

### Syntax

*   `{@Category}`: Matches any token belonging to `Category` but does not capture its value.
*   `{@Category:varName}`: Matches any token belonging to `Category` and captures its text into the variable `{varName}`.

This makes patterns both readable and robust. A pattern to find a number is simply `{@Number}`, which is far clearer than a complex regex like `[-+]?[0-9]*\.?[0-9]+`.

For a complete list of categories, see the [Matching by token category](/Reference/Patterns/Matching-by-token-category/Introduction) topic.

---

## The `!` Operator: Negating a Category

The `!` operator is the logical inverse of `@`. It matches any token that does **not** belong to the specified category. This is extremely useful for capturing 'everything else' or for defining boundaries in a pattern.

### Syntax

*   `{!Category}`: Matches any token that is **not** in `Category`.
*   `{!Category:varName}`: Matches and captures any token that is **not** in `Category`.

For example, the pattern `{!Bracket:content}` will capture any token as long as it isn't an opening or closing bracket. This is a simple and powerful way to capture the content between delimiters.

--- 

## ⚖️ Comparative Analysis

| Feature | uCalc Category Operators | Regular Expressions |
| :--- | :--- | :--- |
| **Matching** | **Token-based**. `{@Alphanumeric}` matches a whole word. | **Character-based**. `\w+` matches a sequence of word characters. |
| **Safety** | **High**. `{@Alphanumeric}` will not match inside a string literal like `"my_variable_name"` by default. | **Low**. `\w+` can easily and incorrectly match text inside strings or comments. |
| **Readability** | **High**. `{@Number}` is self-documenting. | **Low**. `[-+]?\d*\.?\d+` is cryptic. |
| **Negation** | **Simple**. `{!Whitespace}` clearly means 'not whitespace'. | **Complex**. Requires negative lookarounds like `(?!\s)` which are less intuitive. |

--- 

## Summary Table

| Operator | Name | Syntax | Purpose |
| :--- | :--- | :--- | :--- |
| `@` | Category Matcher | `{@Category:var}` | Matches a token that **is** a member of `Category`. |
| `!` | Negation Operator | `{!Category:var}` | Matches any token that **is not** a member of `Category`. |

**Examples:**

---

## Matching by token category - ID: 798
/doc/reference/patterns/matching-by-token-category/

---

## Introduction - ID: 813
/doc/reference/patterns/matching-by-token-category/introduction/

**Remarks:**

While you often match exact text (like matching the word "If" or "Select"), dynamic parsing requires matching **categories** of data, such as "any number" or "any string."

**Syntax:** `{@Category}`
* **Match Only:** `{@Alpha}` matches any alphanumeric token but does not capture it into a variable.
* **Match & Capture:** `{@Alpha:myVar}` matches an alphanumeric token and stores the value in `{myVar}`.
* **Not case sensitive**:  `{@Number}` and `{@number}` are equivalent.

**Common Categories:**
* `{@Alpha}` (or `{@Alphanumeric}`): Matches words/identifiers (e.g., `Result`, `x1`).
* `{@Number}`: Matches integers or decimals (e.g., `42`, `3.14`).
* `{@String}`: Matches text inside quotes (e.g., `"Hello"`, `'World'`).
* `{@Literal}`: Matches any data value (Number OR String).

### Comparative Analysis: Why uCalc?

* **vs. Regex (`\d`, `\w`):**
    * **Context:** `\w` in Regex matches a single word character. `{@Alpha}` matches a complete token. This means `{@Alpha}` won't accidentally match the first letter of a string literal or a character inside a comment (if comments are filtered).
    * **Simplicity:** To match a quoted string in Regex, you need `"[^"]*"`. In uCalc, it is simply `{@String}`. The parser handles the escape characters and quote boundaries for you.

        

**Examples:**

### Example ID: 176

**Description:** Matching by token type

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{@String:txt}", "<<InnerQuote={txt}><TxtWithQuotes={txt(0)}>>");
t.FromTo("{@Number:MyNum}", "<NumericValue={MyNum}>");
t.FromTo("{@Bracket:MyBrack}", "<Brack={MyBrack}>");
t.FromTo("{@CloseBracket:CloseBr}", "<CloseBrack={CloseBr}>");
t.FromTo("{@StatementSeparator:Sep}", "<Separator={Sep}>");
t.FromTo("{@Alphanumeric:alpha}", "<Alpha={alpha}>");
t.FromTo("{@Whitespace:ws}", "<whitespace count={@Eval: Length(ws)}>");
t.FromTo("{@Reducible:r}", "<Reducible={r}>");
t.FromTo("{@Newline}", "<New line{@Newline}>");

var s = [verbatim]This is   55.2*6 "Hello world";
'Single quote'(parenth)[/verbatim];

wl(t.Filter(s).@Matches().@Text())
```

**Output:**
```
<Alpha=This>
<whitespace count=1>
<Alpha=is>
<whitespace count=3>
<NumericValue=55.2>
<Reducible=*>
<NumericValue=6>
<whitespace count=1>
<<InnerQuote=Hello world><TxtWithQuotes="Hello world">>
<Separator=;>
<New line
>
<<InnerQuote=Single quote><TxtWithQuotes='Single quote'>>
<Brack=(>
<Alpha=parenth>
<CloseBrack=)>
```

---

### Example ID: 70

**Description:** Displays the complete list of default token definitions, showing their type, internal name, and regex pattern.

**Code:**
```pseudocode
// Lists all tokens currently defined for the expression evaluator.

wl("Token Count: ", uc.@ExpressionTokens().@Count())
wl("")
wl("Index  Type  Name: regex")
wl("========================")
var Tokens = uc.@ExpressionTokens();
foreach (var token in Tokens)
   w(Tokens.IndexOf(token))
   wl("  ", token.@Description(), "  ", token.@Name(), ": ", token.@Regex())
end for

// Note that the expression evaluator token list has a few extra tokens,
// related to hex/bin/oct notation, string interpolation, and imaginary number
// notation, which are not found in the default Transformer token list.
```

**Output:**
```
Token Count: 30

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
27  literal  _token_imaginaryunit: #i
28  tokentransform  _token_binaryhexoctalnotation: #[bho][0-9A-F]+
29  tokentransform  _token_stringinterpolationquote: \$['"]
```

---

### Example ID: 886

**Description:** Simple arithmetic matching.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Match "Number + Number"
t.FromTo("{@Number} + {@Number}", "Math Operation");

wl(t.Transform("10 + 20")) // Output: Math Operation
wl(t.Transform("A + B"))   // No Match (A/B are Alpha, not Number)
```

**Output:**
```
Math Operation
A + B
```

---

### Example ID: 887

**Description:** Parsing Key-Value pairs where values can be numbers or strings.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Use {@Literal} to match either numbers or strings
t.FromTo("{@Alpha:key} = {@Literal:val}", "Set {key} to {val}");

wl(t.Transform("Timeout = 100"))      // Output: Set Timeout to 100
wl(t.Transform("Name = 'Admin'"))     // Output: Set Name to 'Admin'
```

**Output:**
```
Set Timeout to 100
Set Name to 'Admin'
```

---

### Example ID: 923

**Description:** (Default Matching) Identifying any brackets and normalizing them to a standard parentheses.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Bracket}", "(");
t.FromTo("{@CloseBracket}", ")");

wl(t.Transform("{a, b, c} f(x, y) [1, 2, 3];"))
```

**Output:**
```
(a, b, c) f(x, y) (1, 2, 3);
```

---

### Example ID: 177

**Description:** {@Alphanumeric}

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("({@Alphanumeric:txt})", "<Alpha str={txt}>");

wl(t.Transform("Testing 123 (456) (abc) ('text') (xyz111)"))
```

**Output:**
```
Testing 123 (456) <Alpha str=abc> ('text') <Alpha str=xyz111>
```

---

### Example ID: 250

**Description:** Extracting keys from a key-value list where keys must be identifiers.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Capture the alphanumeric key and any literal value
t.FromTo("{@Alpha:key} = {@Literal:val}", "KEY:[{key}] VAL:[{val}]");

var input = "Timeout = 100; User = 'Admin'";
wl(t.Transform(input))
```

**Output:**
```
KEY:[Timeout] VAL:[100]; KEY:[User] VAL:['Admin']
```

---

### Example ID: 921

**Description:** (Real World: Escaping Helper) Finding double quotes to manually insert an escape backslash before them.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@dq}", [verbatim]\"[/verbatim]);

var(string, input) = [verbatim]He said "Hello"[/verbatim];
wl(t.Transform(input))
```

**Output:**
```
He said \"Hello\"
```

---

### Example ID: 915

**Description:** (Real World: Value Masking)

**Code:**
```pseudocode
// Creating a "Clean View" of a log or configuration file by replacing all
// actual data values with a placeholder, leaving only the structural identifiers.
New(uCalc::Transformer, t)
// Replace every literal with a generic placeholder
t.FromTo("{@Literal}", "?");

var(string, input) = [verbatim]setting_a = 500; setting_b = "active";[/verbatim];
wl(t.Transform(input))
```

**Output:**
```
setting_a = ?; setting_b = ?;
```

---

### Example ID: 911

**Description:** Replacing all platform-specific newlines with a generic visible tag.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Newline}", "[BR]");

[c]string input = "Line 1\nLine 2\r\nLine 3";[/c]
[vb]Dim input = $"Line 1{vbLf}Line 2{vbCrLf}Line 3"[/vb]
wl(t.Transform(input))
```

**Output:**
```
Line 1[BR]Line 2[BR]Line 3
```

---

### Example ID: 251

**Description:** (Real World: Currency Formatter) Finding raw numbers in a text stream and converting them to a formatted currency string.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("Price: {@Number:amt}", "Price: ${amt}");

var(string, input) = "Item A Price: 19.99, Item B Price: 5"
wl(t.Transform(input))
```

**Output:**
```
Item A Price: $19.99, Item B Price: $5
```

---

### Example ID: 906

**Description:** Identifying any quote character and replacing it with a visible tag.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@QuoteChar}", "[Q]");

wl(t.Transform([verbatim]"Double" and 'Single'[/verbatim]))
```

**Output:**
```
[Q]Double[Q] and [Q]Single[Q]
```

---

### Example ID: 903

**Description:** Identifying any operator sequence (single or multi-character) and labeling it.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Reducible:op}", "[OP:{op}]");
wl(t.Transform("a + b <= c"))
```

**Output:**
```
a [OP:+] b [OP:<=] c
```

---

### Example ID: 902

**Description:** (Mixed Delimiter Check) Verifying that `{@sq}` captures only single quotes (ignoring double quotes).

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@sq}", "$");

// Only the single quote should be replaced
wl(t.Transform([verbatim]"Hello" and 'World'[/verbatim]))
```

**Output:**
```
"Hello" and $World$
```

---

### Example ID: 184

**Description:** {@StatementSeparator}

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("{@StatementSeparator}", "<sep>");
wl(t.Transform("a = b + c; x = y + 1;"))
```

**Output:**
```
a = b + c<sep> x = y + 1<sep>
```

---

### Example ID: 894

**Description:** Demonstrating the difference between the `(0)` and `(1)` index.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Capture the string and show both versions in the replacement
t.FromTo("{@String:txt}", "With: {txt(0)}, Without: {txt(1)}, Default: {txt}");

wl(t.Transform("'uCalc'"))
```

**Output:**
```
With: 'uCalc', Without: uCalc, Default: uCalc
```

---

### Example ID: 179

**Description:** {@Whitespace}

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("{@Whitespace}", ",");

wl(t.Transform("This is   a 'small test' about ' whitespace ' tokens."))
```

**Output:**
```
This,is,a,'small test',about,' whitespace ',tokens.
```

---

---

## {@Alphanumeric} - ID: 806
/doc/reference/patterns/matching-by-token-category/{@alphanumeric}/

**Remarks:**

Captures tokens categorized as **Alphanumeric**. This includes standard words, variable identifiers, and any text defined by the current alphanumeric tokenizer rules (typically `[a-zA-Z_][a-zA-Z0-9_]*`).

### Remarks
The `{@Alphanumeric}` category matcher is used to find and optionally capture words or identifiers without needing to know their specific literal value.

* **Shortcut Syntax**: The parser is not case-sensitive regarding category names and only evaluates the first letter. Therefore, `{@a}`, `{@alpha}`, and `{@AlphNum}` are all functionally identical to `{@Alphanumeric}`.
* **Variable Capture**: Use the syntax `{@Alphanumeric:varName}` to capture the matched word into a variable for use in replacements.

* **Precedence Warning**: Use caution when defining a rule consisting solely of `{@Alphanumeric}`. Because it matches any identifier, it may compete with and take precedence over more specific alphanumeric anchors (literals) in other patterns if not properly ordered.

### Why uCalc? (Comparative Analysis)

* **vs. Regular Expressions (`\w+`)**: 
    * **Boundary Awareness**: `\w+` is a character-level match that can bleed into other tokens. `{@Alphanumeric}` is a **token-level** match; it will never capture half a word or match inside a quoted string unless configured to do so.
    * **Configurability**: In Regex, `\w` is fixed. In uCalc, you can redefine what characters are considered "alphanumeric" globally (e.g., adding hyphens or foreign characters) and `{@Alphanumeric}` will automatically adapt across all rules.
* **vs. AI (LLMs)**: 
    * **Determinism**: An LLM might hallucinate whether a specific string (like `var_123`) is a "word" or a "symbol." uCalc provides a **deterministic** guarantee: if the tokenizer says it's alphanumeric, the pattern matches.

**Examples:**

### Example ID: 177

**Description:** {@Alphanumeric}

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("({@Alphanumeric:txt})", "<Alpha str={txt}>");

wl(t.Transform("Testing 123 (456) (abc) ('text') (xyz111)"))
```

**Output:**
```
Testing 123 (456) <Alpha str=abc> ('text') <Alpha str=xyz111>
```

---

### Example ID: 176

**Description:** Matching by token type

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{@String:txt}", "<<InnerQuote={txt}><TxtWithQuotes={txt(0)}>>");
t.FromTo("{@Number:MyNum}", "<NumericValue={MyNum}>");
t.FromTo("{@Bracket:MyBrack}", "<Brack={MyBrack}>");
t.FromTo("{@CloseBracket:CloseBr}", "<CloseBrack={CloseBr}>");
t.FromTo("{@StatementSeparator:Sep}", "<Separator={Sep}>");
t.FromTo("{@Alphanumeric:alpha}", "<Alpha={alpha}>");
t.FromTo("{@Whitespace:ws}", "<whitespace count={@Eval: Length(ws)}>");
t.FromTo("{@Reducible:r}", "<Reducible={r}>");
t.FromTo("{@Newline}", "<New line{@Newline}>");

var s = [verbatim]This is   55.2*6 "Hello world";
'Single quote'(parenth)[/verbatim];

wl(t.Filter(s).@Matches().@Text())
```

**Output:**
```
<Alpha=This>
<whitespace count=1>
<Alpha=is>
<whitespace count=3>
<NumericValue=55.2>
<Reducible=*>
<NumericValue=6>
<whitespace count=1>
<<InnerQuote=Hello world><TxtWithQuotes="Hello world">>
<Separator=;>
<New line
>
<<InnerQuote=Single quote><TxtWithQuotes='Single quote'>>
<Brack=(>
<Alpha=parenth>
<CloseBrack=)>
```

---

### Example ID: 250

**Description:** Extracting keys from a key-value list where keys must be identifiers.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Capture the alphanumeric key and any literal value
t.FromTo("{@Alpha:key} = {@Literal:val}", "KEY:[{key}] VAL:[{val}]");

var input = "Timeout = 100; User = 'Admin'";
wl(t.Transform(input))
```

**Output:**
```
KEY:[Timeout] VAL:[100]; KEY:[User] VAL:['Admin']
```

---

---

## {@Bracket} - ID: 803
/doc/reference/patterns/matching-by-token-category/{@bracket}/

**Remarks:**

**Description**: A category matcher that identifies any token defined as an opening bracket (e.g., `(`, `[`, `{`, or custom patterns like `<` or `begin`).

The `{@Bracket}` token directive is a high-level matcher within a `uCalc::Transformer`. Unlike a character literal, it does not look for a specific symbol; instead, it queries the uCalc engine to see if the next token in the input stream belongs to the **Opening Bracket** category.

### The Power of Category Definition
By default, uCalc defines `(`, `[`, and `{` as opening brackets. However, these are not hard-coded. Because `{@Bracket}` relies on the underlying token definitions:
* **Multi-character support**: If you define the word `begin` as an opening bracket, `{@Bracket}` will match it.
* **Customizability**: You can add angle brackets (`<`) or remove default ones based on your language requirements.
* **Ambiguity Handling**: Angle brackets are excluded by default to prevent conflict with mathematical "less-than" operators.

### Integration with {@CloseBracket}
`{@Bracket}` matches only the **opening** component. To build patterns that capture content between brackets, it is used in tandem with `{@CloseBracket}` (Topic 804). This separation allows for granular control over how different styles of scopes are opened and closed.

### Inverse Matching with `!`
You can invert the logic of this directive using the `!` operator.
* `{@Bracket}`: Matches any token that **is** an opening bracket.
* `{!Bracket}`: Matches any token that **is not** an opening bracket.

This is extremely useful for "negative matching," such as identifying all content that exists outside of a bracketed scope.


**Examples:**

### Example ID: 176

**Description:** Matching by token type

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{@String:txt}", "<<InnerQuote={txt}><TxtWithQuotes={txt(0)}>>");
t.FromTo("{@Number:MyNum}", "<NumericValue={MyNum}>");
t.FromTo("{@Bracket:MyBrack}", "<Brack={MyBrack}>");
t.FromTo("{@CloseBracket:CloseBr}", "<CloseBrack={CloseBr}>");
t.FromTo("{@StatementSeparator:Sep}", "<Separator={Sep}>");
t.FromTo("{@Alphanumeric:alpha}", "<Alpha={alpha}>");
t.FromTo("{@Whitespace:ws}", "<whitespace count={@Eval: Length(ws)}>");
t.FromTo("{@Reducible:r}", "<Reducible={r}>");
t.FromTo("{@Newline}", "<New line{@Newline}>");

var s = [verbatim]This is   55.2*6 "Hello world";
'Single quote'(parenth)[/verbatim];

wl(t.Filter(s).@Matches().@Text())
```

**Output:**
```
<Alpha=This>
<whitespace count=1>
<Alpha=is>
<whitespace count=3>
<NumericValue=55.2>
<Reducible=*>
<NumericValue=6>
<whitespace count=1>
<<InnerQuote=Hello world><TxtWithQuotes="Hello world">>
<Separator=;>
<New line
>
<<InnerQuote=Single quote><TxtWithQuotes='Single quote'>>
<Brack=(>
<Alpha=parenth>
<CloseBrack=)>
```

---

### Example ID: 929

**Description:** Normalizing mixed input by replacing any opening bracket style with a standard parenthesis.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Bracket}", "(");

wl(t.Transform("{ x + [ y ] }"))
```

**Output:**
```
( x + ( y ] }
```

---

### Example ID: 930

**Description:** (Real World: Structure Identification) Labeling the start of complex data structures in a mixed text stream.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Bracket}", "[START_SCOPE]");

var(string, input) = "func { data [ 1, 2 ] }";
wl(t.Transform(input))
```

**Output:**
```
func [START_SCOPE] data [START_SCOPE] 1, 2 ] }
```

---

### Example ID: 931

**Description:** (Negative Match) Ensuring that `{@Bracket}` does not match common "bracket-like" characters that are not in its definition (like angle brackets).

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Bracket}", "FOUND");

// Angle brackets are not included in {@Bracket} by default
wl(t.Transform("vector <int>"))
```

**Output:**
```
vector <int>
```

---

### Example ID: 923

**Description:** (Default Matching) Identifying any brackets and normalizing them to a standard parentheses.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Bracket}", "(");
t.FromTo("{@CloseBracket}", ")");

wl(t.Transform("{a, b, c} f(x, y) [1, 2, 3];"))
```

**Output:**
```
(a, b, c) f(x, y) (1, 2, 3);
```

---

---

## {@Bracketed} - ID: 832
/doc/reference/patterns/matching-by-token-category/{@bracketed}/

**Remarks:**

[revisit]
**Description**: A structural token pattern that matches content enclosed within balanced opening and closing delimiters (parentheses, brackets, or braces).

The `{@Bracket}` token is a specialized pattern used within a `uCalc::Transformer`. It is designed to solve the "Nested Delimiter Problem" that often plagues traditional string parsing. 

By default, `{@Bracket}` recognizes:
* Parentheses: `( ... )`
* Square Brackets: `[ ... ]`
* Curly Braces: `{ ... }`

### Why use {@Bracket} instead of Regex?

Standard regular expressions are typically **regular** (Finite Automata) and cannot handle recursive nesting without complex extensions.

| Feature | Regex `(.*)` | uCalc `{@Bracket}` |
| :--- | :--- | :--- |
| **Nesting Awareness** | Matches to the *last* closing bracket (greedy) or *first* (non-greedy), often breaking inner logic. | Tracks nesting levels; only stops when the initial opening bracket is balanced. |
| **Mixed Delimiters** | Requires separate patterns for `()`, `[]`, and `{}`. | Automatically detects and balances all standard types. |
| **Logic Speed** | Can encounter "Catastrophic Backtracking" on deep nests. | Linear-time token scanning. |



**Examples:**

---

## {@CloseBracket} - ID: 804
/doc/reference/patterns/matching-by-token-category/{@closebracket}/

**Remarks:**

**Description**: A category matcher that identifies any token defined as a closing delimiter (e.g., `)`, `]`, `}`, or custom patterns like `>` or `end`).

The `{@CloseBracket}` directive identifies the termination point of a scope or grouping. Like its counterpart `{@Bracket}`, it operates on **token categories** rather than character literals. 

### Category-Based Matching
By default, uCalc recognizes `)`, `]`, and `}` as closing brackets. However, because this matcher queries the engine's token definitions:
* **Custom Keywords**: If the token `end` is defined as a closing bracket, `{@CloseBracket}` will successfully match it.
* **Configurability**: Users can add tokens like `>` or custom delimiters to the Closing Bracket category using `uCalc.Tokens.Add` (Topic 373).

### Inverse Matching with `!`
The inversion operator `!` can be applied to this category:
* `{@CloseBracket}`: Matches any token that **is** a closing bracket.
* `{!CloseBracket}`: Matches any token that **is not** a closing bracket.

This is particularly useful for patterns that need to "consume" all content inside a block until the final delimiter is reached.



**Examples:**

### Example ID: 176

**Description:** Matching by token type

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{@String:txt}", "<<InnerQuote={txt}><TxtWithQuotes={txt(0)}>>");
t.FromTo("{@Number:MyNum}", "<NumericValue={MyNum}>");
t.FromTo("{@Bracket:MyBrack}", "<Brack={MyBrack}>");
t.FromTo("{@CloseBracket:CloseBr}", "<CloseBrack={CloseBr}>");
t.FromTo("{@StatementSeparator:Sep}", "<Separator={Sep}>");
t.FromTo("{@Alphanumeric:alpha}", "<Alpha={alpha}>");
t.FromTo("{@Whitespace:ws}", "<whitespace count={@Eval: Length(ws)}>");
t.FromTo("{@Reducible:r}", "<Reducible={r}>");
t.FromTo("{@Newline}", "<New line{@Newline}>");

var s = [verbatim]This is   55.2*6 "Hello world";
'Single quote'(parenth)[/verbatim];

wl(t.Filter(s).@Matches().@Text())
```

**Output:**
```
<Alpha=This>
<whitespace count=1>
<Alpha=is>
<whitespace count=3>
<NumericValue=55.2>
<Reducible=*>
<NumericValue=6>
<whitespace count=1>
<<InnerQuote=Hello world><TxtWithQuotes="Hello world">>
<Separator=;>
<New line
>
<<InnerQuote=Single quote><TxtWithQuotes='Single quote'>>
<Brack=(>
<Alpha=parenth>
<CloseBrack=)>
```

---

### Example ID: 923

**Description:** (Default Matching) Identifying any brackets and normalizing them to a standard parentheses.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Bracket}", "(");
t.FromTo("{@CloseBracket}", ")");

wl(t.Transform("{a, b, c} f(x, y) [1, 2, 3];"))
```

**Output:**
```
(a, b, c) f(x, y) (1, 2, 3);
```

---

---

## {@dq} - ID: 827
/doc/reference/patterns/matching-by-token-category/{@dq}/

**Remarks:**

**Description**: A shortcut directive that matches the double-quote character `"` (specifically the `_Token_QuoteChar_Double` token).

The `{@dq}` directive is used within a `uCalc::Transformer` as a specialized matcher for the double-quote character. Conceptually, it functions similarly to `{@Bracket}` (Topic 803), serving as a structural anchor rather than a content matcher.

### Structural Role
Unlike `{@String}`—which captures an entire quoted string—`{@dq}` matches **only the quote character itself**. This is useful when you need to redefine the boundaries of a string or perform transformations that affect the delimiters specifically.

* **Internal Shortcut**: This is equivalent to calling `{@Token(_Token_QuoteChar_Double)}`.
* **Delimiter vs. Data**: Use `{@dq}` to match the quote; use `{@String}` or `{@StringDQ}` to match the enclosed text.

### Inverse Matching with `!`
The inversion operator `!` can be applied to this directive:
* `{@dq}`: Matches the double-quote character.
* `{!dq}`: Matches any token that is **not** a double-quote character.



**Examples:**

### Example ID: 920

**Description:** Replacing double quotes with single quotes.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@dq}", "'");

wl(t.Transform([verbatim]print "Hello"[/verbatim]))
```

**Output:**
```
print 'Hello'
```

---

### Example ID: 921

**Description:** (Real World: Escaping Helper) Finding double quotes to manually insert an escape backslash before them.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@dq}", [verbatim]\"[/verbatim]);

var(string, input) = [verbatim]He said "Hello"[/verbatim];
wl(t.Transform(input))
```

**Output:**
```
He said \"Hello\"
```

---

---

## {@Line} - ID: 830
/doc/reference/patterns/matching-by-token-category/{@line}/

**Remarks:**

**Description**: A structural matcher that captures all tokens from the current position until the end of the line.

The `{@Line}` directive is used within a `uCalc::Transformer` to consume an entire line of input. Because uCalc is token-aware, `{@Line}` doesn't just look for a newline character; it captures the sequence of tokens that constitute the rest of the current logical line.

### Key Characteristics
* **Greedy until EOL**: It will match every token until it encounters a newline token or the end of the input stream.
* **Newline Excluded**: Typically, `{@Line}` captures the content *before* the newline, leaving the newline token itself available for the next match or structural processing.
* **Token Sensitivity**: It respects token boundaries, ensuring that it doesn't break in the middle of a multi-character token if one happens to span a line (though rare).

### Inverse Matching with `!`
The universal inversion operator `!` can be applied to this directive:
* `{@Line}`: Matches the rest of the line.
* `{!Line}`: Matches a token only if it is a newline (or a token that breaks the "line" continuity).



**Examples:**

---

## {@Literal} - ID: 826
/doc/reference/patterns/matching-by-token-category/{@literal}/

**Remarks:**

**Description**: A category matcher that identifies any token defined as a literal constant value (e.g., numbers, quoted strings, or booleans).

The `{@Literal}` directive is a broad matcher used within a `uCalc::Transformer` to target data values. Unlike specific matchers like `{@Number}` or `{@String}`, `{@Literal}` matches any token that represents a fixed value rather than an identifier or an operator.

### Types of Literals
By default, `{@Literal}` will match:
* **Numbers**: `123`, `45.67`, `0xFF`
* **Strings**: `"Hello World"`, `'Single Quote'`
* **Booleans**: `true`, `false` (if defined as literal tokens)

### Choosing Precision
While `{@Literal}` is convenient for general data manipulation, uCalc allows for higher precision. If your transformation logic depends on the *type* of data (e.g., you want to format numbers but leave strings alone), you should use the more specific directives:
* `{@Number}`: For numeric values only.
* `{@String}`: For quoted text values only.

### Inverse Matching with `!`
The universal inversion operator `!` can be applied to this category:
* `{@Literal}`: Matches any constant value.
* `{!Literal}`: Matches any token that is **not** a literal (e.g., variable names, keywords, operators like `+` or `if`).

### Why uCalc?

In many parsers, you have to write a complex regex that accounts for every possible numeric format and quote style. `{@Literal}` leverages uCalc's built-in token categorization, making your patterns immune to changes in how numbers or strings are defined.



**Examples:**

### Example ID: 914

**Description:** Identifying all literal values in an expression and tagging them.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Literal:val}", "VAL({val})");

wl(t.Transform([verbatim]x = 10 + "abc"[/verbatim]))
```

**Output:**
```
x = VAL(10) + VAL("abc")
```

---

### Example ID: 915

**Description:** (Real World: Value Masking)

**Code:**
```pseudocode
// Creating a "Clean View" of a log or configuration file by replacing all
// actual data values with a placeholder, leaving only the structural identifiers.
New(uCalc::Transformer, t)
// Replace every literal with a generic placeholder
t.FromTo("{@Literal}", "?");

var(string, input) = [verbatim]setting_a = 500; setting_b = "active";[/verbatim];
wl(t.Transform(input))
```

**Output:**
```
setting_a = ?; setting_b = ?;
```

---

---

## {@Newline} - ID: 811
/doc/reference/patterns/matching-by-token-category/{@newline}/

**Remarks:**

**Description**: A structural category matcher that identifies any token defined as a line break or newline character sequence.

The `{@Newline}` directive (shorthand `{@nl}`) is used within a `uCalc::Transformer` to detect boundaries between lines. Because uCalc operates on tokens, `{@Newline}` is platform-agnostic; it will match whichever line-ending sequence (LF, CRLF, or custom separators) the engine is currently configured to recognize as a line break.

### Structural Significance
In many grammars, a newline acts as an implicit statement terminator. `{@Newline}` allows you to:
* **Enforce formatting**: Normalize varied line endings to a single standard.
* **Control Scope**: Prevent a match from spanning across multiple lines.
* **Remove Clutter**: Clean up unnecessary empty lines in data or code.

### Dual Role in Transformation
* **In the Pattern (Match)**: When used in the first argument of `FromTo()`, it matches an existing newline token in the input stream.
* **In the Replacement (Insert)**: When used in the second argument of `FromTo()`, it inserts the actual line-break character sequence defined in the engine's `_newline` variable.

### Inverse Matching with `!`
The universal inversion operator `!` can be applied to this directive:
* `{@Newline}`: Matches a line break.
* `{!Newline}`: Matches any token that is **not** a line break.

This is particularly effective when combined with `{@Line}` to create precise "horizontal" search patterns that strictly stay within the bounds of a single line.


**Examples:**

### Example ID: 176

**Description:** Matching by token type

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{@String:txt}", "<<InnerQuote={txt}><TxtWithQuotes={txt(0)}>>");
t.FromTo("{@Number:MyNum}", "<NumericValue={MyNum}>");
t.FromTo("{@Bracket:MyBrack}", "<Brack={MyBrack}>");
t.FromTo("{@CloseBracket:CloseBr}", "<CloseBrack={CloseBr}>");
t.FromTo("{@StatementSeparator:Sep}", "<Separator={Sep}>");
t.FromTo("{@Alphanumeric:alpha}", "<Alpha={alpha}>");
t.FromTo("{@Whitespace:ws}", "<whitespace count={@Eval: Length(ws)}>");
t.FromTo("{@Reducible:r}", "<Reducible={r}>");
t.FromTo("{@Newline}", "<New line{@Newline}>");

var s = [verbatim]This is   55.2*6 "Hello world";
'Single quote'(parenth)[/verbatim];

wl(t.Filter(s).@Matches().@Text())
```

**Output:**
```
<Alpha=This>
<whitespace count=1>
<Alpha=is>
<whitespace count=3>
<NumericValue=55.2>
<Reducible=*>
<NumericValue=6>
<whitespace count=1>
<<InnerQuote=Hello world><TxtWithQuotes="Hello world">>
<Separator=;>
<New line
>
<<InnerQuote=Single quote><TxtWithQuotes='Single quote'>>
<Brack=(>
<Alpha=parenth>
<CloseBrack=)>
```

---

### Example ID: 911

**Description:** Replacing all platform-specific newlines with a generic visible tag.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Newline}", "[BR]");

[c]string input = "Line 1\nLine 2\r\nLine 3";[/c]
[vb]Dim input = $"Line 1{vbLf}Line 2{vbCrLf}Line 3"[/vb]
wl(t.Transform(input))
```

**Output:**
```
Line 1[BR]Line 2[BR]Line 3
```

---

### Example ID: 912

**Description:** Identifying and removing redundant empty lines (consecutive newlines).

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Match two newlines in a row and replace with one
t.FromTo("{@nl} {@nl}", "{@nl}"); // {@nl} same as {@NewLine}

[c]string text = "First\n\nSecond\n\nThird";[/c]
[vb] Dim text = $"First{vbLf}{vbLf}Second{vbLf}{vbLf}Third"[/vb]
wl(t.Transform(text))
```

**Output:**
```
First
Second
Third
```

---

---

## {@Number} - ID: 800
/doc/reference/patterns/matching-by-token-category/{@number}/

**Remarks:**

**Description**: A category matcher that identifies any token defined as a numeric value (e.g., `10`, `3.14`, `1e-5`).

The `{@Number}` directive is used within a `uCalc::Transformer` to target numeric data. Because it operates at the tokenization level, it is more robust than a standard numeric regex. It understands the context of a number and treats it as a single unit, regardless of its format.

### Supported Formats
By default, `{@Number}` recognizes:
* **Integers**: `42`
* **Decimals**: `0.99`
* **Scientific Notation**: `6.022e23`
* **Hex/Binary**: `0xFF` or `0b1010` (if configured in the engine)

### Accuracy vs. Regex
A common regex like `\d+` might accidentally match digits inside a variable name (like the `3` in `data3`). Because `{@Number}` queries the **lexer**, it only matches tokens that have been explicitly identified as numeric literals, ensuring your transformations don't corrupt variable identifiers.

### Inverse Matching with `!`
The universal inversion operator `!` can be applied to this category:
* `{@Number}`: Matches a numeric token.
* `{!Number}`: Matches any token that is **not** a number (e.g., operators, strings, or keywords).


**Examples:**

### Example ID: 176

**Description:** Matching by token type

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{@String:txt}", "<<InnerQuote={txt}><TxtWithQuotes={txt(0)}>>");
t.FromTo("{@Number:MyNum}", "<NumericValue={MyNum}>");
t.FromTo("{@Bracket:MyBrack}", "<Brack={MyBrack}>");
t.FromTo("{@CloseBracket:CloseBr}", "<CloseBrack={CloseBr}>");
t.FromTo("{@StatementSeparator:Sep}", "<Separator={Sep}>");
t.FromTo("{@Alphanumeric:alpha}", "<Alpha={alpha}>");
t.FromTo("{@Whitespace:ws}", "<whitespace count={@Eval: Length(ws)}>");
t.FromTo("{@Reducible:r}", "<Reducible={r}>");
t.FromTo("{@Newline}", "<New line{@Newline}>");

var s = [verbatim]This is   55.2*6 "Hello world";
'Single quote'(parenth)[/verbatim];

wl(t.Filter(s).@Matches().@Text())
```

**Output:**
```
<Alpha=This>
<whitespace count=1>
<Alpha=is>
<whitespace count=3>
<NumericValue=55.2>
<Reducible=*>
<NumericValue=6>
<whitespace count=1>
<<InnerQuote=Hello world><TxtWithQuotes="Hello world">>
<Separator=;>
<New line
>
<<InnerQuote=Single quote><TxtWithQuotes='Single quote'>>
<Brack=(>
<Alpha=parenth>
<CloseBrack=)>
```

---

### Example ID: 251

**Description:** (Real World: Currency Formatter) Finding raw numbers in a text stream and converting them to a formatted currency string.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("Price: {@Number:amt}", "Price: ${amt}");

var(string, input) = "Item A Price: 19.99, Item B Price: 5"
wl(t.Transform(input))
```

**Output:**
```
Item A Price: $19.99, Item B Price: $5
```

---

### Example ID: 909

**Description:** Identifying all numbers in an expression and wrapping them in a "Num" tag.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Number:n}", "Num({n})");

wl(t.Transform("price = 50 + 5.50"))
```

**Output:**
```
price = Num(50) + Num(5.50)
```

---

### Example ID: 910

**Description:** Verifying that `{@Number}` correctly ignores digits that are part of other tokens (like strings or identifiers).

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Number}", "FOUND");

// The '2' in 'var2' and the '100' in the string should NOT match
wl(t.Transform([verbatim]var2 = "count is 100" + 50[/verbatim]))
```

**Output:**
```
var2 = "count is 100" + FOUND
```

---

---

## {@QuoteChar} - ID: 829
/doc/reference/patterns/matching-by-token-category/{@quotechar}/

**Remarks:**

**Description**: A category matcher that identifies any token defined as a string delimiter, covering both single (`'`) and double (`"`) quotes.

The `{@QuoteChar}` directive serves as a structural matcher within a `uCalc::Transformer`. It targets the characters used to open or close string literals. By using this category matcher instead of specific quote directives, you can write rules that apply to all supported string delimiter styles simultaneously.

### The Delimiter Category
By default, `{@QuoteChar}` matches:
* **Double Quotes**: `"` (See `{@dq}`, Topic 827)
* **Single Quotes**: `'` (See `{@sq}`, Topic 828)

Using `{@QuoteChar}` is ideal when you want to treat all types of quoted strings with the same structural logic, such as swapping delimiters or identifying the boundaries of literal data without knowing which specific quote style the input uses.

### Inverse Matching with `!`
The universal inversion operator `!` can be applied to this category:
* `{@QuoteChar}`: Matches any quote character.
* `{!QuoteChar}`: Matches any token that is **not** a quote character.


**Examples:**

### Example ID: 906

**Description:** Identifying any quote character and replacing it with a visible tag.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@QuoteChar}", "[Q]");

wl(t.Transform([verbatim]"Double" and 'Single'[/verbatim]))
```

**Output:**
```
[Q]Double[Q] and [Q]Single[Q]
```

---

### Example ID: 907

**Description:** (Real World: Quote Normalizer) Converting all string literals to use double quotes, regardless of whether they were originally single or double quoted.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Convert any quote character found to a double quote
t.FromTo("{@QuoteChar}", [verbatim]"[/verbatim]);

var(string, input) = [verbatim]msg = 'Hello'; val = "World";[/verbatim];
wl(t.Transform(input))
```

**Output:**
```
msg = "Hello"; val = "World";
```

---

### Example ID: 908

**Description:** (Non-delimiter characters) Verifying that `{@QuoteChar}` does not match characters that are not defined as string delimiters in the engine.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@QuoteChar}", "MATCH");

// Backticks (`) are usually not delimiters by default
wl(t.Transform("`Backtick`"))
```

**Output:**
```
`Backtick`
```

---

---

## {@Reducible} - ID: 802
/doc/reference/patterns/matching-by-token-category/{@reducible}/

**Remarks:**

**Description**: A structural matcher that identifies clusters of symbol/operator characters and breaks them down into the largest possible recognized tokens.

The `{@Reducible}` directive is a specialized matcher designed to handle **symbol ambiguity** in mathematical and programming expressions. It targets tokens primarily composed of operator characters (e.g., `+`, `-`, `*`, `/`, `=`, `>`, `<`, etc.).

### The Deconstruction Logic
Unlike a standard token matcher that looks for an exact match, `{@Reducible}` employs a "greedy-to-granular" strategy:

1.  **Capture**: It identifies a cluster of symbol characters (e.g., `+-`).
2.  **Verify**: It checks if a single identifier/operator named `+-` exists.
3.  **Reduce**: If `+-` is not defined, it removes the last character and checks for `+`. 
4.  **Match**: Since `+` is a known identifier, it captures `+` as the current token and passes `-` back to the lexer to be processed as the next token.

### Why use {@Reducible}?
This approach is essential for parsing languages where operators can be adjacent without whitespace. 

| Input | Standard Tokenizer | uCalc `{@Reducible}` |
| :--- | :--- | :--- |
| **`x+-y`** | Might fail if `+-` is not a single defined operator. | Breaks it into `x`, `+`, `-`, and `y`. |
| **`x>>=y`** | Might match `>` and `>` separately. | Correctily identifies `>>=` as the "Right-Shift-Assign" operator (if defined). |

### Inverse Matching with `!`
The universal inversion operator `!` can be applied:
* `{@Reducible}`: Matches symbol clusters that can be broken down.
* `{!Reducible}`: Matches any token that is **not** a symbol-based reducible (e.g., Alphanumeric identifiers, Strings, or Numbers).


**Examples:**

### Example ID: 176

**Description:** Matching by token type

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{@String:txt}", "<<InnerQuote={txt}><TxtWithQuotes={txt(0)}>>");
t.FromTo("{@Number:MyNum}", "<NumericValue={MyNum}>");
t.FromTo("{@Bracket:MyBrack}", "<Brack={MyBrack}>");
t.FromTo("{@CloseBracket:CloseBr}", "<CloseBrack={CloseBr}>");
t.FromTo("{@StatementSeparator:Sep}", "<Separator={Sep}>");
t.FromTo("{@Alphanumeric:alpha}", "<Alpha={alpha}>");
t.FromTo("{@Whitespace:ws}", "<whitespace count={@Eval: Length(ws)}>");
t.FromTo("{@Reducible:r}", "<Reducible={r}>");
t.FromTo("{@Newline}", "<New line{@Newline}>");

var s = [verbatim]This is   55.2*6 "Hello world";
'Single quote'(parenth)[/verbatim];

wl(t.Filter(s).@Matches().@Text())
```

**Output:**
```
<Alpha=This>
<whitespace count=1>
<Alpha=is>
<whitespace count=3>
<NumericValue=55.2>
<Reducible=*>
<NumericValue=6>
<whitespace count=1>
<<InnerQuote=Hello world><TxtWithQuotes="Hello world">>
<Separator=;>
<New line
>
<<InnerQuote=Single quote><TxtWithQuotes='Single quote'>>
<Brack=(>
<Alpha=parenth>
<CloseBrack=)>
```

---

### Example ID: 903

**Description:** Identifying any operator sequence (single or multi-character) and labeling it.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Reducible:op}", "[OP:{op}]");
wl(t.Transform("a + b <= c"))
```

**Output:**
```
a [OP:+] b [OP:<=] c
```

---

---

## {@sq} - ID: 828
/doc/reference/patterns/matching-by-token-category/{@sq}/

**Remarks:**

**Description**: A shortcut directive that matches the single-quote character `'` (specifically the `_Token_QuoteChar_Single` token).

The `{@sq}` directive is used within a `uCalc::Transformer` as a specialized matcher for the single-quote character. It functions as a structural anchor, allowing you to target the delimiter itself rather than the string content.

### Structural Role
Like `{@dq}` (Topic 827), this directive matches **only the single-character delimiter**. It is essential for patterns where you need to manipulate the "wrapper" of a literal without necessarily affecting the data inside.

* **Internal Shortcut**: This is a direct call to `{@Token(_Token_QuoteChar_Single)}`.
* **Precision Matching**: Use `{@sq}` to match the quote mark; use `{@sqs}` (Topic 832) to match a complete single-quoted string literal.  Use {@QuoteChar} to match either the single or double quote character.

### Inverse Matching with `!`
The universal inversion operator `!` applies to this directive:
* `{@sq}`: Matches the single-quote character.
* `{!sq}`: Matches any token that is **not** a single-quote character.


**Examples:**

### Example ID: 888

**Description:** Converting single-quoted strings to double-quoted ones by targeting the delimiters.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@sq}", [verbatim]"[/verbatim]);

wl(t.Transform("print 'Hello'"))
```

**Output:**
```
print "Hello"
```

---

### Example ID: 901

**Description:** (Real World: SQL-style Escaping) Doubling up single quotes to escape them for a SQL query.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@sq}", "''");

var(string, input) = "It's a trap";
wl(t.Transform(input))
```

**Output:**
```
It''s a trap
```

---

### Example ID: 902

**Description:** (Mixed Delimiter Check) Verifying that `{@sq}` captures only single quotes (ignoring double quotes).

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@sq}", "$");

// Only the single quote should be replaced
wl(t.Transform([verbatim]"Hello" and 'World'[/verbatim]))
```

**Output:**
```
"Hello" and $World$
```

---

---

## {@StatementSeparator} - ID: 805
/doc/reference/patterns/matching-by-token-category/{@statementseparator}/

**Remarks:**

**Description**: A structural category matcher that identifies any token defined as a terminator or separator between distinct logic statements (e.g., `;` or a *newline*).

The `{@StatementSeparator}` directive (shorthand `{@Sep}`) is used within a `uCalc::Transformer` to identify the boundaries of a statement. In many programming and data-formatting languages, statements must be separated to prevent ambiguity. 

By targeting the **category** of a separator rather than a specific character, uCalc allows you to write transformation rules that are portable across different syntax styles.

### Supported Separators
By default, the engine typically recognizes:
* **Semicolons**: `;` (The standard explicit separator).
* **Newlines**: `\n` or `\r\n` (use uCalc.ItemOf("_Token_Newline").Release() to remove *newline* as a separator).

### Why use {@StatementSeparator}?
Using this directive instead of a literal `;` is a "Best Practice" for parser building:
1.  **Flexibility**: Your transformer can process both "C-style" code (semicolons) and "Basic-style" or "Python-style" code (newlines) using the same logic.
2.  **Accuracy**: It prevents matching delimiters that exist inside strings or comments, as `{@StatementSeparator}` only triggers on tokens recognized by the lexer as functional separators.

### Inverse Matching with `!`
The universal inversion operator `!` can be applied:
* `{@StatementSeparator}`: Matches a statement terminator.
* `{!StatementSeparator}`: Matches any token that is **not** a separator (useful for capturing the entire "meat" of a statement).

---

## Strategy & Critique
* **Structural Abstraction**: This is one of uCalc's most powerful architectural features. It treats "Statement Termination" as a logical concept rather than a character-matching task.
* **Ambiguity Note**: In some languages, a newline is only a separator if the current statement isn't "open" (e.g., inside an unclosed parenthesis). Because `{@StatementSeparator}` relies on the engine's tokenization, it automatically inherits this advanced context-awareness.
* **See Also**: Refer to **Topic 811** (`{@Newline}`) for matching line breaks specifically.

Current Time: Tuesday, January 13, 2026 at 8:55 PM EST.

**Examples:**

### Example ID: 184

**Description:** {@StatementSeparator}

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("{@StatementSeparator}", "<sep>");
wl(t.Transform("a = b + c; x = y + 1;"))
```

**Output:**
```
a = b + c<sep> x = y + 1<sep>
```

---

### Example ID: 176

**Description:** Matching by token type

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{@String:txt}", "<<InnerQuote={txt}><TxtWithQuotes={txt(0)}>>");
t.FromTo("{@Number:MyNum}", "<NumericValue={MyNum}>");
t.FromTo("{@Bracket:MyBrack}", "<Brack={MyBrack}>");
t.FromTo("{@CloseBracket:CloseBr}", "<CloseBrack={CloseBr}>");
t.FromTo("{@StatementSeparator:Sep}", "<Separator={Sep}>");
t.FromTo("{@Alphanumeric:alpha}", "<Alpha={alpha}>");
t.FromTo("{@Whitespace:ws}", "<whitespace count={@Eval: Length(ws)}>");
t.FromTo("{@Reducible:r}", "<Reducible={r}>");
t.FromTo("{@Newline}", "<New line{@Newline}>");

var s = [verbatim]This is   55.2*6 "Hello world";
'Single quote'(parenth)[/verbatim];

wl(t.Filter(s).@Matches().@Text())
```

**Output:**
```
<Alpha=This>
<whitespace count=1>
<Alpha=is>
<whitespace count=3>
<NumericValue=55.2>
<Reducible=*>
<NumericValue=6>
<whitespace count=1>
<<InnerQuote=Hello world><TxtWithQuotes="Hello world">>
<Separator=;>
<New line
>
<<InnerQuote=Single quote><TxtWithQuotes='Single quote'>>
<Brack=(>
<Alpha=parenth>
<CloseBrack=)>
```

---

### Example ID: 898

**Description:** Identifying any statement separator and replacing it with a standardized tag.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@StatementSeparator}", " [END_STMT]");

wl(t.Transform("x = 10; y = 20"))
```

**Output:**
```
x = 10 [END_STMT] y = 20
```

---

### Example ID: 900

**Description:** Internal Test (Configurability) Verifying that `{@StatementSeparator}` respects the engine's definition (e.g., checking if it correctly ignores a comma used as a parameter separator).

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@StatementSeparator}", "STMT");

// Comma is not a StatementSeparator, so it should be ignored.
wl(t.Transform("func(a, b); next();"))
```

**Output:**
```
func(a, b)STMT next()STMT
```

---

---

## {@String} - ID: 799
/doc/reference/patterns/matching-by-token-category/{@string}/

**Remarks:**

**Description**: A category matcher that identifies any token defined as a string literal, supporting single, double, and triple quotes, as well as interpolated strings.

The `{@String}` directive is the primary tool for matching text literals in a `uCalc::Transformer`. It handles the structural complexity of delimiters and escaping automatically.

### Supported Formats
* **Quotes**: Matches `'Single'`, `"Double"`, or `"""Triple"""` quoted blocks.
* **Interpolation**: Matches `$"{expression}"` patterns. Note that for pattern matching, the content within the braces `{ }` is captured based on balanced syntax; it does not require the internal identifiers to be defined unless the expression is being evaluated.

### Comparison with Specific Matchers
While `{@String}` captures any string literal, you can use more specific variants if your logic requires it:
* **`{@dqs}`**: Matches only double-quoted strings.
* **`{@sqs}`**: Matches only single-quoted strings.
* **`{@String}`**: Matches any string.

### Inverse Matching with `!`
The universal inversion operator `!` can be applied to this category:
* `{@String}`: Matches any string literal.
* `{!String}`: Matches any token that is **not** a string (e.g., numbers, identifiers, or operators).

### Advanced Capture: Suffix Indexing
When capturing a string with a named variable (e.g., `{@String:txt}`), the captured value includes the surrounding quotes. uCalc provides a powerful shortcut to access only the **inner content**:

* `{txt(0)}`: Returns the full string **with** quotes (e.g., `"Hello"`).
* `{txt(1)}`: Returns the "inner" content **without** quotes (e.g., `Hello`).  `{txt}` defaults to `{txt(1)}`

This is particularly useful when converting code to data formats (like XML or JSON) where delimiters must be stripped or changed.

* **Why uCalc?** Matching strings with regex is notoriously difficult due to escaping and greedy matching. `{@String}` leverages the lexer's pre-defined knowledge of where a string starts and ends, ensuring perfect accuracy even with nested quotes or escape characters.


**Examples:**

### Example ID: 176

**Description:** Matching by token type

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{@String:txt}", "<<InnerQuote={txt}><TxtWithQuotes={txt(0)}>>");
t.FromTo("{@Number:MyNum}", "<NumericValue={MyNum}>");
t.FromTo("{@Bracket:MyBrack}", "<Brack={MyBrack}>");
t.FromTo("{@CloseBracket:CloseBr}", "<CloseBrack={CloseBr}>");
t.FromTo("{@StatementSeparator:Sep}", "<Separator={Sep}>");
t.FromTo("{@Alphanumeric:alpha}", "<Alpha={alpha}>");
t.FromTo("{@Whitespace:ws}", "<whitespace count={@Eval: Length(ws)}>");
t.FromTo("{@Reducible:r}", "<Reducible={r}>");
t.FromTo("{@Newline}", "<New line{@Newline}>");

var s = [verbatim]This is   55.2*6 "Hello world";
'Single quote'(parenth)[/verbatim];

wl(t.Filter(s).@Matches().@Text())
```

**Output:**
```
<Alpha=This>
<whitespace count=1>
<Alpha=is>
<whitespace count=3>
<NumericValue=55.2>
<Reducible=*>
<NumericValue=6>
<whitespace count=1>
<<InnerQuote=Hello world><TxtWithQuotes="Hello world">>
<Separator=;>
<New line
>
<<InnerQuote=Single quote><TxtWithQuotes='Single quote'>>
<Brack=(>
<Alpha=parenth>
<CloseBrack=)>
```

---

### Example ID: 894

**Description:** Demonstrating the difference between the `(0)` and `(1)` index.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Capture the string and show both versions in the replacement
t.FromTo("{@String:txt}", "With: {txt(0)}, Without: {txt(1)}, Default: {txt}");

wl(t.Transform("'uCalc'"))
```

**Output:**
```
With: 'uCalc', Without: uCalc, Default: uCalc
```

---

### Example ID: 895

**Description:** Converting quoted strings into XML-style elements by stripping the original quotes.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Use {s(1)} to get just the text inside the quotes
t.FromTo("msg = {@String:s}", "<message>{s(1)}</message>");

var(string, input) = [verbatim]msg = "Welcome to uCalc!"[/verbatim];
wl(t.Transform(input))
```

**Output:**
```
<message>Welcome to uCalc!</message>
```

---

### Example ID: 896

**Description:** (Real World: Sensitive Data Redaction) Masking the content of all string literals in a log or script, while preserving the non-string code structure.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Replace every string literal with a placeholder
t.FromTo("{@String}", [verbatim]"[REDACTED]"[/verbatim]);

var(string, log) = [verbatim]UserLogin(id: 101, pass: 'secret123', name: "Admin")[/verbatim];
wl(t.Transform(log))
```

**Output:**
```
UserLogin(id: 101, pass: "[REDACTED]", name: "[REDACTED]")
```

---

---

## {@StringDQ} - ID: 834
/doc/reference/patterns/matching-by-token-category/{@stringdq}/

**Remarks:**

**Shortcut**: `{@dqs}`

**Description**: A specialized category matcher that identifies double-quoted string literals (`" "`), including triple double-quotes (`""" """`) and interpolated double-quoted strings.

The `{@StringDQ}` directive (shorthand `{@dqs}`) is used within a `uCalc::Transformer` to target literals specifically enclosed in double quotation marks. While the master `{@String}` (Topic 799) directive matches any string literal, `{@StringDQ}` provides the precision needed when a transformation only applies to a specific syntax style.

### Supported Formats
* **Standard Double Quotes**: `"Content"`
* **Triple Double Quotes**: `"""Multi-line content"""`
* **Interpolated Double Quotes**: `$"{expression}"` (Captured structurally via balanced braces).

### Advanced Capture: Suffix Indexing
When capturing a string with a named variable (e.g., `{@dqs:txt}`), you can control whether the delimiters are included in the replacement logic:

* `{txt(0)}`: Returns the full string **including** the double quotes (e.g., `"Hello"`).
* `{txt(1)}`: Returns the **inner** content only (e.g., `Hello`). `{txt}` defaults to `{txt(1)}`

### Comparison with Specific Matchers
| Directive | Scope | Use Case |
| :--- | :--- | :--- |
| **`{@String}`** | Any String | General data handling where quote style doesn't matter. |
| **`{@StringDQ}`** | `"` only | JSON parsing or C# code generation where `"` is mandatory. |
| **`{@StringSQ}`** | `'` only | SQL or Javascript specific transformations. |

### Inverse Matching with `!`
The universal inversion operator `!` can be applied to this category:
* `{@dqs}`: Matches a double-quoted string.
* `{!dqs}`: Matches any token that is **not** a double-quoted string (including single-quoted strings).

---

---

## Strategy & Critique
* **Precision:** In environments like **JSON**, where single quotes are invalid, `{@dqs}` is a mandatory tool for ensuring structural validity.
* **Redundancy:** Remind users that `{@dqs}` is a subset of `{@String}`. If a rule should apply to both types, use the parent directive to keep the code DRY (Don't Repeat Yourself).
* **Naming:** The shorthand `{@dqs}` is highly efficient, though the full name `{@StringDQ}` should be used in documentation for clarity.

Current Time: Tuesday, January 13, 2026 at 9:48 PM EST.

**Examples:**

---

## {@StringSQ} - ID: 835
/doc/reference/patterns/matching-by-token-category/{@stringsq}/

**Remarks:**

Similar to {@String} but only for single quoted strings.  Shortcut {@sqs}

---

## {@Whitespace} - ID: 801
/doc/reference/patterns/matching-by-token-category/{@whitespace}/

**Remarks:**

**Description**: A category matcher that identifies any token defined as whitespace, primarily horizontal spacing like spaces and tabs.

The `{@Whitespace}` directive (shorthand {@ws}) is used within a `uCalc::Transformer` to target non-printing characters used for spacing. Unlike many regular expression engines where `\s` includes newlines, uCalc typically distinguishes between **horizontal whitespace** (`{@Whitespace}`) and **vertical whitespace** (`{@Newline}`).

If you need for newline to be whitespace, you can modify it like this: `Tokens["_token_newline"].TypeOfToken =  TokenType::Whitespace;`

### Usage Context
In many parsers, whitespace is ignored or "skipped." However, when building a transformer that preserves formatting or cleans up code, `{@Whitespace}` allows you to precisely target and manipulate spacing without affecting the line structure.

* **Spaces and Tabs**: Automatically matches standard ASCII spaces and horizontal tabs.
* **Token Boundaries**: Because uCalc is token-aware, `{@Whitespace}` will not match characters inside a quoted string unless they have been explicitly tokenized as whitespace tokens by the engine.

### Inverse Matching with `!`
The universal inversion operator `!` can be applied to this category:
* `{@Whitespace}`: Matches a space or tab.
* `{!Whitespace}`: Matches any token that is **not** whitespace (e.g., numbers, identifiers, or punctuation).


**Examples:**

### Example ID: 179

**Description:** {@Whitespace}

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("{@Whitespace}", ",");

wl(t.Transform("This is   a 'small test' about ' whitespace ' tokens."))
```

**Output:**
```
This,is,a,'small test',about,' whitespace ',tokens.
```

---

### Example ID: 176

**Description:** Matching by token type

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{@String:txt}", "<<InnerQuote={txt}><TxtWithQuotes={txt(0)}>>");
t.FromTo("{@Number:MyNum}", "<NumericValue={MyNum}>");
t.FromTo("{@Bracket:MyBrack}", "<Brack={MyBrack}>");
t.FromTo("{@CloseBracket:CloseBr}", "<CloseBrack={CloseBr}>");
t.FromTo("{@StatementSeparator:Sep}", "<Separator={Sep}>");
t.FromTo("{@Alphanumeric:alpha}", "<Alpha={alpha}>");
t.FromTo("{@Whitespace:ws}", "<whitespace count={@Eval: Length(ws)}>");
t.FromTo("{@Reducible:r}", "<Reducible={r}>");
t.FromTo("{@Newline}", "<New line{@Newline}>");

var s = [verbatim]This is   55.2*6 "Hello world";
'Single quote'(parenth)[/verbatim];

wl(t.Filter(s).@Matches().@Text())
```

**Output:**
```
<Alpha=This>
<whitespace count=1>
<Alpha=is>
<whitespace count=3>
<NumericValue=55.2>
<Reducible=*>
<NumericValue=6>
<whitespace count=1>
<<InnerQuote=Hello world><TxtWithQuotes="Hello world">>
<Separator=;>
<New line
>
<<InnerQuote=Single quote><TxtWithQuotes='Single quote'>>
<Brack=(>
<Alpha=parenth>
<CloseBrack=)>
```

---

### Example ID: 223

**Description:** Using {@Whitespace} and {@Exec} to Count Indentation (for Python or YAML-like text)

**Code:**
```pseudocode
// Using {@Whitespace} to Count Indentation
// A common use case for parsing structured text (like Python or YAML)
// is capturing the exact whitespace at the start of a line.

uc.DefineVariable("IndentLen");

var t = uc.NewTransformer();
t.@Text("    Item 1"); // Indented by 4 spaces

// Capture the leading whitespace into 'w' and evaluate its length
t.FromTo("{@Whitespace:w} Item {id}", "<{@Self}>{@Exec: IndentLen = Length(w)}");
t.Transform();
// We can now analyze the captured whitespace
wl("Indentation length: ", uc.EvalStr("IndentLen"))
```

**Output:**
```
Indentation length: 4
```

---

### Example ID: 252

**Description:** Finding instances where there are two or more consecutive whitespace tokens and reducing them to a single space.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Match two whitespace tokens and replace with one space
t.FromTo("{@Whitespace}", " ");

var(string, messy) = "var    x   =  100;"
wl(t.Transform(messy))
```

**Output:**
```
var x = 100;
```

---

### Example ID: 889

**Description:** Replacing all horizontal whitespace with a visible underscore for debugging.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Whitespace}", "_");

wl(t.Transform("x = 10 + y"))
```

**Output:**
```
x_=_10_+_y
```

---

---

## Matching by token name ({@Token}) - ID: 807
/doc/reference/patterns/matching-by-token-name--{@token}/

**Remarks:**

**Description**: A high-precision matcher that identifies a token by its specific internal name (ID) rather than its general category.

The `{@Token}` directive is the most granular matching tool in the `uCalc::Transformer`. While other directives match broad categories (like `{@Number}` or `{@Whitespace}`), `{@Token}` allows you to target a single, specific entry in the engine's token table.

### Why use {@Token}?
In advanced parser development, you often need to distinguish between tokens that look identical but serve different structural roles. For example:
* **Internal Shortcuts**: Directives like `{@dq}` are actually shortcuts for `{@Token(_Token_QuoteChar_Double)}`.
* **Custom Tokens**: If you have added a specialized token via `uCalc.Tokens.Add` with a unique name like `MyCustomSeparator`, you can target it specifically using `{@Token(MyCustomSeparator)}`.

### Comparison: Category vs. Token
| Feature | Category Matcher (e.g., `{@Bracket}`) | Token Matcher (`{@Token}`) |
| :--- | :--- | :--- |
| **Scope** | Matches any opening bracket (`(`, `[`, `{`). | Matches only the specific token name provided. |
| **Precision** | High-level structural matching. | Low-level surgical matching. |
| **Flexibility** | Inherits engine-wide category settings. | Strict adherence to a single internal ID. |

### Inverse Matching with `!`
The universal inversion operator `!` can be applied to this directive:
* `{@Token(Name)}`: Matches only the specified token.
* `{!Token(Name)}`: Matches any token **except** the one specified.


**Examples:**

### Example ID: 185

**Description:** {@Token} - matching a token by name

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("{@String}", "<Any quoted {@Self}>");
t.FromTo("({@Token(String_Singlequoted)})", "<Single quoted {@Self}>");
t.FromTo("({@Token(String_Doublequoted)})", "<Double quoted {@Self}>");

var s = [verbatim]"Test" '123' ("abc") ('xyz')[/verbatim];
wl(t.Transform(s))
```

**Output:**
```
<Any quoted "Test"> <Any quoted '123'> <Double quoted ("abc")> <Single quoted ('xyz')>
```

---

### Example ID: 70

**Description:** Displays the complete list of default token definitions, showing their type, internal name, and regex pattern.

**Code:**
```pseudocode
// Lists all tokens currently defined for the expression evaluator.

wl("Token Count: ", uc.@ExpressionTokens().@Count())
wl("")
wl("Index  Type  Name: regex")
wl("========================")
var Tokens = uc.@ExpressionTokens();
foreach (var token in Tokens)
   w(Tokens.IndexOf(token))
   wl("  ", token.@Description(), "  ", token.@Name(), ": ", token.@Regex())
end for

// Note that the expression evaluator token list has a few extra tokens,
// related to hex/bin/oct notation, string interpolation, and imaginary number
// notation, which are not found in the default Transformer token list.
```

**Output:**
```
Token Count: 30

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
27  literal  _token_imaginaryunit: #i
28  tokentransform  _token_binaryhexoctalnotation: #[bho][0-9A-F]+
29  tokentransform  _token_stringinterpolationquote: \$['"]
```

---

---

## Pattern Methods - ID: 769
/doc/reference/patterns/pattern-methods/

**Remarks:**

A pattern method performs an action or returns a computed value.  Patterns are enclosed by curly braces, and inside the opening brace it starts with the @ symbol, followed by the method keyword, and optionally a colon and a body.

Some methods may appear in both the pattern and the replacement sections, while others may appear in only one or the other.



---

## Introduction - ID: 817
/doc/reference/patterns/pattern-methods/introduction/

**Remarks:**

**Description**: A comprehensive guide to the functional syntax, logic directives, and structural anchors used to define and evaluate transformation rules in uCalc.

**Pattern Methods** are specialized instructions enclosed in `{ }` that allow the uCalc Transformer to move beyond literal text matching. These methods interact with the uCalc engine to identify token categories, perform calculations, or even execute external logic during a transformation.

### 1. The Evaluation Timeline (`@` vs `@@`)

The most powerful aspect of uCalc Pattern Methods is the ability to control **when** logic is executed using the `@` prefix. This applies to almost all Directives:

| Syntax | Name | Timing | Behavior |
| :--- | :--- | :--- | :--- |
| **`{@Method}`** | **Static Directive** | **Rule Creation** | Evaluated once when the rule is defined. Ideal for constant calculations or loading external templates. |
| **`{@@Method}`** | **Dynamic Directive** | **Match Time** | Evaluated every time the pattern finds a match. Ideal for logic that depends on captured text. |

---

### 2. Functional Categories

#### **Directives (Commands)**
Directives perform actions. Note that variables captured in the pattern (e.g., `{@Number:val}`) are accessed **by name** without additional curly braces inside these directives.
* `{@Eval}` / `{@@Eval}`: Evaluates an expression. Example: `{@@Eval:val * 2}`.
* `{@File}` / `{@@File}`: Inserts file content. Example: `{@@File:filename}` where `filename` is a captured variable.
* `{@Define}` / `{@@Define}`: Defines variables/functions in the uCalc evaluator space.
* `{@Exec}` / `{@@Exec}`: Executes code without returning a value to the pattern/replacement.
* `{@Comment}`: Annotates patterns; ignored during parsing (irrelevant to `@`/`@@`).

#### **Structural Matchers (Anchors)**
These identify specific locations in the text stream:
* `{@Beginning}`: Matches only if at the start of the source string.
* `{@End}`: Matches only if at the very end of the source string.
* `{@All}`: Captures the entire source string as a single entity.
* `{@Stop}`: Truncates the saved match at this specific point in the pattern.

#### **Replacement-Only Keywords**
Reserved for the "To" part of a transformation:
* `{@Self}`: The entire captured pattern.
* `{@Doc}`: The entire source document string.
* `{@Param:n}`: References a specific captured sub-part by number.

#### **Character Literals (`{#}`)**
Injects characters by ASCII code. `{#65#66#67}` results in `ABC`. Useful for non-printing characters like `{#0}` (Null) or `{#10}` (Line Feed).


---

## {@@...} - ID: 795
/doc/reference/patterns/pattern-methods/{@@...}/

**Remarks:**

**Description**: The syntax used to trigger engine-level logic dynamically at the moment a pattern match occurs, allowing the directive to use data captured during the match.

The **`@@`** prefix is a modifier that shifts the execution of a directive from **Rule Creation Time** to **Match Time**. While a single-`@` directive (like `{@File}`) is resolved once when the rule is defined, a double-`@@` directive is resolved every single time the pattern finds a match in the source text.

### Dynamic Resolution
Match-time directives are the key to building "intelligent" transformers. Because they execute during the transformation process, they have access to the **local variables** captured by the pattern match.

### Common Match-Time Directives
* **`{@@Eval:expr}`**: Evaluates an expression using captured data.
* **`{@@File:var}`**: Loads a file whose name is determined by a captured variable.
* **`{@@Define:var}`**: Dynamically sets a variable or function in the evaluator space based on the match.
* **`{@@Exec:code}`**: Runs a procedure during the match without returning text.

### Variable Syntax
When using variables captured in a pattern (e.g., `{@Number:n}`) within a `{@@...}` directive, do not use curly braces. The variable is already resident in the evaluator space for the duration of that specific match.
* **Correct**: `{@@Eval:n * 10}`
* **Incorrect**: `{@@Eval:{n} * 10}`


**Examples:**

### Example ID: 201

**Description:** {@Eval}, {@@Eval}, and escaping special characters in a pattern

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("'['{word}']'", "{@Eval: UCase(word)}");
t.FromTo("'{'{expr}'}'", "{@@Eval: expr}");

wl(t.Transform("Words like [this] and [that]."))
wl(t.Transform("Is {5*3} bigger than {5^3}?"))
```

**Output:**
```
Words like THIS and THAT.
Is 15 bigger than 125?
```

---

### Example ID: 1359

**Description:** A practical, real-world example of integration: using the Transformer and Expression Parser together to create a simple template engine that replaces placeholders with evaluated data.

**Code:**
```pseudocode
// Define the data context for our template
uc.DefineVariable("user = 'Alice'");
uc.DefineVariable("score = 95");

// Define the template with placeholders
var myTemplate = "User: {user}, Score: {score * 10}, Status: {IIf(score > 90, 'Excellent', 'Good')}";

var t = uc.NewTransformer();
// This single rule finds placeholders like {...}
// and uses the Expression Parser ({@@Eval}) to evaluate the content inside.
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");

wl(t.Transform(myTemplate))

```

**Output:**
```
User: Alice, Score: 950, Status: Excellent
```

---

---

## {@All} - ID: 814
/doc/reference/patterns/pattern-methods/{@all}/

**Remarks:**

## Global Capture Directive

**Description**: A structural directive that represents the entire source text being processed, regardless of token boundaries or internal formatting.

The `{@All}` directive is used within a `uCalc::Transformer` to target the full scope of the input string. While most directives (like `{@Number}` or `{@Alpha}`) focus on specific tokens, `{@All}` provides a way to interact with the document as a single, unified entity.

### Purpose and Scope
`{@All}` is typically used when you need to perform a "Document-Level" transformation. Instead of matching individual pieces, you are matching the **entirety** of what was passed into the `Transform()` method. 

* **Implicit Context**: It ignores standard delimiters (like whitespace or newlines) and treats everything from the first character to the last as part of the match.
* **Anchor Pairing**: It is often used in conjunction with `{@Beginning}` and `{@End}` to ensure the pattern represents the absolute total content of the source.

### Contrast with `{@Doc}`
In the replacement string of a rule:
* **`{@Self}`**: Refers to the text that was specifically matched by your pattern.
* **`{@Doc}`**: Refers to the entire original source document.
* **`{@All}`**: When used in a **pattern**, it causes the capture to encompass the entire input.


**Examples:**

### Example ID: 203

**Description:** {@All}

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{@All}", "<<{@Self}>>");

wl(t.Transform("This is a test"))
```

**Output:**
```
<<This is a test>>
```

---

---

## {@Beginning} - ID: 777
/doc/reference/patterns/pattern-methods/{@beginning}/

**Remarks:**

## Start-of-String Anchor

**Description**: A structural anchor directive that restricts a pattern match to the very beginning of the source text.

The `{@Beginning}` directive is used within a `uCalc::Transformer` to ensure that a specific pattern only triggers if it is found at the absolute start of the input string. It is a zero-width anchor, meaning it does not "consume" any tokens itself; it simply validates that the parser's current position is at index zero.

### Positional Logic
In many transformation tasks, the first few tokens of a file contain metadata, headers, or unique identifiers (like a "shebang" in scripts). `{@Beginning}` allows you to target these elements safely without accidentally matching similar patterns elsewhere in the document.

* **Comparison to Regex**: `{@Beginning}` is functionally equivalent to the `^` anchor in standard Regular Expressions when used at the start of a pattern.
* **Token Awareness**: Even if your input starts with whitespace or comments, `{@Beginning}` refers to the start of the entire source string, unless the engine is configured to skip those tokens during the initial anchor check.

---

## Examples

### 1. Succinct (Quick Start: Header Identification)
Replacing a specific keyword only if it appears at the very start of the document.

```[body]
New(uCalc::Transformer, t)
// Match 'ID' only if it's the first thing in the string
t.FromTo("{@Beginning} ID", "IDENTIFIER:")

wl(t.Transform("ID 12345"))
wl(t.Transform("User ID 123"))
```
**[Expected Output]**
`IDENTIFIER: 12345`
`User ID 123` (No change, since 'ID' was not at the beginning)

### 2. Practical (Real World: Script Shebang Transpiler)
Using `{@Beginning}` to find a script indicator and convert it to a standardized header, while ignoring similar text in the body.

```[body]
New(uCalc::Transformer, t)
// Match a '#' followed by a word only at the start
t.FromTo("{@Beginning} # {@Alpha:lang}", "--- Language: {lang} ---")

var(string, script) = "#uCalc\nprint \"Hello\"; #Note: comments"
wl(t.Transform(script))
```
**[Expected Output]**
`--- Language: uCalc ---`
`print "Hello"; #Note: comments`

### 3. Internal Test (Whitespace Sensitivity)
Verifying that `{@Beginning}` respects the absolute start, even when adjacent to other tokens.

```[body]
New(uCalc::Transformer, t)
t.FromTo("{@Beginning}", "[START]")

// Note: If the engine doesn't auto-skip leading spaces, 
// this will insert [START] at the very front.
wl(t.Transform("Data"))
```
**[Expected Output]**
`[START]Data`

---

## Strategy & Critique
* **Performance Optimization**: Positional anchors are incredibly efficient. When the transformer sees `{@Beginning}`, it can immediately skip the rule if the current match attempt is not at the start of the string, saving significant processing time in large documents.
* **Naming**: The name is clear, though some developers might expect `{@Start}`. Using `{@Beginning}` aligns with a more descriptive, semantic approach to structural anchors.
* **Critique**: If used in a multi-line document where "Beginning" should apply to every line, this directive might be too restrictive. In those cases, use line-based logic instead.
* **See Also**: Refer to **Topic 792** (`{@End}`) for anchoring to the conclusion of the source string.

**Examples:**

---

## {@Comment} - ID: 775
/doc/reference/patterns/pattern-methods/{@comment}/

**Remarks:**

## Pattern Annotation Directive

**Description**: A non-functional structural directive used to include notes, explanations, or labels within a transformation pattern without affecting the match or the output.

The `{@Comment}` directive is the annotation tool of the `uCalc::Transformer`. It allows developers to document complex pattern logic directly within the pattern string itself.

### Functional Invisibility
When the uCalc engine parses a pattern containing `{@Comment}`, it effectively "strips" the comment directive. It does not look for a match for the comment content, nor does it insert the comment into the replacement result. 

* **In the Pattern**: `{@Comment: This matches a name}{@Alpha:name}` is treated exactly like `{@Alpha:name}`.
* **In the Replacement**: `Hello{@Comment: friendly greeting} {name}` is treated exactly like `Hello {name}`.

### Maintenance and Clarity
In large-scale transformation projects where patterns can become quite dense, `{@Comment}` provides a way to:
1.  Explain the purpose of specific structural segments.
2.  Label complex capture groups.
3.  Include internal versioning or metadata within a specific rule.

---

## Examples

### 1. Succinct (Quick Start: Basic Annotation)
Adding a note to a pattern that identifies a specific keyword.

```[body]
New(uCalc::Transformer, t)
// The comment is ignored by the engine
t.FromTo("{@Comment: match the keyword} KEY", "FOUND")

wl(t.Transform("KEY"))
```
**[Expected Output]**
`FOUND`

### 2. Practical (Real World: Documenting Complex Logic)
Using comments to clarify a multi-part transpiler rule that converts assignment syntax.

```[body]
New(uCalc::Transformer, t)
t.FromTo(
  "let {@Comment: identifier} {@Alpha:id} = {@Comment: value} {@Number:val}",
  "set {id} = {val}"
)

var(string, input) = "let x = 10"
wl(t.Transform(input))
```
**[Expected Output]**
`set x = 10`

### 3. Internal Test (Placement Versatility)
Verifying that `{@Comment}` can be placed anywhere, even in the replacement string, without altering the result.

```[body]
New(uCalc::Transformer, t)
t.FromTo("{@Alpha:a}", "Word:{@Comment: add label} {a}")

wl(t.Transform("Hello"))
```
**[Expected Output]**
`Word: Hello`

---

## Strategy & Critique
* **Documentation "At the Source"**: The biggest benefit of `{@Comment}` is that the explanation lives inside the code it describes. This prevents documentation from becoming stale or "drifting" away from the actual logic.
* **Readability Trade-off**: While useful, over-commenting short patterns can make them visually cluttered. Use `{@Comment}` primarily for non-obvious logic or structural anchors.
* **Critique**: Unlike other directives, the `@@` prefix is irrelevant for `{@Comment}` because there is no execution or evaluation logic to shift from rule-creation to match-time.
* **See Also**: Refer to **Topic 817** (Pattern Methods Introduction) for an overview of other functional directives.

**Examples:**

### Example ID: 205

**Description:** {@Comment}

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a {@Comment: Ignore this} b c", "x{@Comment: ignore} y z");

wl(t.Transform("a b. a b c. abc."))
```

**Output:**
```
a b. x y z. abc.
```

---

---

## {@Define} - ID: 815
/doc/reference/patterns/pattern-methods/{@define}/

**Remarks:**

## Evaluator Configuration Directive

**Description**: A directive used to define variables, functions, or other entities within the uCalc evaluator space during rule creation or at match-time.

The `{@Define}` directive allows a transformation pattern to modify the engine's internal state. It is primarily used to set up variables or logic that will be referenced by subsequent `{@Eval}` or `{@@Eval}` directives.

### Required Syntax: Type Prefix
Definitions must specify the type of entity being created. Common types include `Variable:`, `Function:`, and `Operator:`. Failing to include a type prefix may result in the engine failing to categorize the definition properly.

* **Format**: `{@Define: [Type]: [Definition]}`

### Static vs. Dynamic Definitions
* **`{@Define}` (Static)**: Executed once when the `FromTo` rule is first created. The definition is fixed.
* **`{@@Define}` (Dynamic)**: Executed every time a match is found. This is significantly more powerful because the **definition itself** can be constructed from captured text.

While a static definition might set a global constant, a dynamic definition can "learn" from the document being parsed—for example, capturing a variable assignment in a script and making it available to the uCalc engine for the rest of the transformation.

---

## Examples

### 1. Succinct (Quick Start: Static Definition)
Defining a constant PI value at the start of a transformation pass.

```[body]
New(uCalc::Transformer, t)
// Define a variable once during rule initialization
t.FromTo("init_math", "{@Define: Variable: pi = 3.14159}Math Initialized")

wl(t.Transform("init_math"))
```
**[Expected Output]**
`Math Initialized`

### 2. Practical (Real World: Match-Driven Variable Definitions)
This example demonstrates the power of `{@@Define}` where the matched content dictates what is defined.

```[body]
New(uCalc::Transformer, t)
// Capture a variable name and its value to define it in the engine
t.FromTo("const {@Alpha:name} = {@Number:val}", "{@@Define: Variable: {name} = {val}}Property {name} registered")

// Use the newly defined variable in a later calculation
t.FromTo("calc({@Alpha:name})", "{@@Eval: {name} * 1.1}")

var(string, input) = "const tax = 0.15; calc(tax)"
wl(t.Transform(input))
```
**[Expected Output]**
`Property tax registered; 0.165`

### 3. Internal Test (Dynamic Expression Evaluation)
The real utility of `{@@...}` directives is when the expression itself comes from text, rather than being a hardcoded formula.

```[body]
New(uCalc::Transformer, t)
// Capture a math formula provided in the text and solve it
t.FromTo("evaluate: {@All:expr}", "Result: {@@Eval: expr}")

// In this case, 'expr' is not just a value, but the formula itself
wl(t.Transform("evaluate: 10 + 20 * 5"))
```
**[Expected Output]**
`Result: 110`

---

## Strategy & Critique
* **Creation-time vs Match-time**: The `@` vs `@@` distinction is the most important concept to master. `{@@Define}` allows the rule to be self-modifying based on the input stream.
* **Type-Strict State**: Requiring the `Variable:` or `Function:` prefix ensures that the evaluator space remains organized and prevents naming collisions.
* **Critique**: Because `{@@Define}` can modify global state, developers should be careful when running parallel transformations on the same engine instance.
* **See Also**: Refer to **Topic 33** for a full list of supported definition types.

**Examples:**

### Example ID: 206

**Description:** {@Define}

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.Pattern("{@Define: Var: xyz = 123}");
t.FromTo("abc", "{@Eval: xyz * 10}");
wl(t.Transform("The value is: abc"))

```

**Output:**
```
The value is: 1230
```

---

---

## {@Doc} - ID: 788
/doc/reference/patterns/pattern-methods/{@doc}/

**Remarks:**

## Source Document Keyword

**Description**: A replacement-only keyword that returns the entire source text of the document currently being transformed.

The `{@Doc}` keyword is used within the replacement string of a `uCalc::Transformer` rule. Unlike pattern-based variables that refer only to the captured segment of text, `{@Doc}` provides a way to reference the absolute source string in its entirety.

### Usage Context
`{@Doc}` is primarily used when a transformation needs to wrap or re-contextualize the entire input. For example, if a rule identifies a specific document type header, it can use `{@Doc}` to wrap the entire file content in a new set of tags.

### Comparison: {@Doc} vs {@Self}
* **`{@Self}`**: Returns only the specific portion of text that was matched by the pattern.
* **`{@Doc}`**: Returns the full original source document that was passed into the transformer.

### Important Note on Evaluation
`{@Doc}` typically returns the document as it existed at the start of the current transformation pass. If multiple rules are firing sequentially, `{@Doc}` may not reflect the intermediate "dirty" state of the document until the pass is completed.

---

## Examples

### 1. Succinct (Quick Start: Global Wrapper)
Wrapping the entire document in a Markdown code block whenever a specific trigger keyword is found.

```[body]
New(uCalc::Transformer, t)
// Match 'WRAP_ALL' and replace with the whole doc inside backticks
t.FromTo("WRAP_ALL", "```\n{@Doc}\n```")

wl(t.Transform("Line 1\nLine 2\nWRAP_ALL"))
```
**[Expected Output]**
```
Line 1
Line 2
WRAP_ALL
```

### 2. Practical (Real World: Signature/Footer Injection)
Using a match at the end of a file to append a signature block while preserving the entire document content.

```[body]
New(uCalc::Transformer, t)
// Match the word 'END' at the end of the doc and append a footer
t.FromTo("END{@End}", "{@Doc}\n---\nGenerated by uCalc")

var(string, input) = "Document Content\nEND"
wl(t.Transform(input))
```
**[Expected Output]**
```
Document Content
END
---
Generated by uCalc
```

### 3. Internal Test (Document Integrity)
Verifying that `{@Doc}` captures the full source regardless of which specific token triggers the match.

```[body]
New(uCalc::Transformer, t)
t.FromTo("TRIGGER", "FULL_DOC_IS: [{@Doc}]")

wl(t.Transform("Start TRIGGER End"))
```
**[Expected Output]**
`Start FULL_DOC_IS: [Start TRIGGER End] End`

---

## Strategy & Critique
* **Efficiency for Large Files**: Using `{@Doc}` in a replacement causes the engine to handle a potentially very large string. In multi-megabyte files, it is generally better to use positional anchors like `{@Beginning}` or `{@End}` rather than constantly referencing the whole document in every rule.
* **Naming**: The name `{@Doc}` is concise but might be confused with a structured "document object" (like a DOM). In this context, it is strictly the raw source string.
* **Critique**: If `{@Doc}` is used in a rule that matches multiple times, the replacement will result in the entire document being inserted multiple times. It is almost always best used in rules that are guaranteed to match only once (e.g., using `{@Beginning}` or `{@End}`).

**Examples:**

### Example ID: 207

**Description:** {@Doc}

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a test", "'{@Self}' is part of: '{@Doc}'");

// Note: .Str(0) here is a shortcut for .Matches().Str(0)
wl(t.Transform("This sentence is just a test").Str(0))
```

**Output:**
```
'a test' is part of: 'This sentence is just a test'
```

---

---

## {@End} - ID: 778
/doc/reference/patterns/pattern-methods/{@end}/

**Remarks:**

## End-of-String Anchor

**Description**: A structural anchor directive that restricts a pattern match to the very end of the source text.

The `{@End}` directive is used within a `uCalc::Transformer` to ensure that a specific pattern only succeeds if it is found at the absolute conclusion of the input string. Like `{@Beginning}`, it is a zero-width anchor; it doesn't "consume" tokens, but validates that no more tokens remain in the stream following the match.

### Positional Logic
`{@End}` is essential for tasks that require document-level integrity. It is commonly used to:
* Append footers or closing tags.
* Validate that a file ends with a required delimiter (like a semicolon or closing brace).
* Trigger a final "clean-up" calculation using `{@@Eval}` or `{@Doc}`.

* **Comparison to Regex**: `{@End}` is functionally equivalent to the `$` anchor in standard Regular Expressions.
* **Token Awareness**: In a token-based engine, `{@End}` ensures that the preceding pattern accounts for the final token in the stream before the end-of-file (EOF) state is reached.

---

## Examples

### 1. Succinct (Quick Start: EOF Identification)
Matching a specific keyword only if it is the very last thing in the document.

```[body]
New(uCalc::Transformer, t)
// Match 'DONE' only if it's at the very end
t.FromTo("DONE {@End}", "[FINISH]")

wl(t.Transform("Processing... DONE"))
wl(t.Transform("DONE - continuing..."))
```
**[Expected Output]**
`Processing... [FINISH]`
`DONE - continuing...` (No change, since 'DONE' was not at the end)

### 2. Practical (Real World: Automatic Document Footer)
Using `{@End}` to identify the last word of a document and automatically appending a generated timestamp or signature.

```[body]
New(uCalc::Transformer, t)
// Match the last word and append a footer
t.FromTo("{@Alpha:last} {@End}", "{last}\n--- End of Report ---")

var(string, doc) = "Final summary text"
wl(t.Transform(doc))
```
**[Expected Output]**
```
Final summary text
--- End of Report ---
```

### 3. Internal Test (Boundary Integrity)
Verifying that `{@End}` handles various token types at the boundary correctly.

```[body]
New(uCalc::Transformer, t)
t.FromTo("{@End}", " [EOF]")

wl(t.Transform("12345"))
```
**[Expected Output]**
`12345 [EOF]`

---

## Strategy & Critique
* **Logical Symmetry**: `{@End}` provides the necessary symmetry to `{@Beginning}`, allowing developers to define rules for both boundaries of a document.
* **Performance**: Just like its counterpart, `{@End}` allows for fast-fail logic. If a pattern contains `{@End}` but the current token is not the last one, the engine can move on immediately.
* **Naming**: Consistent with `{@Beginning}`. 
* **Critique**: In many programming languages, a "newline" often follows the last meaningful character. Depending on engine settings, you may need to decide if your pattern matches before or after a final `{@Newline}`.
* **See Also**: Refer to **Topic 777** (`{@Beginning}`) for anchoring to the start of the source string.

**Examples:**

---

## {@Eval} - ID: 771
/doc/reference/patterns/pattern-methods/{@eval}/

**Remarks:**

## Evaluator Directive

**Description**: A directive that evaluates expressions within a pattern or replacement. In replacements, it differentiates between pre-parsed static expressions (`@`) and dynamically parsed expressions (`@@`).

The `{@Eval}` directive allows the `uCalc::Transformer` to leverage the full power of the uCalc mathematical and logical engine. Its behavior depends on where it is used and which prefix is applied.

### 1. Within a Pattern (Definition)
In the **From** (pattern) part of a rule, only `{@Eval}` is available. 
* It is evaluated **once** when the rule is defined.
* The result of the evaluation is inserted back into the pattern as a literal.
* **Example**: `{@Eval: 1 + 1}` in a pattern becomes `2`.

### 2. Within a Replacement (Transformation)
In the **To** (replacement) part of a rule, the prefix determines how the expression is handled:

#### **`{@Eval: expression}` (Parse Once)**
This is the high-performance mode. 
* The expression is **parsed/compiled once** when the rule is created.
* With each match, the engine simply evaluates the pre-parsed formula using current variable values.
* Conceptually similar to using `uCalc.Parse()` (Topic 69) and then calling `EvaluateStr()` (Topic 142) repeatedly.
* Use this when the formula is constant but the variable values change.

#### **`{@@Eval: expression}` (Parse Each Time)**
This is the high-flexibility mode.
* The expression is **parsed and evaluated every time** a match is found.
* This allows the expression itself (the formula) to be different for each match.
* Conceptually similar to calling `uCalc.EvalStr()` (Topic 47) for every match.
* Use this when the text captured from the source document *is* the expression you want to solve.

### Variable Handling & Content
Captured pattern variables (e.g., `{@Number:var}`) are accessible inside the evaluator context.
* **In `{@Eval}`**: `var` refers to the captured text as a literal string. If `var` captured `1+1`, `{@Eval: var}` returns the string `1+1`.
* **In `{@@Eval}`**: `var` is treated as a string to be evaluated. If `var` captured `1+1`, `{@@Eval: var}` returns `2`.

### Variable Syntax
When using variables captured within a pattern (e.g., `{@Number:x}`), you refer to them by their name directly inside the evaluation string. Do not use additional curly braces.
* **Correct**: `{@@Eval: x * 2}`
* **Incorrect**: `{@@Eval: {x} * 2}`

### Result Versatility
The evaluated result can be anything the uCalc engine supports, including numbers, and strings. The engine simply "pastes" the result of the evaluation into the location where the directive was placed.

Text passed to {@Eval} from a pattern variable is passed as a string.  If the string contains a value that you want to treat as numeric, you can convert it by casting it, for instance, with double, as in `double(MyStr)`.  Variables defined in the parent uCalc object are also available to `{@Eval}`, in their native type.  All results are converted back to a string when inserted into the replacement text (so you don't need to do an extra step for that).

---

## Examples

### 1. Succinct (Quick Start: Evaluation Logic)
Showing how `{@Eval}` in a pattern is a one-time operation.

```[body]
New(uCalc::Transformer, t)
// The pattern literally looks for "2" because the Eval happens at definition
t.FromTo("val = {@Eval: 1 + 1}", "MATCH")

wl(t.Transform("val = 2"))
```
**[Expected Output]**
`MATCH`

### 2. Practical (Real World: Pre-Parsed Formula)
Using `{@Eval}` in a replacement for high-performance unit conversion where the formula is fixed.

```[body]
New(uCalc::Transformer, t)
// Formula is parsed once; 'c' value changes per match
t.FromTo("{@Number:c}C", "{@Eval: c * 9 / 5 + 32}F")

wl(t.Transform("0C, 100C"))
```
**[Expected Output]**
`32F, 212F`

### 2. Practical (Real World: Dynamic Discounting)
Calculating a 15% discount on a captured price value found in the source text.

```[body]
New(uCalc::Transformer, t)
// Capture 'p' and calculate the discount for every occurrence
t.FromTo("Price: {@Number:p}", "Sale Price: {@@Eval: p * 0.85}")

var(string, input) = "Price: 100, Price: 200"
wl(t.Transform(input))
```
**[Expected Output]**
`Sale Price: 85, Sale Price: 170`

### 3. Internal Test (Meta-Expression Evaluation)
Using `{@@Eval}` to solve a math problem that was captured as text from the source document.

```[body]
New(uCalc::Transformer, t)
// Capture the text '1+1' into 'v'
t.FromTo("solve: {v}", "Result: {@@Eval: v}")

// {@@Eval} parses the string "1+1" and evaluates it to 2.
// {@Eval: v} would have just returned the string "1+1".
wl(t.Transform("solve: 1+1"))
```
**[Expected Output]**
`Result: 2`

---

## Strategy & Critique
* **Performance Choice**: Developers should default to `{@Eval}` in replacements for speed, unless they explicitly need to evaluate strings captured from the source code as formulas.
* **Expression Persistence**: Master the concept that `{@Eval}` keeps the formula constant while `{@@Eval}` allows the formula to be dynamic.
* **Lenient Typing**: Both versions are lenient with input types, but `{@@Eval}` is specifically designed to handle "code-as-data" scenarios.

Current Time: Wednesday, January 14, 2026 at 3:11 PM EST.

**Examples:**

### Example ID: 174

**Description:** Converting from Celsius to Fahrenheit with the Transformer

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Define the pattern first
t.FromTo("Temperature: {temp} C", "temperature: {@Eval: Double(temp) * 1.8 + 32} F");

// Perform the Transform() operation
wl(t.Transform("Here is the temperature: 22.5 C"))
```

**Output:**
```
Here is the temperature: 72.5 F
```

---

### Example ID: 201

**Description:** {@Eval}, {@@Eval}, and escaping special characters in a pattern

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("'['{word}']'", "{@Eval: UCase(word)}");
t.FromTo("'{'{expr}'}'", "{@@Eval: expr}");

wl(t.Transform("Words like [this] and [that]."))
wl(t.Transform("Is {5*3} bigger than {5^3}?"))
```

**Output:**
```
Words like THIS and THAT.
Is 15 bigger than 125?
```

---

### Example ID: 1359

**Description:** A practical, real-world example of integration: using the Transformer and Expression Parser together to create a simple template engine that replaces placeholders with evaluated data.

**Code:**
```pseudocode
// Define the data context for our template
uc.DefineVariable("user = 'Alice'");
uc.DefineVariable("score = 95");

// Define the template with placeholders
var myTemplate = "User: {user}, Score: {score * 10}, Status: {IIf(score > 90, 'Excellent', 'Good')}";

var t = uc.NewTransformer();
// This single rule finds placeholders like {...}
// and uses the Expression Parser ({@@Eval}) to evaluate the content inside.
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");

wl(t.Transform(myTemplate))

```

**Output:**
```
User: Alice, Score: 950, Status: Excellent
```

---

---

## {@Exec} - ID: 772
/doc/reference/patterns/pattern-methods/{@exec}/

**Remarks:**

## Execution Directive

**Description**: A directive used to execute mathematical expressions or logic commands without inserting a return value into the output. It is primarily used for side effects.

The `{@Exec}` directive is functionally identical to `{@Eval}`, but with one key difference: it is "void." It performs the requested calculation or command within the uCalc evaluator space, but the result is discarded rather than being pasted into the pattern or replacement string.

### Purpose: Pure Side Effects
Use `{@Exec}` when you need to update internal state without altering the text being transformed. Common use cases include:
* **Logging**: Triggering a print statement or log update.
* **Counter/State Management**: Incrementing a match counter or toggling a boolean flag.
* **Initialization**: Setting up evaluator variables during rule creation.

### Timing: Rule Creation (@) vs. Match Time (@@)
* **`{@Exec: expression}` (Static)**: Executed **once** when the rule is defined.
* **`{@@Exec: expression}` (Dynamic)**: Executed **for every match** found in the source text.

### Variable Access
Like `{@Eval}`, `{@Exec}` has full access to variables captured in the pattern. These variables are referenced by name without curly braces.
* **Example**: `{@@Exec: match_count = match_count + 1}`.

---

## Examples

### 1. Succinct (Quick Start: Initialization Log)
Triggering a console message when a specific rule is initialized by the transformer.

```[body]
New(uCalc::Transformer, t)
// 'print' is executed at rule creation; nothing is added to the pattern
t.FromTo("{@Exec: print('Rule initialized')}TRIGGER", "MATCH")

wl(t.Transform("TRIGGER"))
```
**[Expected Output]**
`MATCH`
*(Console: Rule initialized)*

### 2. Practical (Real World: Match Counter)
Incrementing a variable in the background for every match without changing the source text itself.

```[body]
New(uCalc::Transformer, t)
// Initialize the counter statically
t.FromTo("{@Beginning}", "{@Define: Variable: cnt = 0}")

// Increment the counter dynamically for every word found
t.FromTo("{@Alpha}", "{@@Exec: cnt = cnt + 1}{@Self}")

// At the end, display the result
t.FromTo("{@End}", " [Total Words: {@@Eval: cnt}]")

wl(t.Transform("One two three"))
```
**[Expected Output]**
`One two three [Total Words: 3]`

### 3. Internal Test (Void Behavior)
Verifying that `{@Exec}` produces absolutely no output characters in the resulting string.

```[body]
New(uCalc::Transformer, t)
// Despite the math result being 100, nothing is inserted here
t.FromTo("TEST", "Result:{@Exec: 50 + 50}!")

wl(t.Transform("TEST"))
```
**[Expected Output]**
`Result:!`

---

## Strategy & Critique
* **Structural Integrity**: `{@Exec}` is invaluable when you need to perform logic at a specific token location but do not want to disturb the spacing or content of that location.
* **Performance**: Since `{@Exec}` doesn't need to format or return a string to the transformer, it is slightly more efficient than `{@Eval}` for pure state updates.
* **Critique**: Because it is invisible, debugging `{@Exec}` logic can be difficult. It is recommended to use `print()` statements inside the expression during development to verify that the side effects are occurring as expected.
* **See Also**: Refer to **Topic 771** (`{@Eval}`) for the version of this directive that returns values.

**Examples:**

### Example ID: 216

**Description:** {@Exec}

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.Pattern("{@Define: Var: Count_a = 0}");
t.Pattern("{@Define: Var: Count_an = 0}");

t.FromTo("a", "{@Self}{@Exec: Count_a++}");
t.FromTo("an", "{@Self}{@Exec: Count_an++}");
t.FromTo(".", [verbatim]{@nl}'a' occurs {@Eval: Count_a} times
'an' occurs {@Eval: Count_an} times[/verbatim]);

// Note: it is counting "a" as a token, not as a character.
wl(t.Transform("An apple, an eagle, a cat, an orange, a tree."))
```

**Output:**
```
An apple, an eagle, a cat, an orange, a tree
'a' occurs 2 times
'an' occurs 3 times
```

---

---

## {@File} - ID: 773
/doc/reference/patterns/pattern-methods/{@file}/

**Remarks:**

`{@File}` lets you insert the contents of a file into a pattern definition or replacement text.  Let's say you have a file called Dictionary.txt, which consists of:

`a | all | the | words | in | the | dictionary | z`

You can define a pattern such as: `The word {userword: {@File:'c:\text\Dictionary.txt'} }`

The definition will be transformed to: `The word {userword: a | all | the | words | in | the | dictionary | z }`

In the above example we used a literal file name within quotes.  But `{@File}` can take any string that when evaluated with uCalc.EvalStr would return a file name.  So you could have `{@File:'c:\text' + '\Dictionary.txt'}` or `{@File:MyFileName}` where *MyFileName* is a string variable defined in the parent uCalc object, which contains the file name.




# {@File}: File Injection Directive

**Description**: A directive used to load the contents of an external file and insert it into a pattern definition or a transformation replacement string.

## Remarks

The `{@File}` directive allows the `uCalc::Transformer` to reference external text resources. This is particularly useful for separating logic from content, such as storing large templates, configuration blocks, or documentation footers in separate files.

### Timing: Static (@) vs. Dynamic (@@)
Like other directives, the behavior of `{@File}` depends on the prefix used in the replacement:

* **`{@File: filename}` (Static)**: The file is loaded **once** at the moment the rule is created. The contents are "baked" into the rule definition as literal text.
* **`{@@File: filename}` (Dynamic)**: The file is loaded **for every match** found during transformation. This allows the filename itself to be captured from the source document.

### Path Resolution
The `filename` parameter should follow the standard path rules of the environment where uCalc is running. If the file cannot be found, the engine will typically insert an empty string or a descriptive error depending on the current error-handling configuration.

### Content Treatment
Unlike `{@Eval}`, which parses the content as an expression, `{@File}` simply inserts the raw text of the file. If you wish to evaluate the contents of a file as a uCalc expression, you should combine it with `{@Eval}`, for example: `{@Eval: {@File: math_rules.txt}}`.

---

## Examples

### 1. Succinct (Quick Start: Template Injection)
Inserting a standard copyright notice from a file into a document header.

```[body]
New(uCalc::Transformer, t)
// Load the license once during rule setup
t.FromTo("{@Beginning} COPYRIGHT", "{@File: license.txt}")

wl(t.Transform("COPYRIGHT\nSource Code..."))
```
**[Expected Output]**
```
(Contents of license.txt)
Source Code...
```

### 2. Practical (Real World: Match-Driven File Inclusion)
Capturing a "module" name from the source text and dynamically loading the corresponding documentation file.

```[body]
New(uCalc::Transformer, t)
// Capture 'mod' and use it to find the filename dynamically
t.FromTo("import_doc {@Alpha:mod}", "DOC_START\n{@@File: mod + '.txt'}\nDOC_END")

wl(t.Transform("import_doc engine"))
```
**[Expected Output]**
```
DOC_START
(Contents of engine.txt)
DOC_END
```

### 3. Internal Test (Literal Integrity)
Verifying that `{@File}` inserts content literally without performing mathematical evaluation on the file's contents.

```[body]
New(uCalc::Transformer, t)
// If 'data.txt' contains "1+1", the output will be "1+1", not "2"
t.FromTo("DATA", "{@File: data.txt}")

wl(t.Transform("DATA"))
```
**[Expected Output]**
`1+1`

---

## Strategy & Critique
* **Separation of Concerns**: `{@File}` is the primary way to keep transformation rules clean. By moving boilerplate text out of the code and into external files, you make the transformer easier to maintain.
* **Performance Consideration**: Use static `{@File}` (single `@`) whenever possible. Dynamic `{@@File}` (double `@@`) requires a disk read for every match, which can significantly slow down transformations on large documents.
* **Security**: Be cautious when using `{@@File}` with user-provided text, as it could potentially lead to unauthorized file access if the input is not strictly validated.
* **See Also**: Refer to **Topic 771** (`{@Eval}`) if you need to execute the contents of a file as code.

---

## {@If} - ID: 774
/doc/reference/patterns/pattern-methods/{@if}/

**Remarks:**

[revisit]
Not implemented yet
{@If} conditionally adds a section to a pattern or replacement based on the condition

Assuming that x is defined numeric value,

Pattern: Testing {@If(x > 5): this and } that

will become:

Pattern: Testing this and that

if x is indeed greater than 5, or else it will be:

Pattern: Testing that

otherwise.

{@If(true) { asdf } else { } }


# {@If}: Conditional Directive

**Description**: A directive used to conditionally insert text or other directives into a pattern or replacement based on the result of a logical expression.

> **Note**: This feature is currently in the design phase and is not yet implemented in the production engine.

## Remarks

The `{@If}` directive allows for branching logic within the uCalc Transformer. It enables the engine to decide which text to output based on variables defined in the evaluator space or captured by pattern matchers.

### Proposed Syntax
The recommended syntax follows a functional ternary structure:
* **`{@If: condition, then_part, else_part}`**

If the `condition` evaluates to non-zero (True), the `then_part` is inserted. If it evaluates to zero (False), the `else_part` is used.

### Timing: Static (@) vs. Dynamic (@@)
* **`{@If: ...}` (Static)**: The condition is checked once when the rule is created. This is useful for environment-based configuration (e.g., `{@If: IsDebug, "[DEBUG] ", ""}`).
* **`{@@If: ...}` (Dynamic)**: The condition is checked for every match. This allows the output to change based on captured data (e.g., singular vs. plural formatting).

### Variable Handling
Variables used in the condition (like those set by `{@Define}`) are accessed by name without curly braces. However, the `then_part` and `else_part` can contain standard placeholders or even other nested directives.

---

## Examples (Proposed)

### 1. Succinct (Static Configuration)
Including a header based on a "TrialMode" variable set in the evaluator.

```[body]
New(uCalc::Transformer, t)
// Define state
t.FromTo("{@Beginning}", "{@Define: Variable: TrialMode = 1}")

// Static If check at rule creation
t.FromTo("HEADER", "{@If: TrialMode, 'TRIAL VERSION', 'LICENSED VERSION'}")

wl(t.Transform("HEADER"))
```
**[Expected Output]**
`TRIAL VERSION`

### 2. Practical (Dynamic Pluralization)
Using captured counts to determine the correct suffix for a word.

```[body]
New(uCalc::Transformer, t)
// Capture 'n' and check if it's greater than 1
t.FromTo("{@Number:n} items", "{n} {@@If: n > 1, 'items', 'item'}")

wl(t.Transform("1 items; 5 items"))
```
**[Expected Output]**
`1 item; 5 items`

### 3. Internal Test (Nested Logic)
Verifying that `{@If}` can be nested to handle more than two states.

```[body]
New(uCalc::Transformer, t)
t.FromTo("status {@Number:s}", "Status: {@@If: s==1, 'Active', {@@If: s==2, 'Pending', 'Inactive'}}")

wl(t.Transform("status 2"))
```
**[Expected Output]**
`Status: Pending`

---

## Strategy & Critique
* **Syntax Consistency**: By using the comma-delimited `(condition, then, else)` format, `{@If}` feels like a natural extension of `{@Eval}`. 
* **Evaluation Context**: The `then` and `else` parts should be treated as "templates" that are only parsed/transformed if their respective branch is chosen. This prevents unnecessary overhead or side effects from the unused branch.
* **Critique**: One challenge with comma-delimited syntax is handling commas within the `then` or `else` strings. We may need to support escaping (e.g., `\,`) or allow quoted strings for the branches.
* **See Also**: Refer to **Topic 815** (`{@Define}`) for setting up variables used in conditions.

---

## {@Newline} - ID: 812
/doc/reference/patterns/pattern-methods/{@newline}/

**Remarks:**

**Shortcut**: `{@nl}`

**Description**: A category matcher that identifies any token defined as a vertical line break (e.g., `\n` or `\r\n`).

The `{@Newline}` directive (shorthand `{@nl}`) is used in a `uCalc::Transformer` to target vertical structural boundaries. Unlike generic whitespace matchers in other languages, uCalc maintains a strict distinction between horizontal and vertical spacing to preserve document structure during complex transformations.

### Vertical vs. Horizontal Space
In uCalc, newlines are treated as a distinct category of tokens. This prevents rules intended for horizontal cleanup from accidentally collapsing multiple lines into a single one.
* **`{@Whitespace}`**: Targets spaces and tabs.
* **`{@Newline}`**: Targets line-ending characters.

### The `_newline` Variable
The actual string character(s) used by the `{@nl}` directive is controlled by a special internal string variable named `_newline`. 

* **Default Behavior**: By default, `_newline` is set to `\r\n` (CRLF) for versions compiled for Windows, and `\n` (LF) for all other platforms.
* **Reconfiguration**: You can manually override the newline character used for output by redefining this variable in the evaluator. This is useful for cross-platform document normalization.
  * **Example**: `uc.Eval("_newline = '\n'");` sets the newline to Unix-style globally.

### Common Behaviors
* **Statement Boundaries**: In many programming languages, a newline signifies the end of a command. `{@nl}` allows rules to be anchored specifically to the "End of Line" context.
* **Cleanup Logic**: Consecutive newlines can be matched and reduced (e.g., matching three newlines and replacing with two) to normalize document formatting.
* **The Inverse Operator (`!`)**: Using `{!nl}` allows the engine to match any token that is *not* a line break, which is useful for processing content while ensuring the match does not spill over into the next line.

### Short Alias
Because vertical alignment is a frequent requirement in transformation patterns, the shorter `{@nl}` alias is provided for cleaner, more readable rule definitions.

---

## Examples

### 1. Succinct (Quick Start: Consolidating Space)
Replacing triple-newlines with a standard double-newline to normalize document spacing.

```[body]
New(uCalc::Transformer, t)
// Match three consecutive newline tokens
t.FromTo("{@nl} {@nl} {@nl}", "{@nl}{@nl}")

wl(t.Transform("Line 1\n\n\nLine 2"))
```
**[Expected Output]**
`Line 1`
` `
`Line 2`

### 2. Practical (Real World: Line Counting)
Using `{@@Exec}` to increment a counter every time a newline is encountered, then displaying the total at the end.

```[body]
New(uCalc::Transformer, t)
// Initialize line counter at the start of the doc
t.FromTo("{@Beginning}", "{@Exec: Variable: lncnt = 1}")

// For every newline, increment the counter
t.FromTo("{@nl}", "{@@Exec: lncnt = lncnt + 1}{@Self}")

// At the end, show the line count
t.FromTo("{@End}", " [Total Lines: {@@Eval: lncnt}]")

wl(t.Transform("A\nB\nC"))
```
**[Expected Output]**
`A`
`B`
`C [Total Lines: 3]`

### 3. Internal Test (Ignoring Horizontal Space)
Verifying that `{@nl}` ignores horizontal whitespace (tabs and spaces) and only triggers on true vertical breaks.

```[body]
New(uCalc::Transformer, t)
t.FromTo("{@nl}", "[BREAK]")

// The spaces between 'A' and 'B' should remain untouched
wl(t.Transform("A   B\nC"))
```
**[Expected Output]**
`A   B[BREAK]C`

---

## Strategy & Critique
* **Structural Safety**: The categorical separation of `{@ws}` and `{@nl}` ensures that developers can perform aggressive horizontal whitespace normalization without worrying about losing the vertical "shape" of the code or document.
* **Performance**: Because newlines are identified during the initial lexing phase, matching `{@nl}` is significantly faster than using a regex that has to backtrack through various whitespace combinations.
* **Critique**: One potential pitfall for new users is forgetting that `\r\n` (Windows style) is often treated as a single token. `{@nl}` handles this automatically, but capturing the newline into a variable might yield different raw string values depending on the source document's encoding.
* **See Also**: Refer to **Topic 801** (`{@Whitespace}`) for horizontal spacing control.

**Examples:**

### Example ID: 176

**Description:** Matching by token type

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{@String:txt}", "<<InnerQuote={txt}><TxtWithQuotes={txt(0)}>>");
t.FromTo("{@Number:MyNum}", "<NumericValue={MyNum}>");
t.FromTo("{@Bracket:MyBrack}", "<Brack={MyBrack}>");
t.FromTo("{@CloseBracket:CloseBr}", "<CloseBrack={CloseBr}>");
t.FromTo("{@StatementSeparator:Sep}", "<Separator={Sep}>");
t.FromTo("{@Alphanumeric:alpha}", "<Alpha={alpha}>");
t.FromTo("{@Whitespace:ws}", "<whitespace count={@Eval: Length(ws)}>");
t.FromTo("{@Reducible:r}", "<Reducible={r}>");
t.FromTo("{@Newline}", "<New line{@Newline}>");

var s = [verbatim]This is   55.2*6 "Hello world";
'Single quote'(parenth)[/verbatim];

wl(t.Filter(s).@Matches().@Text())
```

**Output:**
```
<Alpha=This>
<whitespace count=1>
<Alpha=is>
<whitespace count=3>
<NumericValue=55.2>
<Reducible=*>
<NumericValue=6>
<whitespace count=1>
<<InnerQuote=Hello world><TxtWithQuotes="Hello world">>
<Separator=;>
<New line
>
<<InnerQuote=Single quote><TxtWithQuotes='Single quote'>>
<Brack=(>
<Alpha=parenth>
<CloseBrack=)>
```

---

---

## {@Not} - ID: 819
/doc/reference/patterns/pattern-methods/{@not}/

**Remarks:**

[revisit]

---

## {@Param} - ID: 792
/doc/reference/patterns/pattern-methods/{@param}/

**Remarks:**

**Description**: A replacement-only keyword used to reference a specific captured token or sub-part of a match by its numerical index.

The `{@Param:n}` directive is used within the replacement string of a `uCalc::Transformer` rule. It allows you to access individual components of a match based on their order of appearance in the pattern.

### Indexing Logic
*   **0-Based Indexing**: `{@Param:0}` refers to the first token or group matched by the pattern, `{@Param:1}` to the second, and so on.
*  **Bounds**: An out of bounds value will not cause an error, but will quietly be ignored.
*   **Implicit vs. Explicit**: While named variables (like `{@Alpha:var}`) are often preferred for clarity, `{@Param}` is invaluable when dealing with anonymous tokens or when the pattern consists of a sequence of similar tokens that need to be reordered.
*  **Expressions**:  The index does not have to be a literal numeric value.  It can be an expression.

### Structural Reordering
One of the most powerful uses of `{@Param}` is for "shuffling" text. Because the replacement string can place these parameters in any order, you can easily swap the positions of words, move prefixes to suffixes, or duplicate parts of a match.

### Comparison: {@Param} vs {@Self}
*   **`{@Self}`**: Returns the entire text segment matched by the pattern as a single unit.
*   **`{@Param:n}`**: Returns only the specific nth part of that segment. 

> **Note**: If a pattern uses recursion or complex grouping, the index corresponds to the flat sequence of tokens as they were validated by the engine.

---

## Examples

### 1. Succinct (Quick Start: Swapping Tokens)
Identifying two consecutive words and reversing their order in the output.

```[body]
New(uCalc::Transformer, t)
// Match two words separated by a space
t.FromTo("{@Alpha} {@Alpha}", "{@Param:1} {@Param:0}")

wl(t.Transform("Hello World"))
```
**[Expected Output]**
`World Hello`

### 2. Practical (Real World: Date Format Normalizer)
Converting a date from a slash-separated format (`MM/DD/YYYY`) to a standardized ISO format (`YYYY-MM-DD`).

```[body]
New(uCalc::Transformer, t)
// Pattern matches: Month (0) / (1) Day (2) / (3) Year (4)
t.FromTo("{@Number} / {@Number} / {@Number}", "{@Param:4}-{@Param:0}-{@Param:2}")

wl(t.Transform("01/15/2026"))
```
**[Expected Output]**
`2026-01-15`

### 3. Internal Test (Token Extraction)
Verifying that `{@Param}` can extract specific tokens from a mixed sequence while ignoring the delimiters in the final output.

```[body]
New(uCalc::Transformer, t)
// Pattern: Alpha (0) , (1) Number (2) ; (3)
t.FromTo("{@Alpha} , {@Number} ;", "ID:{@Param:2} NAME:{@Param:0}")

wl(t.Transform("User, 101;"))
```
**[Expected Output]**
`ID:101 NAME:User`

---

## Strategy & Critique
*   **Clarity vs. Conciseness**: In complex rules with 5+ tokens, `{@Param:4}` can become hard to track. In those cases, switching to named variables (e.g., `{@Number:year}`) is recommended for better code maintenance.
*   **Whitespace Handling**: Remember that if your pattern includes optional whitespace (like `{@ws}`), that whitespace occupies an index. If you forget to account for it, your `{@Param}` indices will be off by one.
*   **Critique**: The numerical approach is classic and robust, similar to regex backreferences (`\1`, `\2`), making it a low-friction tool for experienced developers.
*   **See Also**: Refer to **Topic 817** (Pattern Methods Introduction) for an overview of other replacement keywords like `{@Self}` and `{@Doc}`.

**Examples:**

### Example ID: 208

**Description:** {@Param}

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("This {etc} big test {words:2}",
         "{@Param:0}:{@Param:1}:{@Param:1+1}:{@Param:2+1}:{@Param:2*2}");
wl(t.Transform("This is a big test we have today"))
```

**Output:**
```
This:is a:big:test:we have today
```

---

---

## {@Self} - ID: 787
/doc/reference/patterns/pattern-methods/{@self}/

**Remarks:**

**Description**: A replacement-only keyword that represents the entire text segment captured by the pattern match.

The `{@Self}` keyword is used within the replacement string of a `uCalc::Transformer` rule. It acts as a macro for the full string of text that triggered the rule, allowing you to easily wrap or annotate existing content without manually reconstructing it using indexed parameters.

### Preservation of Original Content
The primary use case for `{@Self}` is when you want to keep the matched text exactly as it is but add surrounding context. This is often called "wrapping."
* **Example Pattern**: `{@Alpha}`
* **Example Replacement**: `[{@Self}]`
* **Result**: Every word in the document is wrapped in square brackets.

### Comparison with Other Keywords
* **`{@Self}`**: The total match.
* **`{@Param:n}`**: Only a specific part of the match.
* **`{@Doc}`**: The entire source document, regardless of the match.

### Evaluation Timing
`{@Self}` returns the text as it was captured *before* the replacement logic is applied. This makes it a reliable anchor for rules that perform complex HTML tagging or document-level annotations.

---

## Examples

### 1. Succinct (Quick Start: Wrapping Keywords)
Identifying a specific keyword and wrapping it in a generic tag for later processing.

```[body]
New(uCalc::Transformer, t)
// Match 'Warning' and add a prefix label
t.FromTo("Warning", "!!! {@Self} !!!")

wl(t.Transform("Warning: System low"))
```
**[Expected Output]**
`!!! Warning !!!: System low`

### 2. Practical (Real World: Automatic HTML Highlighting)
Matching a specific format (like a hex color code) and wrapping it in a span with a style attribute.

```[body]
New(uCalc::Transformer, t)
// Match a hex code starting with #
t.FromTo("# {@Alpha:hex}", "<span style='color: {@Self}'>{@Self}</span>")

wl(t.Transform("Background: #FF5500"))
```
**[Expected Output]**
`Background: <span style='color: #FF5500'>#FF5500</span>`

### 3. Internal Test (Whitespace Integrity)
Verifying that `{@Self}` includes the literal whitespace tokens captured between pattern elements.

```[body]
New(uCalc::Transformer, t)
// Pattern captures: Alpha + Space + Number
t.FromTo("{@Alpha} {@Number}", "RECORD: ({@Self})")

wl(t.Transform("User 123"))
```
**[Expected Output]**
`RECORD: (User 123)`

---

## Strategy & Critique
* **Ease of Use**: `{@Self}` is the most frequently used replacement keyword because it handles the "heavy lifting" of re-inserting the match without requiring the developer to track parameter indices.
* **Pattern Design**: When using `{@Self}`, be careful about what your pattern includes. If your pattern matches optional trailing spaces, `{@Self}` will include those spaces, which might lead to double-spacing in the output if not intended.
* **Critique**: It is functionally equivalent to `&` in many Unix `sed` implementations or `$0` in some regex engines, making it highly familiar to systems programmers.
* **See Also**: Refer to **Topic 792** (`{@Param}`) for accessing specific parts of the match.

**Examples:**

### Example ID: 189

**Description:** Whitespace

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("Hello World", "<{@Self}>");
wl(t.Transform("Hello World. HelloWorld. Hello     World. Hello, World."))
```

**Output:**
```
<Hello World>. HelloWorld. <Hello     World>. Hello, World.
```

---

### Example ID: 192

**Description:** Order of concurrent patterns

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Note: Since the patterns start the same,
//       the order in which they're defined matters.
t.FromTo("An {item}", "<{@Self}>");
t.FromTo("An {item}.", "[{@Self}]");
t.FromTo("An {item:2}.", "({@Self})");
t.FromTo("An orange.", "{{@Self}}");

wl(t.Transform("An apple. An orange. An elephant."))
wl(t.Transform("An angry bear. An extremely big dog!"))
```

**Output:**
```
[An apple.] {An orange.} [An elephant.]
(An angry bear.) <An extremely big dog!>
```

---

---

## {@Stop} - ID: 776
/doc/reference/patterns/pattern-methods/{@stop}/

**Remarks:**

**Description**: A structural directive that truncates the captured match segment at a specific point within the pattern.

The `{@Stop}` directive provides surgical control over what text is considered the "match" (the `{@Self}` keyword) versus what text is simply used as "context" for the match. 

### Capture Truncation
In a standard pattern, the entire sequence of tokens that satisfy the pattern is captured into the replacement buffer. When `{@Stop}` is inserted:
1. The engine continues matching the rest of the pattern to ensure the rule is valid.
2. However, the recorded match (`{@Self}`) and the replacement boundary are truncated at the point where `{@Stop}` appeared.

### Contextual Matching (Lookahead Behavior)
`{@Stop}` is effectively used to create a "positive lookahead" without the complexity of standard regex syntax. It allows you to say: "Match X, but only if it is followed by Y. Do not include Y in the replacement."

* **Without Stop**: `{@Alpha} ;` → Replaces both the word and the semicolon.
* **With Stop**: `{@Alpha} {@Stop} ;` → Replaces only the word, but only if a semicolon follows it.

---

## Examples

### 1. Succinct (Quick Start: Trailing Punctuation)
Identifying a word that ends with a colon, but replacing only the word itself while leaving the colon in the document.

```[body]
New(uCalc::Transformer, t)
// Match a word, stop, then validate a colon exists
t.FromTo("{@Alpha} {@Stop} :", "WORD({@Self})")

wl(t.Transform("Title: Content"))
```
**[Expected Output]**
`WORD(Title): Content`

### 2. Practical (Real World: Assignment Transpiler)
Capturing a variable name for transformation, but only if it is followed by an assignment operator (`=`). The operator itself should remain untouched for the next rule to process.

```[body]
New(uCalc::Transformer, t)
// Capture variable 'v', stop, then ensure '=' follows
t.FromTo("{@Alpha:v} {@Stop} =", "VAR_{v}")

wl(t.Transform("x = 10"))
```
**[Expected Output]**
`VAR_x = 10`

### 3. Internal Test (Parameter Impact)
Verifying how `{@Stop}` affects the `{@Param}` indices. Even though the capture stops, the tokens after `{@Stop}` are still indexed for the duration of the pattern check.

```[body]
New(uCalc::Transformer, t)
// Index 1: Alpha, Stop, Index 2: Number
t.FromTo("{@Alpha} {@Stop} {@Number}", "NAME:{@Param:1} NEXT_TYPE:{@Param:2}")

wl(t.Transform("User 123"))
```
**[Expected Output]**
`NAME:User NEXT_TYPE:123`
*(Note: The '123' in the source text is replaced because it was part of the pattern logic, even if it was after the 'Stop' command).*

---

## Strategy & Critique
* **Surgical Replacement**: `{@Stop}` is the best tool for "context-sensitive" editing where you want to avoid accidentally consuming neighboring tokens that other rules might need to see later.
* **Performance**: It is more efficient than capturing the context into a variable and then re-inserting it in the replacement string (e.g., `FromTo("X Y", "X' Y")`), as the engine doesn't have to perform the extra string concatenation for the context part.
* **Critique**: The name `{@Stop}` is highly semantic. It clearly indicates where the "replacement action" stops, even if the "matching logic" continues.
* **See Also**: Refer to **Topic 787** (`{@Self}`) to see how `{@Stop}` determines the content of the match reference.

**Examples:**

### Example ID: 209

**Description:** {@Stop}

**Code:**
```pseudocode
var t = uc.NewTransformer();

// without {@Stop} "end" wouldn't be a match
t.FromTo("StopAt {abc} {@Stop} end", "<{abc}>");
t.FromTo("end", "[The End]");

wl(t.Transform("StopAt a b c end"))

```

**Output:**
```
<a b c> [The End]
```

---

---

## {#} - ID: 816
/doc/reference/patterns/pattern-methods/{#}/

**Remarks:**

## Character Literals

**Description**: A structural directive used to inject specific characters into a pattern or replacement using their ASCII or Unicode numeric code points.

The `{#}` directive allows for the explicit definition of characters by their numeric values. This is particularly useful for representing characters that are either impossible to type, non-printing (control characters), or potentially ambiguous when viewed as literal text.

### Syntax
* **`{#code}`**: Injects a single character.
* **`{#code1#code2#code3...}`**: Concatenates multiple characters into a single unit.

For example, `{#65#66#67}` is equivalent to the literal string `ABC`.

### Common Use Cases
* **Control Characters**: Inserting Null bytes (`{#0}`), Tabs (`{#9}`), or Line Feeds (`{#10}`).
* **Extended ASCII/Unicode**: Representing symbols or characters outside the standard keyboard set without worrying about file encoding issues.
* **Low-Level Protocols**: Matching specific binary markers in data streams that use non-textual delimiters.

### Behavior in Patterns and Replacements
* **In Patterns**: It acts as a literal matcher. The engine expects to see the character(s) corresponding to the provided codes at the current position.
* **In Replacements**: It acts as an injector, placing the characters into the resulting string.

---

## Examples

### 1. Succinct (Quick Start: Basic ASCII Matching)
Matching the character 'A' (ASCII 65) explicitly and replacing it with a text label.

```[body]
New(uCalc::Transformer, t)
// Match 'A' via its code point
t.FromTo("{#65}", "CHAR_A")

wl(t.Transform("A content"))
```
**[Expected Output]**
`CHAR_A content`

### 2. Practical (Real World: Cleaning Null-Terminated Data)
Identifying a data string that contains embedded null characters (`{#0}`) and stripping them out to create clean text.

```[body]
New(uCalc::Transformer, t)
// Match a Null character and remove it (replace with empty string)
t.FromTo("{#0}", "")

// Data often comes from C-style buffers with trailing or embedded nulls
var(string, raw_data) = "Part1" + "{#0}" + "Part2"
wl(t.Transform(raw_data))
```
**[Expected Output]**
`Part1Part2`

### 3. Internal Test (Multi-Character Injection)
Verifying that multiple code points can be concatenated within a single set of curly braces.

```[body]
New(uCalc::Transformer, t)
// 72=H, 69=E, 76=L, 79=O
t.FromTo("GREET", "{#72#69#76#76#79}")

wl(t.Transform("GREET user"))
```
**[Expected Output]**
`HELLO user`

---

## Strategy & Critique
* **Encoding Reliability**: Using `{#}` ensures that the transformation logic is independent of the text editor's encoding settings. It provides a deterministic way to target characters that might otherwise look like garbled text in a source file.
* **Readability Trade-off**: While powerful, using `{#}` for standard printable characters (like `{#65}` for `A`) makes the pattern harder to read. It should be reserved for special characters or specific low-level protocol requirements.
* **Critique**: The ability to chain codes (e.g., `{#13#10}`) makes it very easy to define specific platform-based sequences like CRLF without relying on the internal `_newline` variable logic.
* **See Also**: Refer to **Topic 812** (`{@Newline}`) and **Topic 801** (`{@Whitespace}`) for higher-level structural matchers.

**Examples:**

### Example ID: 202

**Description:** Transforming numeric ASCII codes to text characters

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("{#97#98#99}", "{#120#121#122}");
// Same as t.FromTo("abc", "xyz")

wl(t.Transform("abc"))
```

**Output:**
```
xyz
```

---

---

## Variable Postfix Modifiers - ID: 770
/doc/reference/patterns/variable-postfix-modifiers/

---

## Introduction - ID: 794
/doc/reference/patterns/variable-postfix-modifiers/introduction/

**Remarks:**

# Variable Postfix Modifiers: Introduction

**Description**: An overview of the symbols appended to pattern variables to override default capture logic, ignore structural boundaries, or force immediate transformations.

While **Directives** (starting with `{@`) define structural engine commands, **Variable Postfix Modifiers** are specific symbols used within pattern variables (like `{x}`) to qualify how text is matched. 

By default, uCalc is structurally aware: it respects bracket levels and treats quoted strings as atomic units. Postfix modifiers allow you to override these safe defaults when a specific transformation requires more "raw" or "aggressive" text handling.

### Core Modifiers and Overrides

* **Nesting Override (`^`)**: By default, uCalc respects balanced brackets (nesting). Use `^` to **ignore** balance levels, allowing the capture to stop at a terminal character even if it is inside a nested structure.
* **Quote Override (`` ` ``)**: By default, quoted strings are atomic and cannot be split. Use the backtick to **ignore** quote boundaries, allowing the capture to break or include partial contents of a quoted string.
* **Separator Override (`+`)**: Instructs the engine to ignore standard statement separators (like `;` or specific line breaks) that would otherwise terminate a variable capture.
* **Verbatim Capture (`~`)**: Captures the text exactly as it appears and prevents the engine from scanning for nested matches inside the captured block. This ensures the content remains "opaque" to other rules.
* **Immediate Transform (`%`)**: The opposite of verbatim; it forces the engine to immediately search for and execute nested transformation rules within the captured text before finalizing the outer match.
* **Whitespace Retention**: Determines whether the leading/trailing whitespace found around a token is included in the variable's final string value.
* **Boundary Extension**: A proposed modifier (Topic 783) for extending the reach of a variable match beyond standard termination points.

### Combining Modifiers
Multiple postfix modifiers can be combined within a single variable definition if their logic does not conflict. For example, `{content^~}` would capture a block of text while ignoring bracket levels **and** preventing internal nested matches.


**Examples:**

### Example ID: 210

**Description:** Ignore quote directive `

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a {txt} c", "<{@Self}>"); // Quoted text treated as 1 token
t.FromTo("x {txt`} z", "<{@Self}>"); // Quotes treated as ordinary chars

wl(t.Transform("a 'b c' b c :: x 'y z' y z"))
```

**Output:**
```
<a 'b c' b c> :: <x 'y z>' y z
```

---

---

## Boundary Extension > - ID: 783
/doc/reference/patterns/variable-postfix-modifiers/boundary-extension->/

**Remarks:**

[revisit]

When you append a > to a variable name, this makes the parser eagerly continue until it finds the final possible anchor, instead of the first one.

Pattern: a {etc} c
Replacement: <{@Self}>

a b c d a b c d a b c d

gets replaced with
<a b c> d <a b c> d <a b c> d

but if the pattern is: a {etc>} c
then you get:
<a b c d a b c d a b c> d

---

## ExprUnit # - ID: 782
/doc/reference/patterns/variable-postfix-modifiers/exprunit-#/

**Remarks:**

[revisit]


---

## FocusMatch * - ID: 793
/doc/reference/patterns/variable-postfix-modifiers/focusmatch-*/

**Remarks:**

[revisit]

This indicates a subsection of the match that will be saved as the match.  If you want to match a pattern, but only want a subsection of the match to be counted as a match, then append the * indicator.  Only one FocusMatch per pattern is effective.  If you have more than one, then the first one encountered is selected.  However, if you have optional or alternative patterns within [] and |, then you can technically have more than one, but only the one that is used will count.

With this rule:

Pattern: <{text}>
Replacement: "{text}"

<abc> xyz <123> aaa <cde>
would be replaced with:
"<abc>" xyz "<123>" aaa "<cde>"

However, if you don't want the angle brackets to be part of the match you can do:
Pattern: Pattern: <{text*}>

And you'll get:
"abc" xyz "123" aaa "cde"





---

## Nesting Override ^ - ID: 781
/doc/reference/patterns/variable-postfix-modifiers/nesting-override-^/

**Remarks:**

## Nesting Override

**Shortcut**: `^`
**Associated Method**: `uCalc.Rule.NestingAware(bool)`

**Description**: A postfix modifier that instructs a pattern variable to ignore balanced nesting levels (brackets, parentheses, etc.) and stop at the literal next terminal token.

By default, uCalc is "Nesting Aware." This means if a variable is tasked with capturing content inside a bracketed structure, it will intelligently track open and close markers (like `(` and `)`) to ensure it doesn't stop matching prematurely. 

The **Nesting Override (`^`)** is used to break this structural integrity for specific, surgical transformations.

### Default vs. Override Behavior
* **Default (Nesting Aware)**: A pattern like `func({x})` matched against `func((1+1))` will capture `(1+1)` into `{x}`. The engine sees the first `)` but knows it belongs to an internal group, so it continues until the "balanced" closing bracket is found.
* **Override (`{x^}`)**: Appending the `^` symbol tells the engine to stop at the very first occurrence of the terminal token, regardless of whether brackets are balanced or not. In the example above, `{x^}` would capture `((1+1)`.

### The `NestingAware()` Method
While the `^` symbol provides per-variable control, you can toggle this behavior globally using the `NestingAware()` method on the uCalc object.
* `uc.NestingAware(true)`: (Default) All variables respect bracket levels.
* `uc.NestingAware(false)`: All variables behave as if they have the `^` postfix unless otherwise specified.

---

## Examples

### 1. Succinct (Nesting Awareness Example)
Demonstrating how the engine normally handles nested parentheses versus the override.

```[body]
New(uCalc::Transformer, t)
// Default: captures everything balanced
t.FromTo("calc({v})", "RESULT({v})")

// Override: stops at the first ')' it sees
t.FromTo("raw({v^})", "RAW({v})")

wl(t.Transform("calc((1+1))")) // Output: RESULT((1+1))
wl(t.Transform("raw((1+1))"))  // Output: RAW((1+1)
```

### 2. Practical (Surgical Extraction)
In some complex document formats, you may need to stop at the first delimiter even if it appears "inside" a bracketed segment.

```[body]
New(uCalc::Transformer, t)
// We want to capture the function name and the first part of the args
// but stop immediately at a comma, even if that comma is inside a nested call.
t.FromTo("{@Alpha:f}({args^}, {@All:rest})", "FUNC:{f} ARG1:{args}")

wl(t.Transform("process(format(x, y), z)"))
```
**[Expected Output]**
`FUNC:process ARG1:format(x`

### 3. Internal Test (Global vs Local)
Verifying that the global `NestingAware` setting can be overridden or complemented by the postfix.

```[body]
// Turn off nesting awareness globally
uc.NestingAware(false)

New(uCalc::Transformer, t)
// Now, this variable will stop at the first ')' by default
t.FromTo("test({v})", "GOT:{v}")

wl(t.Transform("test((a))"))
```
**[Expected Output]**
`GOT:(a`

---

## Strategy & Critique
* **Structural Safety**: Nesting awareness is one of uCalc's most powerful features, preventing the "leaky capture" issues common in Regular Expressions. The `^` override should be used sparingly.
* **Logical Use Case**: Use `^` when you are dealing with poorly formatted text or when a bracket character is being used as a literal delimiter rather than a structural container.
* **Naming**: Renaming the associated method to **`NestingAware()`** aligns perfectly with the "Nesting Override" terminology, making the API much more self-documenting.
* **See Also**: Refer to Topic **786** for Quote Overrides and Topic **780** for Statement Boundary Overrides.

**Examples:**

### Example ID: 212

**Description:** Ignore bracket directive ^

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("begin {body} end",   "bracket not ignored: <{@Self}>");
t.FromTo("begin_ {body^} end", "bracket ignored:     <{@Self}>");

wl(t.Transform("begin (a b c end) end"))
wl(t.Transform("begin_ (a b c end) end"))
```

**Output:**
```
bracket not ignored: <begin (a b c end) end>
bracket ignored:     <begin_ (a b c end>) end
```

---

---

## Quote Override ` - ID: 786
/doc/reference/patterns/variable-postfix-modifiers/quote-override-`/

**Remarks:**

## Quote Override

**Shortcut**: `` ` `` (backtick)
**Associated Method**: `uCalc.Rule.QuoteAware(bool)`

**Description**: A postfix modifier that allows a pattern variable to ignore the atomic boundaries of quoted strings, enabling it to match content inside or across quotes.

By default, uCalc is "Quote Aware." The lexer identifies quoted strings (e.g., `"Hello World"`) as single, atomic tokens. This prevents transformation rules from accidentally breaking into a string and changing its contents unless explicitly intended.

The **Quote Override (`` ` ``)** is used to bypass this protection.

### Default vs. Override Behavior
* **Default (Quote Aware)**: A variable match for `{v}` will treat a quoted string as one unit. It cannot capture just the first word inside the quotes because the quotes act as a container.
* **Override (```{v`}```)**: Appending the backtick tells the engine that quotes are not atomic for this specific variable. The engine will treat the quote characters as literal delimiters or standard text, allowing the capture to stop or start *inside* the quoted segment.

### The `QuoteAware()` Method
You can toggle this behavior globally using the `QuoteAware()` method on the uCalc object.
* `uc.QuoteAware(true)`: (Default) Quoted strings are treated as unbreakable atomic tokens.
* `uc.QuoteAware(false)`: All variables behave as if they have the backtick postfix, treating quote characters as standard text.

---

## Examples

### 1. Succinct (Breaking the Atomic Quote)
Showing how a standard variable fails to split a quoted string, while the override succeeds.

```[body]
New(uCalc::Transformer, t)

// Default: Tries to match 'say' then any variable. 
// It will match the WHOLE quoted string as one token.
t.FromTo("say {msg}", "MSG:{msg}")

// Override: Allows splitting the quoted string.
t.FromTo("say \"{msg`}\"", "INSIDE_QUOTE:{msg}")

wl(t.Transform("say \"Hello\"")) 
// Output with ` : INSIDE_QUOTE:Hello
```

### 2. Practical (Content Manipulation inside Quotes)
Useful when you need to perform a search-and-replace for specific keywords that only appear inside quoted strings.

```[body]
New(uCalc::Transformer, t)
// Capture the content inside double quotes using the override
t.FromTo("\"{content`}\"", "QUOTE_START {content} QUOTE_END")

wl(t.Transform("\"Secret Data\""))
```
**[Expected Output]**
`QUOTE_START Secret Data QUOTE_END`

### 3. Internal Test (Global Configuration)
Verifying that disabling global quote awareness allows all patterns to penetrate quoted strings.

```[body]
// Disable quote awareness globally
uc.QuoteAware(false)

New(uCalc::Transformer, t)
// Now the pattern can match 'Word' even if it's inside quotes
t.FromTo("Word", "MATCH")

wl(t.Transform("\"Word\""))
```
**[Expected Output]**
`"MATCH"`

---

## Strategy & Critique
* **Data Protection**: uCalc's default quote awareness is a critical safety feature for code transpilation (e.g., you don't want to change a variable name inside a print statement's string literal). Only use the override when you are explicitly processing string content.
* **Lexer Interaction**: Because the backtick forces the engine to look "inside" the token, it can increase the complexity of the match. Use it surgically.
* **Naming**: Like `NestingAware()`, the method **`QuoteAware()`** clearly defines the engine's stance on structural integrity.
* **See Also**: Refer to Topic **781** for Nesting Overrides and Topic **780** for Statement Boundary Overrides.

**Examples:**

### Example ID: 210

**Description:** Ignore quote directive `

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a {txt} c", "<{@Self}>"); // Quoted text treated as 1 token
t.FromTo("x {txt`} z", "<{@Self}>"); // Quotes treated as ordinary chars

wl(t.Transform("a 'b c' b c :: x 'y z' y z"))
```

**Output:**
```
<a 'b c' b c> :: <x 'y z>' y z
```

---

---

## Separator Override + - ID: 780
/doc/reference/patterns/variable-postfix-modifiers/separator-override-+/

**Remarks:**

## Statement Boundary Override

**Shortcut**: `+`
**Associated Method**: `uCalc.Rule.StatementSeparatorAware(bool)`

**Description**: A postfix modifier that allows a pattern variable to ignore statement separators (such as `;` or structural newlines) and continue capturing text across command boundaries.

By default, uCalc is "Statement Separator Aware." This means that when a variable is capturing text, it treats statement separators as hard boundaries. This safety mechanism prevents a single variable from accidentally merging multiple distinct commands into one capture, which could break the logic of subsequent transformation rules.

The **Statement Boundary Override (`+`)** is used to bypass this structural limitation.

### Default vs. Override Behavior
* **Default (Statement Aware)**: If a variable `{v}` is matched against `x=1; y=2`, and the pattern looks for everything after `x=`, it will stop capturing at the semicolon. `{v}` will contain only `1`.
* **Override (`{v+}`)**: Appending the plus symbol tells the engine that statement separators are not boundaries for this specific variable. In the same example, `{v+}` would capture `1; y=2`.

### The `StatementSeparatorAware()` Method
You can toggle this behavior globally using the `StatementSeparatorAware()` method on the uCalc object.
* `uc.StatementSeparatorAware(true)`: (Default) Variables stop matching at statement separators.
* `uc.StatementSeparatorAware(false)`: All variables behave as if they have the `+` postfix, ignoring separators by default.

---

## Examples

### 1. Succinct (Breaking the Statement Barrier)
Showing how a standard variable is terminated by a semicolon, while the override continues until the pattern's end.

```[body]
New(uCalc::Transformer, t)

// Default: Capture stops at the semicolon
t.FromTo("get {cmd}", "CMD:[{cmd}]")

// Override: Capture ignores the semicolon
t.FromTo("all {cmd+}", "FULL:[{cmd}]")

wl(t.Transform("get x=1; y=2")) // Output: CMD:[x=1]; y=2
wl(t.Transform("all x=1; y=2")) // Output: FULL:[x=1; y=2]
```

### 2. Practical (Capturing Multi-Line Blocks)
Useful when you need to wrap an entire sequence of instructions into a container, where those instructions are separated by semicolons or newlines.

```[body]
New(uCalc::Transformer, t)
// Use '+' to ensure 'block' captures every statement until the 'END' keyword
t.FromTo("BEGIN {block+} END", "<div class='code'>{block}</div>")

wl(t.Transform("BEGIN cmd1; cmd2; cmd3; END"))
```
**[Expected Output]**
`<div class='code'>cmd1; cmd2; cmd3;</div>`

### 3. Internal Test (Global Configuration)
Verifying that disabling global statement awareness allows all variables to span across separators.

```[body]
// Disable statement awareness globally
uc.StatementSeparatorAware(false)

New(uCalc::Transformer, t)
// Now this matches across the semicolon even without the '+' postfix
t.FromTo("capture {v}", "GOT:{v}")

wl(t.Transform("capture a;b;c"))
```
**[Expected Output]**
`GOT:a;b;c`

---

## Strategy & Critique
* **Structural Intent**: Statement separators are critical markers in most languages. Only override them when your goal is to manipulate a "block" of logic rather than an individual expression.
* **Lexer Dependencies**: The definition of a "statement separator" depends on the current lexer configuration. `+` ensures that whatever the lexer considers a separator is ignored for that capture.
* **Naming**: The method **`StatementSeparatorAware()`** clearly identifies that the engine's default state is to protect the boundaries between statements.
* **See Also**: Refer to Topic **781** for Nesting Overrides and Topic **786** for Quote Overrides.

**Examples:**

### Example ID: 217

**Description:** IgnoreStatementSeparator +

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("a {txt} c", "<{@Self}>"); 
t.FromTo("x {txt+} z", "<{@Self}>");

wl(t.Transform("a b c; :: x y z; :: a b; c :: x y; z"))
```

**Output:**
```
<a b c>; :: <x y z>; :: a b; c :: <x y; z>
```

---

---

## Verbatim Capture ~ - ID: 784
/doc/reference/patterns/variable-postfix-modifiers/verbatim-capture-~/

**Remarks:**

## Verbatim Capture

**Shortcut**: `~`
**Associated Method**: `NestedMatchAware(bool)`

**Description**: A postfix modifier that allows a variable to ignore other pattern boundaries during capture, treating the text as a verbatim block.

By default, uCalc is "Nested Match Aware." As a variable moves through text to satisfy a capture, it remains aware of all other active patterns in the transformer. If it encounters text that matches another rule, it treats that entire match as an unbreakable unit (a boundary). It will complete that other match before continuing its own capture, ensuring that it never "crosses" or partially consumes another potential anchor match.

The **Verbatim Capture (`~`)** postfix is used to disable this boundary awareness for a specific variable.

### Boundary Logic
* **Default (Nested Match Aware)**: The variable respects the boundaries of other patterns. If it's capturing "everything until X" and hits the start of another pattern, it waits for that pattern to finish and includes it as a block.
* **Verbatim Capture (`~`)**: The variable ignores all other patterns. It acts as a "bulldozer," capturing every character/token purely based on its own termination criteria, regardless of whether it is splitting another rule's potential match in half.

### Purpose: Verbatim Preservation
This is used when you need to capture a section of text exactly as it is, without allowing other rules to "claim" parts of the content while the capture is in progress. This ensures the resulting variable contains the literal source text without any structural interference from other patterns.

This is essential when transforming documents that contain "literal" sections—such as code blocks, raw data strings, or pre-formatted text—where internal content must remain untouched by global search-and-replace rules.

### The `NestedMatchAware()` Method
You can toggle this behavior globally using the `NestedMatchAware()` method on the uCalc object.
* `uc.NestedMatchAware(true)`: (Default) Variables respect the boundaries of other patterns during capture.
* `uc.NestedMatchAware(false)`: All variables behave as if they have the `~` postfix, ignoring other pattern boundaries.

---

## Strategy & Critique
* **Structural Safety**: The default awareness is what makes uCalc more stable than regex for complex grammars. It prevents rules from "fighting" over the same characters in a way that leads to unpredictable results.
* **Verbatim Intent**: Use `~` when the captured text is meant to be stored or moved without any modification or structural analysis.
* **Naming**: **`NestedMatchAware()`** is appropriate because it describes the engine's ability to "see" and respect other potential matches while it is busy fulfilling the current one.
* **See Also**: Refer to Topic **779** (Immediate Transform) for the reverse behavior (forcing transformation during capture).








**Examples:**

### Example ID: 213

**Description:** Pattern directive to skip nested pattern matching

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("start {etc} end", "<{@Self}>");
t.FromTo("start2 {etc~} end", "<{@Self}>");

wl(t.Transform("start start2 a b c end end"))
wl(t.Transform("start2 start a b c end end"))
```

**Output:**
```
<start start2 a b c end end>
<start2 start a b c end> end
```

---

---

## Immediate Transform % - ID: 779
/doc/reference/patterns/variable-postfix-modifiers/immediate-transform-%/

**Remarks:**

## Immediate Transform

**Shortcut**: `%`
**Associated Method**: `uCalc.Rule.ImmediateTransform(bool)`

**Description**: A postfix modifier that instructs the engine to immediately transform any nested matches found within the captured text before moving on to the next part of the transformation.

By default, uCalc is structurally aware during a variable capture. If a variable `{v}` is moving through text and encounters a sequence that matches another active pattern, it respects that pattern's boundaries (treating it as an atomic unit), but it does **not** perform any transformative actions on that inner match. The inner text remains in its original form within the captured variable.

The **Immediate Transform (`%`)** postfix is used to force uCalc to apply all relevant rules to that inner content right away.

### Default vs. Transform Behavior
* **Default**: The engine identifies nested patterns so it doesn't "cross" them, but it passes over them without changing their text. The variable receives the original source content.
* **Immediate Transform (`%`)**: The engine identifies the nested patterns and executes their replacements immediately. The variable receives the "transformed" version of the text.

### Purpose: Pre-Processing for Evaluation
This modifier is essential when the captured text is intended to be used as input for an evaluator directive like `{@Eval}`. If the captured text contains keywords or shorthand that need to be expanded into numbers or valid formulas before the math engine sees them, the `%` modifier ensures those expansions happen first.

---

## Examples

### 1. Succinct (Immediate vs. Deferred Transformation)
Comparing how a nested rule to change "old" to "new" affects a variable.

```[body]
New(uCalc::Transformer, t)
t.FromTo("old", "new") // Nested rule

// Standard: 'val' contains the original text "old"
t.FromTo("standard: {val}", "RESULT:{val}")

// Immediate: 'val' contains the updated text "new"
t.FromTo("immediate: {val%}", "RESULT:{val}")

wl(t.Transform("standard: old"))  // Output: RESULT:old
wl(t.Transform("immediate: old")) // Output: RESULT:new
```

### 2. Practical (Nested Expression Cleanup)
Using `%` to ensure internal variables are resolved within a captured block before the block is wrapped in a tag.

```[body]
New(uCalc::Transformer, t)
t.FromTo("x", "10")
t.FromTo("y", "20")

// Capture the content inside brackets and update x and y immediately
t.FromTo("calc({expr%})", "COMPUTE:[{expr}]")

wl(t.Transform("calc(x + y)"))
```
**[Expected Output]**
`COMPUTE:[10 + 20]`

### 3. Internal Test (Evaluation Integrity)
Demonstrating that `%` is necessary when a captured string is passed to `{@Eval}` and contains tokens that need to be transformed into numeric literals first.

```[body]
New(uCalc::Transformer, t)
t.FromTo("PI_CONST", "3.14159")

// Without %, {v} would contain the string "PI_CONST" which Eval might not recognize.
// With %, {v} contains "3.14159".
t.FromTo("solve: {v%}", "Result: {@@Eval: v}")

wl(t.Transform("solve: PI_CONST"))
```
**[Expected Output]**
`Result: 3.14159`

---

## Strategy & Critique
* **The "Now vs. Later" Choice**: Most transformations in uCalc are designed to be safe and structural (Default). `%` is the tool you use when you need "active" content that must be fully baked before the current rule finishes.
* **Counterpart to Verbatim**: While **Verbatim Capture (`~`)** (Topic 784) tells the engine to ignore boundaries entirely, **Immediate Transform (`%`)** tells the engine to respect the boundaries and *act* on them immediately.
* **Naming**: The method **`ImmediateTransform()`** is a suggested name that clearly contrasts with the default deferred-transformation behavior of the engine.
* **See Also**: Refer to Topic **784** (Verbatim Capture) for the "Black Box" approach to nested content.

**Examples:**

### Example ID: 214

**Description:** TransformArg directive

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("abc", "changed to xyz");
t.FromTo("Quote1({arg})", "'{arg}'");
t.FromTo("Quote2({arg%})", "'{arg}'");

wl(t.Transform("Quote1(abc), Quote2(abc)"))

```

**Output:**
```
'abc', 'changed to xyz'
```

---

---

## Whitespace Retention $ - ID: 785
/doc/reference/patterns/variable-postfix-modifiers/whitespace-retention-$/

**Remarks:**

## Whitespace Retention

[Note: for now the `$` character is what's implemented instead of `_`]

**Shortcut**: `_` (underscore)
**Associated Method**: `uCalc.Rule.WhitespaceCounts(bool)`

**Description**: A postfix modifier that determines whether leading and trailing whitespace surrounding a matched token is captured as part of the variable's value.

By default, uCalc is "Whitespace Aware" in a way that prioritizes data cleanliness. When a pattern variable (like `{v}`) captures a token, the engine automatically strips any horizontal whitespace (spaces or tabs) that immediately precedes or follows that token. This ensures that a capture like `   123   ` results in the clean string `123`.

The **Whitespace Retention (`_`)** modifier is used to override this stripping behavior.

### Default vs. Retention Behavior
* **Default (Stripped)**: Whitespace is matched by the engine to satisfy the pattern but is not included in the variable's stored string. 
* **Retention (`{v_}`)**: Every whitespace character encountered that belongs to the variable's capture zone is preserved. This is essential for formatting-sensitive transformations.

### The `WhitespaceCounts()` Method
You can toggle this behavior globally using the `WhitespaceCounts()` method on the uCalc object.
* `uc.WhitespaceCounts(false)`: (Default) Variables strip surrounding whitespace.
* `uc.WhitespaceCounts(true)`: All variables behave as if they have the `_` postfix, retaining whitespace by default.

---

## Examples

### 1. Succinct (Stripping vs. Retention)
Comparing how the engine handles a word surrounded by spaces.

```[body]
New(uCalc::Transformer, t)

// Default: " Word " results in "[Word]"
t.FromTo("find {v}", "GOT:[{v}]")

// Retention: " Word " results in "[ Word ]"
t.FromTo("keep {v_}", "GOT:[{v}]")

wl(t.Transform("find  Hello ")) // Output: GOT:[Hello]
wl(t.Transform("keep  Hello ")) // Output: GOT:[ Hello ]
```

### 2. Practical (Preserving Alignment)
When moving or wrapping blocks of text where the original horizontal alignment or indentation is part of the data's meaning.

```[body]
New(uCalc::Transformer, t)
// Use '_' to ensure indentation is kept when wrapping lines in tags
t.FromTo("{line_}", "<li>{line}</li>")

wl(t.Transform("    Indented Line"))
```
**[Expected Output]**
`<li>    Indented Line</li>`

### 3. Internal Test (Global Configuration)
Verifying that enabling global whitespace retention makes all variables include padding by default.

```[body]
// Enable whitespace retention globally
uc.WhitespaceCounts(true)

New(uCalc::Transformer, t)
t.FromTo("id {v}", "ID:{v}")

wl(t.Transform("id   101"))
```
**[Expected Output]**
`ID:  101`

---

## Strategy & Critique
* **Data Integrity**: Default stripping is usually what you want for mathematical or logical evaluation (e.g., passing a number to `{@Eval}`).
* **Visual Integrity**: Retention is what you want for document reconstruction, code prettifiers, or transpilers where the "look" of the source is as important as the content.
* **Naming**: **`WhitespaceCounts()`** is the established method name, though **Whitespace Retention** is used here as the descriptive title to better contrast with the default "stripping" behavior.
* **See Also**: Refer to Topic **801** (Whitespace Directive) and Topic **812** (Newline Directive) for structural spacing controls.


**Examples:**

### Example ID: 215

**Description:** WhitespaceCounts

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.FromTo("A {txtA}. B {txtB$}.", "<{txtA}> <{txtB}>");

wl(t.Transform("A     x y z . B     x y z ."))
```

**Output:**
```
<x y z> <     x y z >
```

---

---

## Aliases - ID: 831
/doc/reference/patterns/aliases/

**Remarks:**

**Description**: A collection of shorthand names for common structural directives and category matchers used to improve pattern readability and conciseness.

In the `uCalc::Transformer`, patterns can often become lengthy when using full descriptive names for every token type. **Aliases** are functionally identical counterparts to standard directives that allow you to express the same logic with fewer characters.

### Case Sensitivity
Directives and their aliases are **not case-sensitive**. For example, `{@Tab}`, `{@tab}`, and `{@TAB}` are all evaluated identically by the engine.

### Common Alias Map

The following table lists the most frequently used aliases:

| Alias | Full Name | Purpose |
| :--- | :--- | :--- |
| `{@nl}` | `{@Newline}` | Matches vertical line breaks. |
| `{@Alpha}` | `{@Alphanumeric}` | Matches alphabetic or alphanumeric identifiers. |
| `{@ws}` | `{@Whitespace}` | Matches horizontal spaces and tabs. |
| `{@str}` / `{@s}`| `{@String}` | Matches any full quoted string (auto-detected). |
| `{@dqs}` | `{@StringDQ}` | Matches a full string enclosed in `"`. |
| `{@sqs}` | `{@StringSQ}` | Matches a full string enclosed in `'`. |
| `{@dq}` | `{@DoubleQuoteChar}`| Matches a literal `"` character. |
| `{@sq}` | `{@SingleQuoteChar}`| Matches a literal `'` character. |
| `{@Sep}` | `{@StatementSeparator}` | Matches boundaries like `;`. |

### Naming Conventions and Nuance
* **Character vs. String**: It is important to distinguish between character aliases and string aliases. 
    * `{@dq}` matches only the double-quote character.
    * `{@dqs}` matches the quote character **plus** all the text inside until the closing quote.
* **The "Alpha" Distinction**: In uCalc, `{@Alpha}` (and its full name `{@Alphanumeric}`) follows the standard for programming identifiers, meaning it includes digits and underscores.
* **API Symmetry**: Establishing full names like `{@DoubleQuoteChar}` to match the existing alias `{@dq}` ensures that the library feels complete for developers who prefer verbose code.

---

## Examples

### 1. Succinct (Char vs String Aliases)
Showing the difference between matching a quote character and a full quoted string.

```[body]
New(uCalc::Transformer, t)

// Pattern: Match 'msg' followed by a literal quote
t.FromTo("msg {@dq}", "MSG_START")

// Pattern: Match 'msg' followed by a full quoted string
t.FromTo("msg {@dqs:val}", "MESSAGE({val})")

wl(t.Transform("msg \"Hello World\""))
```

### 2. Practical (Shorthand Cleanup)
Using `{@ws}` and `{@nl}` to keep a pattern concise while stripping trailing space.

```[body]
New(uCalc::Transformer, t)
// Verbose: {@Alpha:w} {@Whitespace} {@Newline}
t.FromTo("{@Alpha:w} {@ws} {@nl}", "{w}{@nl}")

wl(t.Transform("Test   \n"))
```
**[Expected Output]**
`Test\n`

---

## Strategy & Critique
* **Precision**: The distinction between `{@dq}` (char) and `{@dqs}` (string) is vital. Mapping `{@dq}` to a full string is a common mistake in early pattern design; these aliases help reinforce the correct logic.
* **Readability**: Shortening common markers makes the "meat" of the pattern stand out.
* **Consistency**: Standardizing on aliases like `{@Sep}` and `{@nl}` across a project ensures that different developers are speaking the same shorthand.
* **See Also**: Refer to **Topic 812** (`{@nl}`) and **Topic 827** (`{@dq}`) for detailed behavioral documentation.

---

## Pattern Best Practices & Pitfalls - ID: 820
/doc/reference/patterns/pattern-best-practices-&-pitfalls/

**Remarks:**

In a pattern, the curly brace has special meaning.  If you actually want to capture a literal curly brace, and not have it represent a variable or the start of alternative parts, you can either place it within quotes, as in `"{"`, or you can use `{@Token(CurlyBrace)}`.  To capture any bracket (such as `{` or `[`, etc) you can use `{@Bracket}`).

Note: It is much more efficient to use a token category than to define a regex within a pattern.  If you need a token with a pattern that's not in the list of tokens in the example, you can define a token with Token.Add, and then refer to it by category in the pattern.

If you do not a rule to interpret commands or token categories, pass it as a string to {@Eval}

# Pattern Best Practices & Pitfalls

Designing robust patterns in **uCalc** requires a shift from traditional "string-matching" thinking to "structural-parsing" thinking. While uCalc provides powerful regex-like capabilities, its integration with the expression engine allows for more maintainable logic.

## Best Practices

### 1. Favor Specificity over Generality
The more specific your pattern, the less the engine has to backtrack.

### 2. Use Descriptive Pattern Names
When defining custom patterns or utilizing sub-patterns, use names that reflect the **intent** of the data, not its format.
Instead of `Pattern1`, use `EmailAddress` or `ProductCode`.

## Common Pitfalls

### 1. The "Greedy" Trap
By default, some tokens may consume more than intended. Always verify if a "Lazy" match (stopping at the first possible opportunity) is required.

### 2. Deep Recursion
Patterns that call themselves or are nested too deeply can lead to stack overflows or performance degradation. Ensure recursive patterns have a clear "Base Case" or exit condition.

### 3. Ignoring Whitespace
In many parsing scenarios, ` ` (space), `\t` (tab), and `\n` (newline) are critical. Use `{@Whitespace}` to explicitly capture these when needed.


---

## Enums - ID: 427
/doc/reference/enums/

---

## Associativity - ID: 434
/doc/reference/enums/associativity/

**Description:** Operator associativity

**Remarks:**

This is for [topic: uCalc.DefineOperator].  Operators can be defined with either left to right (default) or right to left associativity.

---

## BuiltInType - ID: 428
/doc/reference/enums/builtintype/

**Description:** Data types that come with uCalc

**Remarks:**

This Enum contains a list of built-in data types that come with uCalc.

It can be used with functions that expect a data type.  For instance, you can specify a data type other than the default Double for [topic: uCalc.Parse].  You can also set the default data type for a uCalc instance with [topic: uCalc.DefaultDataType].  Typically with such functions, you can use either a [topic: uCalc.DataType] object, a string containing the data type name, or a BuiltInType Enum member for functions that require a data type.  A string is the least efficient, while a data type object is the most efficient.  Internally an enum is first converted to a data type object.

To set up a data type though with [uCalc.DataTypeOf] you can pass a member from this Enum.

If you have a data type object, you can retrieve the Enum numeric value associated with that type using [topic: uCalc.DataType.Index]

Note: Not all of the listed data types are implemented in the current version.



---

## ChildStringOptions - ID: 429
/doc/reference/enums/childstringoptions/

**Description:** Determines how child strings are handled in relation to parent strings

**Remarks:**

See [topic: uCalc.String.ChildStringOption]

---

## Comparison - ID: 430
/doc/reference/enums/comparison/

**Description:** For the result of uCalc string comparisons

**Remarks:**

[topic: uCalc.String.Compare] returns a value from this Enum after comparing two strings using uCalc patterns.

---

## DiagMemCount - ID: 599
/doc/reference/enums/diagmemcount/

**Description:** For memory usage diagnosis; returns memory footprint

**Remarks:**

This is for use with [topic: uCalc.DiagMem]

---

## DiagMemOption - ID: 613
/doc/reference/enums/diagmemoption/

**Description:** For memory usage diagnosis

**Remarks:**

This is for use with [topic: uCalc.DiagMem]

---

## ErrorCode - ID: 433
/doc/reference/enums/errorcode/

**Description:** Error numbers/messages that uCalc may return

**Remarks:**

This is the "built-in" list of errors that uCalc can return or that you can raise with [topic: uCalc.Callback.ErrorRaise].  If no error was raised, then ErrorCode.None is returned.

[topic: uCalc.Callback.ErrorRaiseMessage] internally calls the Dynamically_Defined member.



**Examples:**

### Example ID: 1190

**Description:** A practical example of a proactive error handler that automatically defines undeclared variables on the fly, allowing the expression to successfully resume execution.

**Code:**
```pseudocode
[head]
// This handler automatically defines variables when they are first used.
[callback:u AutoDefineHandler]
  // Check if the error is specifically an undefined identifier
  if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
    wl("Handler: '", uc.@Error().@Symbol(), "' is undefined. Defining it now.")
    uc.DefineVariable(uc.@Error().@Symbol());
    
    // Tell the engine to resume the operation
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
  end if
[/callback]

[body]
uc.@Error().AddHandler(AutoDefineHandler);

// 'my_var' doesn't exist yet, but the handler will create it.
var result = uc.EvalStr("my_var = 100; my_var = my_var * 2");

wl("Final result: ", result)
```

**Output:**
```
Handler: 'my_var' is undefined. Defining it now.
Final result: 200
```

---

---

## ErrorHandlerResponse - ID: 432
/doc/reference/enums/errorhandlerresponse/

**Description:** Error hander responses

**Remarks:**

Use this to set the option for [topic: uCalc.ErrorResponse].

It is also the return value of [topic: uCalc.Callback.ErrorRaise] and [topic: uCalc.Callback.ErrorRaiseMessage]

**Examples:**

### Example ID: 1190

**Description:** A practical example of a proactive error handler that automatically defines undeclared variables on the fly, allowing the expression to successfully resume execution.

**Code:**
```pseudocode
[head]
// This handler automatically defines variables when they are first used.
[callback:u AutoDefineHandler]
  // Check if the error is specifically an undefined identifier
  if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
    wl("Handler: '", uc.@Error().@Symbol(), "' is undefined. Defining it now.")
    uc.DefineVariable(uc.@Error().@Symbol());
    
    // Tell the engine to resume the operation
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
  end if
[/callback]

[body]
uc.@Error().AddHandler(AutoDefineHandler);

// 'my_var' doesn't exist yet, but the handler will create it.
var result = uc.EvalStr("my_var = 100; my_var = my_var * 2");

wl("Final result: ", result)
```

**Output:**
```
Handler: 'my_var' is undefined. Defining it now.
Final result: 200
```

---

---

## ItemIs - ID: 435
/doc/reference/enums/itemis/

**Description:** Properties that a uCalc Item may have

**Remarks:**

Items defined with uCalc typically have a combination of properties.  A variable defined with [topic: uCalc.DefineVariable] for instance will have the ItemIs.Variable property set.  An operator will have the ItemIs.Operator property set.  If it's an infix operator, in addition to having the ItemIs.Operator property set, ItemIs.Infix will also be set.  An operator also has the FunctionOrOperator property set.

The [topic: uCalc.Item.IsProperty] function can let you know if a given uCalc.Item has a certain property.  You can also set a Property with [topic: uCalc.Item.IsProperty]

You can use the [topic: uCalc.Item.IsProperty] function to cycle through the list of all items that share certain properties, or to disambiguate between items that share the same name but have different properties (for instance the + operator with the Prefix property vs another one with the Infix property).

SelectAny, and SelectAll are not exactly properties like the others, but modifiers for use with [topic: uCalc.Properties] to determine if it will match items with any of the specified properties or only items with all of the specified properties.

Some uCalc Enum elements are keywords in VB.NET.  To avoid a naming conflict, enclose the member name in brackets. For instance: [Function], [Operator], [Optional], [ByVal], etc.Not for direct use.

---

## MatchesOption - ID: 437
/doc/reference/enums/matchesoption/

**Description:** For filtering list of transformer or search matches

**Remarks:**

This allows you to filter the list of matches returned by [topic: uCalc.Transformer.Matches].

**Examples:**

### Example ID: 139

**Description:** Focusable to select only patterns from local transformer

**Code:**
```pseudocode
var t = uc.NewTransformer();
var FruitsXML =
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <!-- <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' /> -->
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <!-- <Fruit CommonName='Mango' ScientificName='Mangifera indica' /> -->
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <!-- <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' /> -->
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <!-- <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' /> -->
</Fruits>
[/verbatim];

// List names of fruit within comment, not the whole comment as well
t.@Text(FruitsXML);
var CommentedFruits = t.Pattern("<!-- {comment} -->").SetFocusable(false);
var CommentedFruitsTr = CommentedFruits.@LocalTransformer();
CommentedFruitsTr.FromTo("CommonName={@string:text}", "{text}").@Focusable(true);

t.Filter();
wl("With Focusable()")
wl("----------------")
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")

// Note: The displayed Fruit element is modified by CommentedFruitsTr.FromTo()
wl("Without Focusable()")
wl("-------------------")
wl(t.@Matches().@Text())
```

**Output:**
```
With Focusable()
----------------
Grapes
Mango
Rambutan
Watermelon

Without Focusable()
-------------------
<!-- <Fruit Grapes ScientificName='Vitis vinifera' /> -->
Grapes
<!-- <Fruit Mango ScientificName='Mangifera indica' /> -->
Mango
<!-- <Fruit Rambutan ScientificName='Nephelium lappaceum' /> -->
Rambutan
<!-- <Fruit Watermelon ScientificName='Citrullus lanatus' /> -->
Watermelon
```

---

### Example ID: 148

**Description:** MatchesOption: RootLevelOnly and InnermostOnly

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "<p id='aa'>xyz</p><p id='bb'>Hello</p ><p id='cc'>World</p>";
t.Str(txt);

t.Pattern("<p {etc}>").@LocalTransformer().FromTo("id={@string:id}", "{id}");
t.Filter();


wl("All matches")
wl("-----------")
wl(t.GetMatches(MatchesOption::All).@Text()) // All is the default
wl("")

wl("RootLevelOnly")
wl("-------------")
wl(t.GetMatches(MatchesOption::RootLevelOnly).@Text())
wl("")

wl("InnermostOnly")
wl("-------------")
wl(t.GetMatches(MatchesOption::InnermostOnly).@Text())
wl("")
```

**Output:**
```
All matches
-----------
<p aa>
aa
<p bb>
bb
<p cc>
cc

RootLevelOnly
-------------
<p aa>
<p bb>
<p cc>

InnermostOnly
-------------
aa
bb
cc
```

---

---

## MemoryTable - ID: 600
/doc/reference/enums/memorytable/

**Description:** Table of uCalc items

**Remarks:**

For internal use

---

## RegExGrammar - ID: 438
/doc/reference/enums/regexgrammar/

**Description:** RegEx grammar option for defining tokens

**Remarks:**

When tokens are defined with [topic: uCalc.Tokens.Add] a RegEx grammar from this list can be selected.
These are based on the C++ standard library options for regular expressions.

International Components for Unicode will be the new default

---

## StringListType - ID: 439
/doc/reference/enums/stringlisttype/

**Remarks:**

Not implemented

---

## TokenType - ID: 440
/doc/reference/enums/tokentype/

**Description:** Types of tokens

**Remarks:**

This enum is used when creating tokens with [topic: uCalc.Tokens.Add], [topic: uCalc.Tokens.Define], or [topic: uCalc.Tokens.Insert].


A Reducible token is typically used for operator symbols like +, -, *, etc.  Unlike alphanumeric tokens where the match includes all consecutive characters, a the minimum number of characters to produce a match is what is used.  For example, "aaaaa" would be considered one alphanumeric token, whereas consecutive minus signs "-----" might be considered as 5 separate "-" tokens.

---

## TransformerResetOption - ID: 441
/doc/reference/enums/transformerresetoption/

**Description:** Transformer reset options

**Remarks:**

For use with [topic: uCalc.Transformer.Reset].  When resetting a transformer, you have the option to select which part of it to reset; such as just the string input, or tokens, or rules, or results, or passes, or everything.

---

## Views - ID: 849
/doc/reference/enums/views/

---

## Functions and Operators - ID: 699
/doc/reference/functions-and-operators/

---

## Functions - ID: 700
/doc/reference/functions-and-operators/functions/

---

## Math - ID: 702
/doc/reference/functions-and-operators/functions/math/

**Remarks:**

These functions are mainly derived from the C++ math (<cmath>) standard library.

---

# 📐 Trigonometric Functions

| Function | Description |
|---------|-------------|
| `Cos(x)` | Computes the cosine of *x* (radians). |
| `Sin(x)` | Computes the sine of *x* (radians). |
| `Tan(x)` | Computes the tangent of *x* (radians). |
| `Acos(x)` | Computes the arc‑cosine of *x*, returning an angle in radians. |
| `Asin(x)` | Computes the arc‑sine of *x*, returning an angle in radians. |
| `Atan(x)` | Computes the arc‑tangent of *x*, returning an angle in radians. |
| `Atan2(x, y)` | Computes the arc‑tangent of *x/y* using quadrant information. |

---

# 🌡️ Hyperbolic Functions

| Function | Description |
|---------|-------------|
| `Cosh(x)` | Hyperbolic cosine of *x*. |
| `Sinh(x)` | Hyperbolic sine of *x*. |
| `Tanh(x)` | Hyperbolic tangent of *x*. |
| `Acosh(x)` | Inverse hyperbolic cosine. |
| `Asinh(x)` | Inverse hyperbolic sine. |
| `Atanh(x)` | Inverse hyperbolic tangent. |

---

# 📈 Exponential & Logarithmic Functions

| Function | Description |
|---------|-------------|
| `Exp(x)` | Computes \(e^x\). |
| `Frexp(x, y As Int Ptr)` | Splits *x* into mantissa and exponent. |
| `Ldexp(x, y As Int)` | Computes *x × 2^y*. |
| `Log(x)` | Natural logarithm of *x*. |
| `Log10(x)` | Base‑10 logarithm of *x*. |
| `Modf(x, y As Double Ptr)` | Splits *x* into fractional and integer parts. |
| `Exp2(x)` | Computes \(2^x\). |
| `Expm1(x)` | Computes \(e^x - 1\) with high precision for small *x*. |
| `Ilogb(x)` | Extracts exponent of *x* as an integer. |
| `Log1p(x)` | Computes \(\log(1 + x)\) accurately for small *x*. |
| `Log2(x)` | Base‑2 logarithm of *x*. |
| `Logb(x)` | Extracts exponent in floating‑point representation. |
| `Scalbn(x, y As Int)` | Scales *x* by \(2^y\). |
| `Scalbln(x, y As Int)` | Long‑integer version of `Scalbn`. |

---

# 🔢 Power Functions

| Function | Description |
|---------|-------------|
| `Pow(x, y As Int)` | Raises *x* to integer power *y*. |
| `Pow(x, y)` | Raises *x* to floating‑point power *y*. |
| `Sqr(x)` | Square of *x*. |
| `Sqrt(x)` | Square root of *x*. |
| `Cbrt(x)` | Cube root of *x*. |
| `Hypot(x, y)` | Computes \(\sqrt{x^2 + y^2}\) without overflow. |

---

# 🧮 Error & Gamma Functions

| Function | Description |
|---------|-------------|
| `Erf(x)` | Error function. |
| `Erfc(x)` | Complementary error function. |
| `Tgamma(x)` | Gamma function. |
| `Lgamma(x)` | Natural log of the gamma function. |

---

# 🔄 Rounding & Remainder

| Function | Description |
|---------|-------------|
| `Ceil(x)` | Rounds *x* upward to nearest integer. |
| `Floor(x)` | Rounds *x* downward to nearest integer. |
| `Fmod(x, y)` | Floating‑point remainder of *x / y*. |
| `Trunc(x)` | Truncates fractional part of *x*. |
| `Frac(x)` | Returns fractional part of *x*. |
| `Round(x)` | Rounds *x* to nearest integer. |
| `Lround(x)` | Rounds to nearest integer (returns Int). |
| `Llround(x)` | Rounds to nearest integer (returns Int64). |
| `Rint(x)` | Rounds using current rounding mode. |
| `Lrint(x)` | Same as `Rint`, returns Int. |
| `Llrint(x)` | Same as `Rint`, returns Int64. |
| `Nearbyint(x)` | Rounds using current mode without raising exceptions. |
| `Remainder(x, y)` | IEEE remainder of *x / y*. |
| `Remquo(x, y, z As Int Ptr)` | Remainder plus low bits of quotient. |

---

# ⚙️ Floating‑Point Manipulation

| Function | Description |
|---------|-------------|
| `Copysign(x, y)` | Returns *x* with the sign of *y*. |
| `Nextafter(x, y)` | Next representable value of *x* toward *y*. |
| `Nexttoward(x, y)` | Extended‑precision version of `Nextafter`. |

---

# ➕ Max, Min, Difference

| Function | Description |
|---------|-------------|
| `Fdim(x, y)` | Positive difference: max(x − y, 0). |
| `Fmax(x, y)` | Floating‑point max. |
| `Fmin(x, y)` | Floating‑point min. |
| `Min(x …)` | Minimum of a variadic list. |
| `Max(x …)` | Maximum of a variadic list. |

---

# 🔍 Other

| Function | Description |
|---------|-------------|
| `Abs(x)` | Absolute value (generic). |
| `Fabs(x)` | Floating‑point absolute value. |

---

# 🎲 Random Functions

| Function | Description |
|---------|-------------|
| `RandomSeed(x As Int)` | Sets the random seed. |
| `RandomNumber(x = 0, y = 1000)` | Returns integer in range \([x, y]\). |
| `Rand(MinX, MaxX)` | Returns integer in range using `RandomNumber`. |
| `Rand()` | Returns last random number normalized to \([0,1]\). |
| `RandFromSameSeed(x)` | Seeds with *x* and returns a random value. |
| `Rand(x)` | Overloaded: positive → new random, zero → last, negative → deterministic from seed. |

---

# ♾️ Infinity & Classification

| Function | Description |
|---------|-------------|
| `Fpclassify(x)` | Classifies floating‑point value (zero, normal, subnormal, etc.). |
| `Isfinite(x)` | True if *x* is finite. |
| `IsInf(x)` | True if *x* is infinite. |
| `IsNaN(x)` | True if *x* is NaN. |
| `IsNormal(x)` | True if *x* is a normal floating‑point value. |
| `SignBit(x)` | True if sign bit of *x* is set. |

---

# 🔢 Complex Number Operations

| Function | Description |
|---------|-------------|
| `Real(x)` | Real part of complex number. |
| `Imag(x)` | Imaginary part. |
| `Abs(x)` | Magnitude of complex number. |
| `Arg(x)` | Phase angle. |
| `Norm(x)` | Squared magnitude. |
| `Conj(x)` | Complex conjugate. |
| `Polar(x)` | Constructs complex number from magnitude/angle. |
| `Proj(x)` | Complex projection onto Riemann sphere. |

---

# 🔢 Complex Trigonometric & Related Functions

| Function | Description |
|---------|-------------|
| `Cos(x)` | Complex cosine. |
| `Cosh(x)` | Complex hyperbolic cosine. |
| `Exp(x)` | Complex exponential. |
| `Log(x)` | Complex natural log. |
| `Log10(x)` | Complex base‑10 log. |
| `Pow(x, y)` | Complex power. |
| `Sin(x)` | Complex sine. |
| `Sinh(x)` | Complex hyperbolic sine. |
| `Sqrt(x)` | Complex square root. |
| `Tan(x)` | Complex tangent. |
| `Tanh(x)` | Complex hyperbolic tangent. |
| `Acos(x)` | Complex arc‑cosine. |
| `Acosh(x)` | Complex inverse hyperbolic cosine. |
| `Asin(x)` | Complex arc‑sine. |
| `Asinh(x)` | Complex inverse hyperbolic sine. |
| `Atan(x)` | Complex arc‑tangent. |
| `Atanh(x)` | Complex inverse hyperbolic tangent. |

---


---

## Strings - ID: 703
/doc/reference/functions-and-operators/functions/strings/

**Remarks:**

# 🧵 Basic String Operations

| Function | Description |
|---------|-------------|
| `Repeat(string, size_t) As String` | Returns a new string consisting of the first argument repeated `y` times. |
| `Append(string, string)` | Appends the second string to the first (mutating). |
| `Append_Copy(string, string) As String` | Returns a new string equal to `x + y` without modifying the original. |
| `Insert(string, size_t, string)` | Inserts substring `z` into `x` at index `y` (mutating). |
| `Insert_Copy(string, size_t, string) As String` | Returns a new string with `z` inserted at index `y`. |
| `Erase(string, size_t = 0, size_t = 0)` | Removes a substring from `x` starting at `y` of length `z` (mutating). |
| `Erase_Copy(string, size_t = 0, size_t = 0) As String` | Returns a new string with the specified range removed. |
| `Fill(size_t, uint8_t) As String` | Creates a string of length `x` filled with byte `y`. |
| `Replace(string, size_t, size_t, string)` | Replaces a substring in `a` starting at `b` of length `c` with `d` (mutating). |
| `Replace_Copy(string, size_t, size_t, string) As String` | Returns a new string with the replacement applied. |
| `Substr(string, size_t = 0, size_t = 0) As String` | Returns a substring starting at `y` of length `z`. |
| `Length(string) As Size_t` | Returns the number of characters in the string. |
| `C_Str(string) As Int8u Ptr` | Returns a pointer to the underlying C‑style character buffer. |
| `Str(anytype) As String` | Converts any type to a string. |

---

# 🔤 Case & Trimming

| Function | Description |
|---------|-------------|
| `LCase(string) As String` | Converts all characters to lowercase. |
| `UCase(string) As String` | Converts all characters to uppercase. |
| `LTrim(string, string = "") As String` | Removes leading whitespace or specified characters. |
| `RTrim(string, string = "") As String` | Removes trailing whitespace or specified characters. |
| `Trim(string, string = "") As String` | Removes leading and trailing whitespace or specified characters. |

---

# 🔢 Numeric Conversions

| Function | Description |
|---------|-------------|
| `Bin(int) As String` | Converts an integer to a binary string. |
| `Oct(int) As String` | Converts an integer to an octal string. |
| `Hex(int) As String` | Converts an integer to a hexadecimal string. |

---

# 📁 File Utilities

| Function | Description |
|---------|-------------|
| `File(string) As String` | Reads the entire contents of a file into a string. |
| `FileSize(string) As Size_t` | Returns the size of a file in bytes. |

---

# 🔣 Character Functions

| Function | Description |
|---------|-------------|
| `Chr(size_t) As String` | Converts a numeric code point to a single‑character string. |
| `Asc(string) As Size_t` | Returns the code point of the first character. |
| `Asc(string, size_t) As Size_t` | Returns the code point at position `Pos` (1‑based). Equivalent to `Asc(Substr(s, Pos - 1, 1))`. |

---

# 🧮 Comparisons & Aggregates

| Function | Description |
|---------|-------------|
| `Min(string ...) As String` | Returns the lexicographically smallest string. |
| `Max(string ...) As String` | Returns the lexicographically largest string. |
| `Compare(string, string) As Size_t` | Compares two strings lexicographically (typically returns `<0`, `0`, or `>0`). |

---

# 🔍 Search & Predicates

| Function | Description |
|---------|-------------|
| `Contains(string, string, size_t = 0) As Bool` | Returns true if the substring exists in `txt` starting at offset `z`. |
| `StartsWith(string, string) As Bool` | Returns true if the string begins with the given prefix. |
| `EndsWith(string, string) As Bool` | Returns true if the string ends with the given suffix. |
| `IndexOf(string, string, size_t = 0) As Size_t` | Finds the first occurrence of `y` in `x` starting at `z`. |
| `LastIndexOf(string, string, size_t = 0) As Size_t` | Finds the last occurrence of `y` in `x` starting backward from `z`. |
| `Find_First_Of(string, string, size_t = 0) As Size_t` | Finds the first character in `x` that matches any in `y`. |
| `Find_Last_Of(string, string, size_t = 0) As Size_t` | Finds the last character in `x` that matches any in `y`. |
| `Find_First_Not_Of(string, string, size_t = 0) As Size_t` | Finds the first character in `x` not in `y`. |
| `Find_Last_Not_Of(string, string, size_t = 0) As Size_t` | Finds the last character in `x` not in `y`. |

---

# 📏 Padding & Formatting

| Function | Description |
|---------|-------------|
| `PadLeft(string, size_t, string) As String` | Pads the string on the left to reach the specified width. |
| `PadRight(string, size_t, string) As String` | Pads the string on the right (you listed PadLeft twice; I assume one is PadRight). |
| `Format(string, string) As String` | Formats a string using a format specifier. |
| `Format(string, int) As String` | Formats an integer using a format specifier. |
| `Format(string, double) As String` | Formats a floating‑point value using a format specifier. |

Format functions are based on C++ standard library std::format.  A number of others are also based on C++ string functions.  Others are somewhat similar to C# functions.


---

## Specialized - ID: 704
/doc/reference/functions-and-operators/functions/specialized/

**Remarks:**

# ⚠️ Error & State‑Reset Functions

| Function | Description |
|---------|-------------|
| `Error(int) As Int` | Triggers an error using a numeric code. Returns an `ErrorHandlerResponse` enum value (0, 1, or 2). |
| `Error(string) As Int` | Triggers an error with a custom message. Returns an `ErrorHandlerResponse` enum value. |
| `Swap(ByHandle AnyType, ByHandle AnyType)` | Swaps the values of two variables by reference. No return value. |
| `Reset(ByHandle AnyType)` | Resets a variable to its default value (0 for numeric types, empty for strings, etc.). No return value. |

---

# 🧭 Pointer & Memory‑Like Operations

| Function | Description |
|---------|-------------|
| `AddressOf(ByHandle AnyType) As SameTypeAs:0 Ptr` | Returns a pointer to the variable’s storage location. |
| `ValueAt(ByHandle AnyType Ptr, size_t = 0) As SameTypeAs:0` | Dereferences a typed pointer at the given index (pointer + index). |
| `ValueAtType(ByHandle AnyType, Pointer, size_t = 0) As SameTypeAs:0` | Dereferences a raw pointer using a specified data type. |
| `AddPtr(ByHandle AnyType, size_t = 1) As SameTypeAs:0` | Performs pointer arithmetic and returns the resulting pointer. |
| `SubtractPtr(ByHandle AnyType, size_t = 1) As SameTypeAs:0` | Same as `AddPtr` but subtracts the offset. |
| `SetVar(ByRef AnyType, SameTypeAs:0) As SameTypeAs:0` | Assigns a value to a variable by reference and returns the assigned value. |

---

# 🧮 Conditional Functions

| Function | Description |
|---------|-------------|
| `IIf(bool, ByExpr AnyType, ByExpr SameTypeAs:1) As SameTypeAs:1` | Immediate‑if expression; evaluates only the selected branch. |
| `IIf(bool, ByExpr string, ByExpr string = …) As String` | String‑specific overload. |
| `IIf(bool, ByExpr Complex, ByExpr Complex) As Complex` | Complex‑number overload. |


---

# 🧩 Argument Introspection & Expression Evaluation

| Function | Description |
|---------|-------------|
| `Arg(size_t)` | Returns the nth argument passed to the current function or expression. |
| `ArgCount() As Size_t` | Returns the number of arguments passed. |
| `Parse(string, string = "")` | Parses an expression using an optional data‑type string. Returns a pointer to the parsed expression. |
| `Eval(string)` | Evaluates an expression and returns a numeric result. |
| `EvalStr(string, bool = True) As String` | Evaluates an expression and returns a formatted string. |
| `Evaluate(Pointer) As Double` | Evaluates a previously parsed expression via pointer. |
| `EvaluateInt(Pointer) As Int` | Evaluates a parsed expression and returns an integer. |
| `EvaluateStr(Pointer, bool = True) As String` | Evaluates a parsed expression and returns a formatted string. |

---

# 🔄 Expression & Environment Manipulation

| Function | Description |
|---------|-------------|
| `FromTo(string, string, bool = True)` | Defines a rewrite rule using uCalc’s pattern‑based transformer. Can be temporary or permanent. |
| `ExprPtr(AnyType) As Pointer` | Returns a pointer to the internal representation of an expression or value. |
| `Define(string, Pointer = 0, Pointer = 0)` | Defines a variable, operator, or function. Parameters: definition string, optional address, optional datatype handle. |
| `uCalcInstance() As Pointer` | Returns a pointer/handle to the current uCalc engine instance. |
| `Precedence(string, int64_t) As size_t` | Returns the precedence level of an operator. |

---

# 🔁 Looping Constructs

| Function | Description |
|---------|-------------|
| `DoLoop(ByExpr bool, ByExpr AnyType, ByExpr bool = True) As Void` | Executes a do/loop construct inside an expression. |
| `ForLoop(ByHandle Counter, Start, Finish, Step, ByExpr AnyType)` | Executes a for‑loop with a counter variable and an expression body. |

---

# 🔢 Numeric Utilities

| Function | Description |
|---------|-------------|
| `BaseConvert(string, int)` | Converts a number string from one base to another. |
| `Sgn(Number)` | Returns −1, 0, or +1 depending on the sign of the number. |
| `Inf() = 1/0` | Returns positive infinity. |
| `NaN() = 0/0` | Returns a NaN value. |


---

## Operators - ID: 701
/doc/reference/functions-and-operators/operators/

**Remarks:**

Precedence numbers are **relative only**—higher means tighter binding.

---

# 🔢 Integer Operators

| Prec | Operator | Signature | Description |
|------|----------|-----------|-------------|
| 50 | `x + y` | `{x As Int} + {y As Int} As Int` | Integer addition. |
| 50 | `x - y` | `{x As Int} - {y As Int} As Int` | Integer subtraction. |
| 60 | `x * y` | `{x As Int} * {y As Int} As Int` | Integer multiplication. |
| 60 | `x / y` | `{x As Int} / {y As Int} As Int` | Integer division (truncating). |
| 60 | `x % y` | `{x As Int} % {y As Int} As Int` | Integer remainder. |

---

# 🧮 Double‑Precision Operators

| Prec | Operator | Signature | Description |
|------|----------|-----------|-------------|
| 50 | `x + y` | `{x} + {y}` | Floating‑point addition. |
| 50 | `x - y` | `{x} - {y}` | Floating‑point subtraction. |
| 60 | `x * y` | `{x} * {y}` | Floating‑point multiplication. |
| 60 | `x / y` | `{x} / {y}` | Floating‑point division. |
| 60 | `x \\ y` | `{x} \\ {y} = Trunc(x / y)` | Integer‑style division on doubles. |
| 60 | `x mod y` | `{x} mod {y}` | Floating‑point modulo. |
| 70 | `+x` | `+{x}` | Unary plus. |
| 70 | `-x` | `-{x}` | Unary negation. |
| 90 | `x!` | `{x}!` | Factorial. |
| 80 | `x ^ y` | `{x} ^ {y As Int}` | Exponentiation with integer exponent. |
| 80 | `x ^ y` | `{x} ^ {y}` | Exponentiation with floating exponent. |

---

# 🔤 String Operators

| Prec | Operator | Signature | Description |
|------|----------|-----------|-------------|
| 50 | `x + y` | `{ByHandle x As String} + {ByHandle y As AnyType} As String` | String concatenation with automatic conversion. |
| 50 | `x + y` | `{ByHandle x As AnyType} + {ByHandle y As String} As String` | Concatenation (reverse order). |
| 50 | `x + y` | `{x As String} + {y As String} As String` | Pure string concatenation. |
| 30 | `x & y` | `{x As Int} & {y As Int} As Int` | Bitwise AND for integers. |
| 30 | `x & y` | `{ByHandle x As AnyType} & {ByHandle y As AnyType} As String` | String concatenation operator (VB‑style). |
| 60 | `x * y` | `{x As String} * {y As size_t} As String` | String repetition. |

---

# 🧭 Pointer Arithmetic

| Prec | Operator | Signature | Description |
|------|----------|-----------|-------------|
| 50 | `ptr + n` | `{ByHandle x As AnyType Ptr} + {y As Int} As SameTypeAs:0 Ptr` | Pointer addition. |
| 50 | `ptr - n` | `{ByHandle x As AnyType Ptr} - {y As Int} As SameTypeAs:0 Ptr` | Pointer subtraction. |

---

# 🔍 Comparison Operators  
*(String, Int, Double, and generic overloads)*

| Prec | Operator | Signature | Description |
|------|----------|-----------|-------------|
| 40 | `x == y` | `{x As String} == {y As String} As Bool` | String equality. |
| 40 | `x <> y` | `{x As String} <> {y As String} As Bool` | String inequality. |
| 40 | `<, >, <=, >=` | String versions | Lexicographic comparisons. |
| 40 | `x == y` | `{x As Int} == {y As Int} As Bool` | Integer equality. |
| 40 | `x <> y` | `{x As Int} <> {y As Int} As Bool` | Integer inequality. |
| 40 | `<, >, <=, >=` | Integer versions | Numeric comparisons. |
| 40 | `x == y` | `{x} == {y} As Bool` | Generic equality. |
| 40 | `x <> y` | `{x} <> {y} As Bool` | Generic inequality. |
| 40 | `<, >, <=, >=` | Generic versions | Type‑dependent comparisons. |

---

# 🔢 Complex Operators

| Prec | Operator | Signature | Description |
|------|----------|-----------|-------------|
| 50 | `x + y` | `{x As Complex} + {y As Complex} As Complex` | Complex addition. |
| 50 | `x - y` | `{x As Complex} - {y As Complex} As Complex` | Complex subtraction. |
| 60 | `x * y` | `{x As Complex} * {y As Complex} As Complex` | Complex multiplication. |
| 60 | `x / y` | `{x As Complex} / {y As Complex} As Complex` | Complex division. |
| 80 | `x == y` | `{x As Complex} == {y As Complex} As Bool` | Complex equality. |
| 80 | `x <> y` | `{x As Complex} <> {y As Complex} As Bool` | Complex inequality. |
| 80 | `x ^ y` | `{x As Complex} ^ {y As Complex} As Complex` | Complex exponentiation. |

---

# 🟦 Boolean Operators

| Prec | Operator | Signature | Description |
|------|----------|-----------|-------------|
| 35 | `!x` | `! {x As Bool} As Bool` | Logical NOT. |
| 35 | `Not x` | `Not {x As Bool} As Bool` | Alternative NOT. |
| 30 | `x && y` | `{x As Bool} && {ByExpr y As Bool} As Bool` | Logical AND (short‑circuit). |
| 30 | `x And y` | `{x As Bool} And {ByExpr y As Bool} As Bool` | Logical AND (non‑short‑circuit). |
| 30 | `x AndAlso y` | `{x As Bool} AndAlso {ByExpr y As Bool} As Bool` | Short‑circuit AND (VB‑style). |
| 20 | `x || y` | `{x As Bool} || {ByExpr y As Bool} As Bool` | Logical OR (short‑circuit). |
| 20 | `x Or y` | `{x As Bool} Or {ByExpr y As Bool} As Bool` | Logical OR (non‑short‑circuit). |
| 20 | `x OrElse y` | `{x As Bool} OrElse {ByExpr y As Bool} As Bool` | Short‑circuit OR (VB‑style). |

---

# 🧱 Bitwise Operators

| Prec | Operator | Signature | Description |
|------|----------|-----------|-------------|
| 35 | `~x` | `~ {x As Int} As Int` | Bitwise NOT. |
| 35 | `Not x` | `Not {x Int} As Int` | Alternative bitwise NOT. |
| 30 | `x And y` | `{x As Int} And {y As Int} As Int` | Bitwise AND. |
| 30 | `x BitAnd y` | `{x As Int} BitAnd {y As Int} As Int` | Explicit bitwise AND. |
| 20 | `x | y` | `{x As Int} | {y As Int} As Int` | Bitwise OR. |
| 20 | `x Or y` | `{x As Int} Or {y As Int} As Int` | Bitwise OR (keyword). |
| 20 | `x BitOr y` | `{x As Int} BitOr {y As Int} As Int` | Explicit bitwise OR. |
| 20 | `x Xor y` | `{x As Int} Xor {y As Int} As Int` | Bitwise XOR. |
| 45 | `x << y` | `{x As Int} << {y As Int} As Int` | Left shift. |
| 45 | `x >> y` | `{x As Int} >> {y As Int} As Int` | Right shift. |

---

# 📝 Assignment Operators

| Prec | Assoc | Operator | Signature | Description |
|------|--------|----------|-----------|-------------|
| 15 | Right‑to‑Left | `x = y` | `{ByRef x As AnyType} = {y As SameTypeAs:0} As SameTypeAs:0` | Generic assignment. |
| 15 | Right‑to‑Left | `x = y` | `{ByRef x As String} = {y As String} As String` | String assignment. |
| 15 | Right‑to‑Left | `x = y` | `{ByRef x As Complex} = {y As Complex} As Complex` | Complex assignment. |

---

# 🔼 Increment / Decrement

| Operator | Description |
|----------|-------------|
| `++x` | Prefix increment. |
| `x++` | Postfix increment. |
| `--x` | Prefix decrement. |
| `x--` | Postfix decrement. |

---

# 🧩 Miscellaneous Operators

| Operator | Description |
|----------|-------------|
| `;` | Statement separator. |
| `,` | Argument separator (comma operator). |


---

## Classes - ID: 8
/doc/reference/classes/

**Description:** uCalc main class

---

## uCalc - ID: 13
/doc/reference/classes/ucalc/

---

## Introduction - ID: 941
/doc/reference/classes/ucalc/introduction/

**Description:** An overview of the main uCalc class, the central component for parsing, evaluation, and customization.

**Remarks:**

# 🚀 The uCalc Class: Your Parsing Engine

The `uCalc` class is the heart of the library. An instance of this class represents a complete, sandboxed evaluation engine with its own isolated set of variables, functions, operators, and settings. It serves as the primary factory and context for all parsing and transformation operations.

Think of a `uCalc` object as a self-contained language environment. You can create multiple instances, each with a different configuration, allowing you to run different parsers side-by-side without interference. This is the starting point for nearly everything you will do with the library.

---

## ⚡ Core Evaluation Methods
These methods are the workhorses for processing expression strings.

| Member | Description |
| :--- | :--- |
| [`Eval`](/Reference/uCalcBase/uCalc/Eval) | Parses and evaluates a string expression in a single step, returning a numeric result. |
| [`EvalStr`](/Reference/uCalcBase/uCalc/EvalStr) | Parses and evaluates an expression in a single step, returning the result of any data type as a string. |
| [`Parse`](/Reference/uCalcBase/uCalc/Parse) | Compiles a string expression into an intermediate, reusable object for high-performance evaluation. |

---

## 🛠️ Symbol Definition Methods
These methods allow you to extend the engine's syntax and define data at runtime.

| Member | Description |
| :--- | :--- |
| [`Define`](/Reference/uCalcBase/uCalc/Define) | Creates functions, operators, variables, and other symbols using a single, versatile definition string. |
| [`DefineFunction`](/Reference/uCalcBase/uCalc/DefineFunction) | Registers a user-defined function for use in expressions, supporting inline definitions, external callbacks, and advanced features like overloading, recursion, bootstrapping, variadic args, lazy argument evaluation, and more. |
| [`DefineOperator`](/Reference/uCalcBase/uCalc/DefineOperator) | Defines a custom operator to extend or modify the expression syntax at runtime. |
| [`DefineVariable`](/Reference/uCalcBase/uCalc/DefineVariable) | Defines a new variable or array within the uCalc engine, with an optional initial value and data type. |
| [`DefineConstant`](/Reference/uCalcBase/uCalc/DefineConstant) | Defines a named, read-only constant for use in expressions. |
| [`CreateAlias`](/Reference/uCalcBase/uCalc/CreateAlias) | Creates a new symbol that behaves exactly like an existing symbol. |

---

## ⚙️ Instance & Lifetime Management
These members control the creation, cloning, and destruction of `uCalc` engine instances.

| Member | Description |
| :--- | :--- |
| [`Constructor`](/Reference/uCalcBase/uCalc/Constructor) | Creates a new uCalc instance, optionally cloning an existing one, or creating an empty placeholder. |
| [`Clone`](/Reference/uCalcBase/uCalc/Clone) | Creates an identical, but independent, copy of the current uCalc instance, including all its defined variables, functions, and settings. |
| [`Release`](/Reference/uCalcBase/uCalc/Release) | Explicitly releases a uCalc instance and frees all of its associated memory and resources. |
| [`Owned`](/Reference/uCalcBase/uCalc/Owned) | Manages automatic resource release for an object, enabling RAII-style lifetime management primarily for C++. |
| [`DefaultInstance`](/Reference/uCalcBase/uCalc/DefaultInstance) | Gets/sets the globally accessible default uCalc instance. |
| [`IsDefault`](/Reference/uCalcBase/uCalc/IsDefault) | Gets or sets whether the current uCalc instance is the active default for the current thread. |
| [`DefaultClear`](/Reference/uCalcBase/uCalc/DefaultClear) | Resets the default instance stack, restoring the original default instance to its initial state. |
| [`DefaultCount`](/Reference/uCalcBase/uCalc/DefaultCount) | Gets the number of uCalc instances currently on the default instance stack. |
| [`ResetAll`](/Reference/uCalcBase/uCalc/ResetAll) | Resets the entire uCalc library to its initial startup state, releasing all instances and clearing all definitions. |

---

## 🧐 Introspection & Metadata
These members allow you to query the state and symbols within a `uCalc` instance.

| Member | Description |
| :--- | :--- |
| [`ItemOf`](/Reference/uCalcBase/uCalc/ItemOf) | Retrieves the uCalc.Item object for a symbol by its name, optionally filtered by properties to disambiguate overloads. |
| [`Items`](/Reference/uCalcBase/uCalc/Items) | Retrieves a collection of all defined symbols (functions, variables, operators, etc.). |
| [`DataTypeOf`](/Reference/uCalcBase/uCalc/DataTypeOf) | Retrieves the DataType object associated with a specific item name, type name, or expression. |
| [`DataTypes`](/Reference/uCalcBase/uCalc/DataTypes) | Retrieves a collection of all data types registered within the current uCalc instance. |
| [`Properties`](/Reference/uCalcBase/uCalc/Properties) | Creates a bitmask for querying items by their properties, such as function, operator, or variable. |
| [`Description`](/Reference/uCalcBase/uCalc/Description) | Retrieves or assigns a user-defined text description to a uCalc object, useful for attaching metadata and for debugging. |
| [`Error`](/Reference/uCalcBase/uCalc/Error) | Provides access to the ErrorInfo object with details about the last error. |

---

## 🎨 Customization & Extensibility
These members provide access to the engines that control syntax and output formatting.

| Member | Description |
| :--- | :--- |
| [`ExpressionTransformer`](/Reference/uCalcBase/uCalc/ExpressionTransformer) | Returns the singleton transformer instance used to pre-process expressions before they are parsed. |
| [`TokenTransformer`](/Reference/uCalcBase/uCalc/TokenTransformer) | Retrieves the dedicated transformer for defining token-level transformations, enabling custom syntax like string interpolation or hex literals. |
| [`ExpressionTokens`](/Reference/uCalcBase/uCalc/ExpressionTokens) | Retrieves the token definition collection used by the expression parser, allowing for inspection and customization. |
| [`TransformerForRulePatterns`](/Reference/uCalcBase/uCalc/TransformerForRulePatterns) | Retrieves a singleton transformer that pre-processes pattern definition strings before they are compiled into rules. |
| [`TransformerForRuleReplacements`](/Reference/uCalcBase/uCalc/TransformerForRuleReplacements) | Retrieves a meta-transformer that pre-processes the replacement strings of other transformer rules before they are defined. |
| [`Format`](/Reference/uCalcBase/uCalc/Format) | Defines a declarative rule for transforming the string output of evaluation functions. |
| [`FormatRemove`](/Reference/uCalcBase/uCalc/FormatRemove) | Removes one or all custom output formatting rules previously defined with the Format method. |
| [`DefaultDataType`](/Reference/uCalcBase/uCalc/DefaultDataType) | Gets or sets the default data type used for implicit typing during definitions and evaluation. |

---

## 🏭 Component Factories
These methods create instances of other major uCalc components.

| Member | Description |
| :--- | :--- |
| [`NewString`](/Reference/uCalcBase/uCalc/NewString) | Creates a new uCalc.String object. |
| [`NewTransformer`](/Reference/uCalcBase/uCalc/NewTransformer) | Creates a new Transformer object. |

---

## 🔍 Low-Level & Diagnostics
These members are for advanced use cases, performance tuning, and debugging.

| Member | Description |
| :--- | :--- |
| [`Handle`](/Reference/uCalcBase/uCalc/Handle) | Returns the internal handle of the uCalc instance, a unique identifier used by the library for low-level operations. |
| [`MemoryIndex`](/Reference/uCalcBase/uCalc/MemoryIndex) | Returns a stable, session-unique integer that identifies a uCalc object, primarily for diagnostics and tracking object lifetimes. |
| [`DiagMem`](/Reference/uCalcBase/uCalc/DiagMem) | Provides a programmatic way to query uCalc's internal memory usage. |
| [`ValueAt`](/Reference/uCalcBase/uCalc/ValueAt) | Dereferences a pointer and returns a string representation of the value, allowing for on-the-fly type casting. |

**Examples:**

### Example ID: 1296

**Description:** A quick start example showing defining a variable, a function, and evaluating an expression.

**Code:**
```pseudocode
uc.DefineVariable("x = 10");
uc.DefineFunction("DoubleThis(n) = n * 2");

wl(uc.Eval("DoubleThis(x) + 5"))
```

**Output:**
```
25
```

---

### Example ID: 271

**Description:** Manage separate parser contexts for different application modules.

**Code:**
```pseudocode
// --- Main Application Context ---
// Starting with the 'uc' object as the initial default.
uCalc::@DefaultInstance().DefineConstant("PI = 3.14159");
wl("Initial Count: ", uCalc::@DefaultCount())

// --- A Plugin needs a temporary, isolated context ---
NewUsing(uCalc, moduleCalc)
moduleCalc.@IsDefault(true); // Push the new instance onto the stack.
wl("Count after module pushes new default: ", uCalc::@DefaultCount())

// The module's context is now active.
// uCalc::DefaultInstance() would now return 'moduleCalc'.
End Using

// When 'moduleCalc' goes out of scope, it's destroyed and automatically
// removed from the stack, restoring the previous default.

wl("Count after module instance is disposed: ", uCalc::@DefaultCount())

// Verify the original default instance is active again.
var result = uCalc::@DefaultInstance().EvalStr("PI");
wl("Original context restored. PI = ", result)
```

**Output:**
```
Initial Count: 1
Count after module pushes new default: 2
Count after module instance is disposed: 1
Original context restored. PI = 3.14159
```

---

### Example ID: 161

**Description:** "using" (C#) and Owned (C++) for auto-releasing uCalc object

**Code:**
```pseudocode

// In C# and VB you should use "using".
// In C++ you can flag a uCalc object for
// auto-release with Owned(), or by setting
// the last parameter of the constructor to true.

uc.@IsDefault(true); // Set uc as the default uCalc object
uCalc::@DefaultInstance().DefineVariable("Value = 'Original uc object'");
wl(uCalc::@DefaultInstance().EvalStr("Value")) // Outputs: Original uc object

[NotCpp]// Use "using" so that the object is auto-released when it it goes out of scope[/NotCpp]
   NewUsing(uCalc, uCalcTemp) [cpp]// Make uCalcTemp owned so it reverts back to uc when uCalcTemp goes out of scope[/cpp]
   uCalcTemp.@IsDefault(true); // Set uCalcTemp as the default uCalc object
   uCalc::@DefaultInstance().DefineVariable("Value = 'uCalcTemp object'");
   wl(uCalc::@DefaultInstance().EvalStr("Value")) // uCalcTemp object
End Using
// uCalcTemp goes out of scope here, and the default uCalc object reverts back to uc

wl(uCalc::@DefaultInstance().EvalStr("Value")) // Original uc object

[c]{!Eval: Chr(123)}[/c][vb]If True Then[/vb]
   [cs]/*using*/[/cs] New(uCalc, uCalcSticky) // remains the default even after going out of scope
   uCalcSticky.@IsDefault(true); // Set uCalcSticky as the default uCalc object
   uCalc::@DefaultInstance().DefineVariable("Value = 'uCalcSticky object'");
   wl(uCalc::@DefaultInstance().EvalStr("Value")) // Outputs: uCalcSticky object
[c]{!Eval: Chr(125)}[/c][vb]End If[/vb]    // The uCalcSticky object itself goes out of scope here, but internally it remains the default uCalc object

wl(uCalc::@DefaultInstance().EvalStr("Value"))
```

**Output:**
```
Original uc object
uCalcTemp object
Original uc object
uCalcSticky object
uCalcSticky object
```

---

### Example ID: 14

**Description:** Passing arg ByExpr (delayed lazy eval) and ByHandle

**Code:**
```pseudocode
[head]
[callback MySum]
   var Total = 0.0;
   var Expr = cb.ArgExpr(1);
   var Start = cb.Arg(2);
   var Finish = cb.Arg(3);
   var Variable = cb.ArgItem(4);

   for(double x = Start to Finish)
      Variable.Value(x);
      Total += Expr.Evaluate();
   end for
   cb.Return(Total);
[/callback]
[body]
uc.DefineVariable("x");
uc.DefineFunction("Sum(ByExpr Expr, Start, Finish, ByHandle Var)", MySum);
wl(uc.Eval("Sum(x ^ 2, 1, 10, x)"))

```

**Output:**
```
385
```

---

---

## (Constructor) - ID: 647
/doc/reference/classes/ucalc/-constructor/

**Description:** Creates a new uCalc instance, optionally cloning an existing one, or creating an empty placeholder.

**Remarks:**

The uCalc constructor initializes a new evaluation engine. Depending on the overload used, the new instance may:

- Clone the default engine
- Clone a specific engine
- Create an empty placeholder for later assignment

Each instance maintains its own isolated namespace of variables, functions, operators, tokens, transformers, and configuration settings.

---

## **Constructor Overloads**

### **1. `uCalc(bool setAsDefault = false, bool autoRelease = false)`**  
Creates a new uCalc instance as a clone of the **Default** instance.

- **setAsDefault = true**  
  The new instance becomes the new Default instance.  
  Equivalent to calling `IsDefault(true)` after construction.

- **autoRelease (C++ only)**  
  Marks the instance for automatic release when it goes out of scope.  
  Equivalent to calling `Owned()`.

**Isolation:**  
The new instance is a deep clone. Changes to this instance do **not** affect the Default instance or any other instance.

---

### **2. `uCalc(uCalc other)` (C# only)**  
Creates a new instance as a clone of another uCalc instance.

- Not supported in C++ (invokes the native copy constructor instead).  
- For cross‑language consistency, prefer `Clone()`.

---

### **4. `uCalc(uCalc::Empty)`**  
Creates an **empty placeholder** instance.

- Allocates only a minimal handle  
- No internal engine state  
- Can later be assigned a real instance (e.g., via `Clone()` or assignment)

Useful for deferred initialization.

---

# **Instance Lifetime & Scoping**

uCalc instances behave differently depending on:

- How they were created (constructor vs `Clone()`)  
- Whether they are owned  
- Whether the language supports deterministic destruction  

Below is the unified model.

---

## **Lifetime Rules (All Languages)**

### **Instances created with `Clone()`**
- Always persist until explicitly released with `Release()`  
- Going out of scope does **not** release them  
- The variable holding the handle may be destroyed, but the engine remains alive

**Therefore:**  
Always call `Release()` when you no longer need a cloned instance.

---

## **C# Lifetime Rules**

### **Constructor-created instances**
- Are automatically released **only** when used with `using`  
- Without `using`, they behave like cloned instances and must be released manually

### **Clone() instances**
- Same rule: auto-release only when wrapped in `using`

**Examples:**

```csharp
{  
   var u1 = new uCalc();  
   var u2 = uc.Clone();  
   // Neither u1 nor u2 auto-release  
}

{  
   using var u1 = new uCalc();  
   using var u2 = uc.Clone();  
   // Both auto-release  
}
```

---

## **C++ Lifetime Rules**

### **Constructor-created instances**
- Auto-release when the object goes out of scope

### **Clone() instances**
- Must be released manually unless wrapped in a stack‑allocated uCalc

**Examples:**

```cpp
{  
   auto u1 = new uCalc();  
   auto u2 = uc.Clone();  
   // Must call Release() manually  
}

{  
   uCalc u1;  
   uCalc u2(uc.Clone());  
   uc1.Owned();
   uc2.Owned();
   // Auto-release on scope exit  
}
```

---

# **MemoryIndex vs Handle**

- **Handle**  
  Internal pointer-like value; unpredictable value; cannot be duplicated.

- **MemoryIndex**  
  Stable, predictable identifier for an instance.  
  Useful for detecting whether an instance has been released.

Released instances are recycled.  
If you create a new instance immediately after releasing another, it will typically reuse the same MemoryIndex.

---

# **Comparative Analysis — Why uCalc?**

### **vs. Native C#/C++ Objects**
- uCalc instances encapsulate a full expression engine, not just data  
- Cloning produces isolated execution environments  
- Deterministic destruction is optional and configurable  
- MemoryIndex provides introspection not available in native objects

### **vs. Script Engines**
- uCalc instances are lightweight and fast to clone  
- Each instance maintains its own namespace  
- No global state unless explicitly shared


**Examples:**

### Example ID: 255

**Description:** Quick Start

**Code:**
```pseudocode
// Create a new instance
NewUsing(uCalc, calc)

// Evaluate an expression
wl(calc.Eval("2 + 3"))
End Using
```

**Output:**
```
5
```

---

### Example ID: 256

**Description:** Creating isolated evaluation contexts.

**Code:**
```pseudocode
New(uCalc, main)
main.DefineVariable("rate = 0.05");

var scenarioA = main.Clone();
var scenarioB = main.Clone();

scenarioA.DefineVariable("rate = 0.10");
scenarioB.DefineVariable("rate = 0.20");

wl("A: ", scenarioA.Eval("1000 * rate"))
wl("B: ", scenarioB.Eval("1000 * rate"))
wl("Main: ", main.Eval("1000 * rate"))
main.Release();
scenarioA.Release();
scenarioB.Release();

```

**Output:**
```
A: 100
B: 200
Main: 50
```

---

### Example ID: 78

**Description:** Creating uCalc instances

**Code:**
```pseudocode
uc.DefineVariable("x = 123");

New(uCalc, uc1) // Creates a new instance
wl(uc1.EvalStr("x")) // uc1 does not have a variable named x
uc1.Release(); // Releases uc1 if it is no longer needed

var uc2 = uc.Clone(); // Creates new instance that is a clone of uc
wl(uc2.EvalStr("x")) // starts with the value of x obtained from uc
uc2.Eval("x = 456"); // Changes the value of x in uc1 but not uc
wl(uc2.EvalStr("x"))
wl(uc.EvalStr("x")) // The original x in uc remains unchanged
uc2.Release();

// Language specific - auto-releasing uCalc object
[vb]#If False[/vb]
{ // Instances pointed to by neither uCalc1 nor uCalc2 will be released when they go out of scope
   var uCalc1 = new uCalc();
   var uCalc2 = uc.Clone();
   // Call uCalc1.Release() and uCalc2.Release() explicitly if want to release them
}

{ // The instances that both uCalc1 and uCalc2 point to will be released when uCalc1 and uCalc2 go out of scope
   [cs]using var uCalc1 = new uCalc();
   using var uCalc2 = uc.Clone();[/cs]
   [cpp]uCalc uCalc1;
   uCalc uCalc2(uc.Clone());[/cpp]
   // No need for uCalc1.Release() or uCalc2.Release(), they will automatically be released
}
[vb]#End If[/vb]
```

**Output:**
```
Undefined identifier
123
456
123
```

---

### Example ID: 21

**Description:** Evaluating expressions

**Code:**
```pseudocode
// See EvalStr for more examples.

wl(uc.Eval("1+1"))
wl(uc.Eval("5*(3+9)^2"))
wl(uc.Eval("Length('This is a test')"))
```

**Output:**
```
2
720
14
```

---

### Example ID: 161

**Description:** "using" (C#) and Owned (C++) for auto-releasing uCalc object

**Code:**
```pseudocode

// In C# and VB you should use "using".
// In C++ you can flag a uCalc object for
// auto-release with Owned(), or by setting
// the last parameter of the constructor to true.

uc.@IsDefault(true); // Set uc as the default uCalc object
uCalc::@DefaultInstance().DefineVariable("Value = 'Original uc object'");
wl(uCalc::@DefaultInstance().EvalStr("Value")) // Outputs: Original uc object

[NotCpp]// Use "using" so that the object is auto-released when it it goes out of scope[/NotCpp]
   NewUsing(uCalc, uCalcTemp) [cpp]// Make uCalcTemp owned so it reverts back to uc when uCalcTemp goes out of scope[/cpp]
   uCalcTemp.@IsDefault(true); // Set uCalcTemp as the default uCalc object
   uCalc::@DefaultInstance().DefineVariable("Value = 'uCalcTemp object'");
   wl(uCalc::@DefaultInstance().EvalStr("Value")) // uCalcTemp object
End Using
// uCalcTemp goes out of scope here, and the default uCalc object reverts back to uc

wl(uCalc::@DefaultInstance().EvalStr("Value")) // Original uc object

[c]{!Eval: Chr(123)}[/c][vb]If True Then[/vb]
   [cs]/*using*/[/cs] New(uCalc, uCalcSticky) // remains the default even after going out of scope
   uCalcSticky.@IsDefault(true); // Set uCalcSticky as the default uCalc object
   uCalc::@DefaultInstance().DefineVariable("Value = 'uCalcSticky object'");
   wl(uCalc::@DefaultInstance().EvalStr("Value")) // Outputs: uCalcSticky object
[c]{!Eval: Chr(125)}[/c][vb]End If[/vb]    // The uCalcSticky object itself goes out of scope here, but internally it remains the default uCalc object

wl(uCalc::@DefaultInstance().EvalStr("Value"))
```

**Output:**
```
Original uc object
uCalcTemp object
Original uc object
uCalcSticky object
uCalcSticky object
```

---

---

## Clone - ID: 555
/doc/reference/classes/ucalc/clone/

**Description:** Creates an identical, but independent, copy of the current uCalc instance, including all its defined variables, functions, and settings.

**Syntax:** Clone(bool)
**Parameters:**
makeDefault - bool [default = false] - If true, the newly created clone becomes the new default uCalc instance for the current thread.
**Return:** uCalcBase - A new, independent uCalc instance that is a complete replica of the original.
**Remarks:**

This method creates an identical, yet completely independent, copy of a `uCalc` object. The new instance inherits the entire state of the original, including all defined variables, functions, operators, and configuration settings. Once cloned, the two instances are decoupled; changes made to one will not affect the other.

This is functionally equivalent to, but more expressive than, creating a new `uCalc` instance with the original as a constructor argument. So [pseudocode]`var clone = uc.Clone();` is the same as [pseudocode]`New(uCalc, clone(uc));`.

### State Replication
A clone is a deep copy. The following state is replicated:
*   **Variables**: All user-defined variables.
*   **Functions**: All user-defined functions, including those with callbacks.
*   **Operators**: All custom operators.
*   **Error Handlers**: The entire error handler chain.
*   **Settings**: All configuration settings, such as `Format`, `DecimalSeparator`, etc.

### ⚙️ Primary Use Cases
Cloning is essential for creating isolated environments for computation.

*   **"What-If" Scenario Analysis**: Create a base configuration and then clone it multiple times to model different scenarios without affecting the original or other scenarios. This is useful in financial modeling or scientific simulations.
*   **Sandboxing**: Evaluate untrusted or experimental expressions in a cloned instance. If the clone's state is corrupted, the original instance remains intact.
*   **Multithreading**: Provide each thread with its own identical `uCalc` instance to perform calculations in parallel without state conflicts.

### 💡 Comparative Analysis
In a standard programming language, replicating a complex object's state often requires implementing a deep copy constructor or a serialization-deserialization mechanism, which can be error-prone.

*   **Without uCalc**: You would need to instantiate a new `uCalc` object and then manually re-apply all definitions and settings from the original. This is inefficient and verbose.

    ```pseudocode
    // Manual, inefficient way
    New(uCalc, uc2);
    // ... manually copy dozens of variables, functions, settings ...
    uc2.DefineVariable("rate = 0.05");
    uc2.DefineFunction("MyFunc(x) = x*2");
    // etc.
    ```

*   **With uCalc's `Clone`**: The entire state replication is handled by a single, optimized method call.

    ```pseudocode
    // Clean, efficient uCalc way
    var uc2 = uc.Clone();
    ```

This simplifies code, reduces bugs, and improves performance for scenarios requiring state duplication.

**Examples:**

### Example ID: 59

**Description:** Creating a clone of a uCalc object

**Code:**
```pseudocode

uc.DefineVariable("MyVar = 100");
uc.DefineFunction("MyFunc(x) = x + 1");

var Cloned_uc = uc.Clone();

wl(uc.EvalStr("MyVar"))
wl(uc.EvalStr("MyFunc(10)"))

wl(Cloned_uc.EvalStr("MyVar"))
wl(Cloned_uc.EvalStr("MyFunc(10)"))

Cloned_uc.Eval("MyVar = 200");
Cloned_uc.DefineFunction("OtherFunc(x) = x * 10");

wl(uc.EvalStr("MyVar"))
wl(uc.EvalStr("OtherFunc(5)"))

wl(Cloned_uc.EvalStr("MyVar"))
wl(Cloned_uc.EvalStr("OtherFunc(5)"))
```

**Output:**
```
100
11
100
11
100
Undefined identifier
200
50
```

---

### Example ID: 78

**Description:** Creating uCalc instances

**Code:**
```pseudocode
uc.DefineVariable("x = 123");

New(uCalc, uc1) // Creates a new instance
wl(uc1.EvalStr("x")) // uc1 does not have a variable named x
uc1.Release(); // Releases uc1 if it is no longer needed

var uc2 = uc.Clone(); // Creates new instance that is a clone of uc
wl(uc2.EvalStr("x")) // starts with the value of x obtained from uc
uc2.Eval("x = 456"); // Changes the value of x in uc1 but not uc
wl(uc2.EvalStr("x"))
wl(uc.EvalStr("x")) // The original x in uc remains unchanged
uc2.Release();

// Language specific - auto-releasing uCalc object
[vb]#If False[/vb]
{ // Instances pointed to by neither uCalc1 nor uCalc2 will be released when they go out of scope
   var uCalc1 = new uCalc();
   var uCalc2 = uc.Clone();
   // Call uCalc1.Release() and uCalc2.Release() explicitly if want to release them
}

{ // The instances that both uCalc1 and uCalc2 point to will be released when uCalc1 and uCalc2 go out of scope
   [cs]using var uCalc1 = new uCalc();
   using var uCalc2 = uc.Clone();[/cs]
   [cpp]uCalc uCalc1;
   uCalc uCalc2(uc.Clone());[/cpp]
   // No need for uCalc1.Release() or uCalc2.Release(), they will automatically be released
}
[vb]#End If[/vb]
```

**Output:**
```
Undefined identifier
123
456
123
```

---

---

## CreateAlias - ID: 16
/doc/reference/classes/ucalc/createalias/

**Description:** Creates a new symbol that behaves exactly like an existing symbol.

**Syntax:** CreateAlias(string, Item, bool, string)
**Parameters:**
aliasName - string - The new name to register
targetItem - Item - The symbol to alias
commandAlias - bool [default = false] - If true, creates a Define() command alias instead of an expression alias
ignore - string [default = ""] - Internal use only
**Return:** Item - Newly created alias Item
**Remarks:**

`Alias()` defines an alternate name for an existing symbol (variable, function, operator, constant, etc.). When the parser encounters the alias, it behaves as though the original symbol were used.

Aliases are lightweight and efficient because they **do not rewrite text**. Instead, the alias internally points to the existing symbol’s definition.

---

## **How Aliases Work**

When you create an alias:

- A new symbol name is registered  
- The alias receives its own **Item handle**, used only for releasing the alias  
- All operational behavior (evaluation, type, callbacks, precedence, etc.) is delegated to the **existing item**  

This makes aliases ideal for:

- Synonyms (`Sum` → `Add`)  
- Backwards compatibility (`Ln` → `Log`)  
- Domain‑specific naming (`Velocity` → `v`)  
- Localization (`Suma` → `Add`)  

---

## **Alias vs ExpressionTransformer().FromTo()**

You could simulate an alias using:

```
ExpressionTransformer.FromTo("OldName", "NewName")
```

…but this performs **text substitution**, which modifies the expression string, and is slower.

`Alias()` is superior because it does not modify text and is faster.

Use `Alias()` whenever you simply want two names to refer to the same symbol.

---

## **Overloads**

You may specify the existing symbol in two ways:

### **1. Using an Item object**
```
Alias("NewName", uc.ItemOf("OldName"))
```
This is the preferred method when:

- Multiple items share the same name (overloaded functions)  
- You want to alias a specific overload  
- You already have the Item reference  

### **2. Using a string**
```
Alias("NewName", "OldName")
```
This resolves the name using `ItemOf()`.  
If multiple items share the same name, the selection may not be obvious — use the Item overload instead.

---

## **Command Aliases**

Setting `commandAlias = true` creates an alias **only for the Define() command syntax**, not for expressions.

Example:

```
Alias("Func", "Function", commandAlias: true)
```

This allows:

```
Define("Func: f(x) = x+1")
```

…but does **not** create an expression‑level alias.

---

## **Return Value**

Returns an **Item** representing the alias.  
Call `.Release()` on this Item to remove the alias.

(Command aliases return no Item and cannot be removed.)

**Examples:**

### Example ID: 57

**Description:** Simple alias

**Code:**
```pseudocode
uc.DefineVariable("x = 10");

// Create alias: y behaves exactly like x
uc.CreateAlias("y", "x");

wl(uc.Eval("y + 5"))
```

**Output:**
```
15
```

---

### Example ID: 56

**Description:** Alias using symbol object

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar = 123");
var MyAlias = uc.CreateAlias("MyAlias", MyVar);

wl(uc.Eval("MyAlias")) // Contains same value as MyVar
uc.Eval("MyAlias = 456"); // Same as changing MyVar
wl(uc.EvalStr("MyVar")) // MyVar reflects change made in MyAlias
wl("")


// This section below shows how you can have Alias distinguish
// between different variables with the same name

uc.DefineFunction("MyFunc() = MyVar + 1");

// MyVar defined below is a new variable sharing the same name
// MyFunc() will still use the value of the original MyVar
var MyVarAlt = uc.DefineVariable("MyVar = 100");

// The function below uses the new MyVar variable
uc.DefineFunction("MyFunc2() = MyVar + 1");

wl(uc.Eval("MyFunc()"))
wl(uc.Eval("MyFunc2()"))
wl("")

uc.CreateAlias("MyAliasAlt", MyVarAlt);
uc.Eval("MyAlias = 200"); // Changes MyVar used in MyFunc()
uc.Eval("MyAliasAlt = 300"); // Changes MyVar used in MyFunc2()

wl(uc.Eval("MyFunc()"))
wl(uc.Eval("MyFunc2()"))
```

**Output:**
```
123
456

457
101

201
301
```

---

### Example ID: 58

**Description:** Creating alternative names for Define commands

**Code:**
```pseudocode
uc.CreateAlias("VariableDefinition", "Variable", true);
uc.CreateAlias("Method", "Function", true);

uc.Define("VariableDefinition: MyVar = 123");
uc.Define("Method: MyFunc(x) = x * 10");

wl(uc.Eval("MyVar"))
wl(uc.Eval("MyFunc(5)"))
```

**Output:**
```
123
50
```

---

### Example ID: 260

**Description:** Verifying alias removal and fallback behavior.

**Code:**
```pseudocode
uc.DefineVariable("a = 100");

var aliasB = uc.CreateAlias("b", "a");

wl("Before release: ", uc.EvalStr("b"))
aliasB.Release();
wl("After release: ", uc.EvalStr("b"))
```

**Output:**
```
Before release: 100
After release: Undefined identifier
```

---

---

## DataTypeOf - ID: 21
/doc/reference/classes/ucalc/datatypeof/

---

## DataTypeOf(BuiltInType) - ID: 22
/doc/reference/classes/ucalc/datatypeof/datatypeof-builtintype/

**Description:** Retrieves the DataType object associated with a specific built-in type enumeration.

**Syntax:** DataTypeOf(BuiltInType)
**Parameters:**
typeEnum - BuiltInType - The built-in type enumeration member (e.g., BuiltInType::Int32).
**Return:** DataType - The DataType object corresponding to the specified enum.
**Remarks:**

The `DataTypeOf` method retrieves the [DataType](/datatype/) object corresponding to a member of the [BuiltInType](/enums/builtintype/) enumeration.

### Instance-Specific Data Types
Every `uCalc` instance manages its own registry of data type objects. For example, `uc1.DataTypeOf(BuiltInType::Integer_32)` and `uc2.DataTypeOf(BuiltInType::Integer_32)` return two different objects. This architecture allows you to customize properties (such as display formatting or names) for a type in one parser instance without affecting others.

### Usage
Use this method when you need to:
*   Inspect properties of a standard type (e.g., `ByteSize`, `Name`).
*   Set the default data type for the engine via [DefaultDataType](/ucalc/defaultdatatype/).
*   Perform type comparisons (checking if a generic [Item](/item/) matches a specific built-in type).

If you need to retrieve a data type by its string name (e.g., "Integer"), use the string overload of this method or [ItemOf](/ucalc/itemof/).

**Examples:**

### Example ID: 2

**Description:** Getting data type object with DataTypeOf

**Code:**
```pseudocode
wl(uc.DataTypeOf(BuiltInType::Integer_8u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Integer_16u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Boolean).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::String).ToString("-1"))

wl(uc.DataTypeOf(BuiltInType::Integer_8u).@Name())
wl(uc.DataTypeOf(BuiltInType::Integer_32).@ByteSize())
```

**Output:**
```
255
65535
true
-1
int8u
4
```

---

### Example ID: 277

**Description:** Introspection and conversion using standard types

**Code:**
```pseudocode
// Inspect basic properties of built-in types
wl(uc.DataTypeOf(BuiltInType::Integer_8u).@Name())
wl(uc.DataTypeOf(BuiltInType::Integer_32).@ByteSize())

// Testing edge case conversions mentioned in development notes
// Also string conversion behavior for signed vs unsigned and complex types
wl(uc.DataTypeOf(BuiltInType::Integer_8u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Integer_16u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::String).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Boolean).ToString("-1"))
```

**Output:**
```
int8u
4
255
65535
-1
true
```

---

### Example ID: 278

**Description:** Checking variable types against BuiltInType

**Code:**
```pseudocode
// Define a variable with a specific type
uc.DefineVariable("myVar As Int16");

// Retrieve the generic Int16 type object
var typeObj = uc.DataTypeOf(BuiltInType::Integer_16);

// Check if the variable's type matches Int16
if (uc.ItemOf("myVar").@DataType().@BuiltInTypeEnum() == typeObj.@BuiltInTypeEnum())
   wl("Variable 'myVar' is an Int16.");
else
   wl("Type mismatch.");
end if
```

**Output:**
```
Variable 'myVar' is an Int16.
```

---

---

## DataTypeOf(string) - ID: 23
/doc/reference/classes/ucalc/datatypeof/datatypeof-string/

**Description:** Retrieves the DataType object associated with a specific item name, type name, or expression.

**Syntax:** DataTypeOf(string)
**Parameters:**
definition - string - A string containing a math expression, an existing item name (variable/function), or a data type name (e.g., "Int32").
**Return:** DataType - The `DataType` object corresponding to the input. Returns `DataType::Empty` if the input is invalid or cannot be resolved.
**Remarks:**

The `DataTypeOf` method is a runtime introspection tool that resolves a string input into a [DataType](topic:uCalc.DataType) object.

It handles three categories of input strings:
1.  **Expressions:** It parses the expression (without fully evaluating it) to determine the resulting return type (e.g., `"5 + 2.5"` returns the `Double` type).
2.  **Item Names:** If the string matches a defined [Variable](topic:uCalc.DefineVariable) or [Function](topic:uCalc.DefineFunction), it returns that item's declared data type.
3.  **Type Names:** If the string is a known type alias (e.g., `"Int"`, `"String"`, `"Double"`), it returns the corresponding type definition.

### Comparison
Unlike C#'s `typeof(T)` which is resolved at compile-time, or `Object.GetType()` which requires an instantiated object, `uCalc.DataTypeOf()` operates on dynamic string definitions at runtime. This allows you to check the semantic type of a user's input string before attempting to evaluate it.

### Aliases
For convenience, the string `"Int"` and `"Integer"` are treated as synonyms for `"Int32"`.

If the input cannot be resolved to a valid type, the method returns `DataType::Empty`.

**Examples:**

### Example ID: 3

**Description:** Returning the data type of an expression

**Code:**
```pseudocode
wl(uc.DataTypeOf("10 + 20 - 3").@Name())
wl(uc.DataTypeOf(" 'What type ' + 'is this?' ").@Name())
wl(uc.DataTypeOf("3 < 10").@Name())
wl(uc.DataTypeOf("5 + 7 * #i").@Name())
wl("---")

uc.DefineFunction("func(x) as string = 'Hello' * 3");
wl(uc.DataTypeOf("func").@Name())
wl(uc.DataTypeOf("Int").@Name())
wl(uc.DataTypeOf("NonExistantType").@Name()) // Empty string
wl(uc.DataTypeOf("&&").@Name())


```

**Output:**
```
double
string
bool
complex
---
string
int

bool
```

---

### Example ID: 284

**Description:** Practical: Introspecting variables and functions.

**Code:**
```pseudocode
// Define a variable and a function
uc.DefineVariable("myVar As Int16 = 55");
uc.DefineFunction("myFunc(x) = x * 10.5"); // Implicitly returns Double

// Inspect their types dynamically
var typeVar = uc.DataTypeOf("myVar");
var typeFunc = uc.DataTypeOf("myFunc");

wl("Variable Type: ", typeVar.@Name())
wl("Function Return: ", typeFunc.@Name())

// Check specific properties
if (bool(typeVar.@BuiltInTypeEnum() == BuiltInType::Integer_16))
   wl("Variable is strictly a 16-bit integer.")
end if
```

**Output:**
```
Variable Type: int16
Function Return: double
Variable is strictly a 16-bit integer.
```

---

### Example ID: 285

**Description:** Internal Test: aliases and comparison logic.

**Code:**
```pseudocode
// "Int" is a synonym for Int32
wl(uc.DataTypeOf("Int").@Name())

// Boolean logic expression returns bool type
wl(uc.DataTypeOf("3 < 10").@Name())

// String concatenation returns string
wl(uc.DataTypeOf(" 'A' + 'B' ").@Name())

// Complex number syntax
wl(uc.DataTypeOf("5 + 7 * #i").@Name())
```

**Output:**
```
int
bool
string
complex
```

---

---

## DataTypes = [DataTypesAccessor] - ID: 853
/doc/reference/classes/ucalc/datatypes-=-[datatypesaccessor]/

**Description:** Provides access to the collection of all data types registered within the uCalc instance.

**Remarks:**

# 📂 Accessing Data Types

The `DataTypes` property provides access to the collection of all [DataType](/Reference/uCalcBase/DataType/Constructor) objects registered within the current `uCalc` instance. It is the primary tool for runtime introspection of the engine's type system.

This collection includes all built-in types (like `Double`, `Int32`, `String`) as well as any custom data types you have defined using the [Define](/Reference/uCalcBase/uCalc/Define) method.

## ⚙️ Usage

The returned [DataTypesAccessor](/Reference/uCalcBase/DataTypesAccessor) object behaves like a standard collection, allowing you to:
*   Iterate through all data types using a `foreach` loop.
*   Access a specific data type by its index.
*   Get the total number of defined types.

This is invaluable for building dynamic tools on top of uCalc, such as:
*   **Debuggers and Inspectors**: Programmatically list all available types and their properties.
*   **Dynamic UI**: Populate a dropdown menu with a list of valid types for a variable definition.
*   **Code Generators**: Write tools that can understand the uCalc type system to generate host-language code.

---
## ✨ Why uCalc? (Comparative Analysis)

*   **vs. Native Reflection (C# `typeof`, C++ RTTI)**: Native reflection systems inspect the types available in the entire compiled application or assembly. `DataTypes` is more focused and safer; it operates only within the sandboxed context of a specific [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance. It reveals the types known to the *parser*, not the entire host application. This makes it a tailored, lightweight introspection mechanism for the domain of expression evaluation.

**Examples:**

### Example ID: 801

**Description:** Lists the names of all standard data types registered in the current uCalc instance.

**Code:**
```pseudocode
foreach(var Item in uc.@DataTypes())
   wl(Item.@Name())
end foreach
```

**Output:**
```
anytype
bool
bool
int8u
complex
double
single
int
int16
int16u
int
int32u
int64
int64u
int8
int8u
int
omnitype
pointer
sametypeas
single
size_t
string
void
```

---

---

## DefaultClear - ID: 569
/doc/reference/classes/ucalc/defaultclear/

**Description:** Resets the default instance stack, restoring the original default instance to its initial state.
[Static = true]
**Syntax:** DefaultClear()
**Return:** void - No return value.
**Remarks:**

# 🧹 Resetting the Global uCalc State

The static [pseudocode]`uCalc.DefaultClear()` method provides a powerful way to reset the global uCalc environment. It unwinds the default instance stack and restores the original, built-in default instance to its pristine, startup condition.

## ⚙️ How the Default Instance Stack Works

uCalc maintains a stack of "default" instances. This allows different parts of an application to temporarily set their own `uCalc` instance as the active default without losing the previous one. This behavior is LIFO (Last-In, First-Out).

1.  **Initial State**: At startup, there is one built-in default instance on the stack. You can access it via [pseudocode]`uCalc.GetDefaultInstance()`.
2.  **Pushing a New Default**: When you call [pseudocode]`myInstance.IsDefault(true)`, `myInstance` is pushed onto the top of the stack. It becomes the new active default returned by [pseudocode]`uCalc.GetDefaultInstance()`.
3.  **Popping an Instance**: When an instance that is on the stack is disposed of, or if you call [pseudocode]`myInstance.IsDefault(false)`, it is popped from the stack, and the previous instance becomes the active default again.
4.  **Clearing the Stack**: [pseudocode]`uCalc.DefaultClear()` removes *all* instances from the stack except for the original one. It then resets that original instance, clearing all user-defined variables, functions, and other settings.

## 🆚 Comparative Analysis: Global State Management

### The Traditional Approach (e.g., C# / C++)

In a standard application, managing a global or shared "calculator" object is often done using a Singleton pattern or a simple static class.

```csharp
// C# Singleton Example
public sealed class GlobalCalculator
{
    private static readonly GlobalCalculator instance = new GlobalCalculator();
    private GlobalCalculator() { /* setup */ }
    public static GlobalCalculator Instance { get { return instance; } }
    
    public double Evaluate(string expression) { /* ... */ }
    public void Reset() { /* ... */ }
}

// Usage
GlobalCalculator.Instance.Evaluate("1+1");
```

While functional, this approach has drawbacks:
*   **Rigidity**: There is only one global instance. If different components need different settings (e.g., custom functions, different number precision), they must manually configure and restore the single instance, which is error-prone.
*   **State Conflicts**: Component A might change a setting that Component B relies on, leading to unexpected behavior.
*   **Testing**: Tightly coupling to a global static instance makes unit testing difficult.

### The uCalc Advantage

uCalc's default instance stack provides a more flexible and robust solution. It behaves like a managed, scoped global context.

*   **Scoped Overrides**: A component can push its own configured `uCalc` instance onto the stack, perform its work, and then pop it off, automatically restoring the previous context. This prevents state conflicts.
*   **Centralized Reset**: The [pseudocode]`uCalc.DefaultClear()` method acts as a global "panic button." It's invaluable in scenarios like:
    *   Tear-down logic in unit tests to ensure a clean state for every test run.
    *   An "application reset" feature for end-users.
    *   Recovering from an error state where the default stack might be corrupted.

In essence, uCalc provides a structured mechanism for managing a shared resource, avoiding the common pitfalls of global static objects.

**Examples:**

### Example ID: 61

**Description:** Setting default uCalc instance with uCalc.IsDefault(); also clearing all uCalc instances from default list

**Code:**
```pseudocode
uCalc::@DefaultInstance().DefineVariable("val = 'original default'");
wl(uCalc::@DefaultInstance().EvalStr("val"))

uc.DefineVariable("val = 'uc'");
uc.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("val"))

New(uCalc, ucB)
ucB.DefineVariable("val = 'ucB'");
ucB.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("val"))

New(uCalc, ucC)
ucC.DefineVariable("val = 'ucC'");
ucC.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("val"))

uCalc::DefaultClear();

// The original unnamed default instance is reset so user variable val no longer exists
wl(uCalc::@DefaultInstance().EvalStr("val"))

// The other instances are removed from Default list but remain active
wl(uc.EvalStr("val"))
wl(ucB.EvalStr("val"))
wl(ucC.EvalStr("val"))
```

**Output:**
```
original default
uc
ucB
ucC
Undefined identifier
uc
ucB
ucC
```

---

---

## DefaultCount = [int] - ID: 567
/doc/reference/classes/ucalc/defaultcount-=-[int]/

**Description:** Gets the number of uCalc instances currently on the default instance stack.
[Static = true]
**Remarks:**

This static property returns the current depth of the default instance stack. This stack manages which `uCalc` instance is returned by the static `uCalc.GetDefaultInstance()` method.

### ⚙️ How the Default Instance Stack Works

uCalc maintains a LIFO (Last-In, First-Out) stack of default instances. This allows different parts of an application to temporarily set their own `uCalc` instance as the active default without losing the previous context.

*   **Pushing**: Calling [pseudocode]`myInstance.IsDefault(true)` pushes `myInstance` onto the top of the stack, making it the new active default.
*   **Popping**: An instance is automatically popped from the stack when it is disposed or garbage collected. This makes the previously pushed instance the active default again.
*   **Clearing**: The [pseudocode]`uCalc.DefaultClear()` method removes all instances from the stack except for the original, root instance.

### 💡 Practical Applications

This mechanism is particularly useful in modular applications. For example, a plugin or a UI component can create and configure its own `uCalc` instance and temporarily make it the default while it performs calculations. Once the component is done (or disposed), the application's original default `uCalc` instance is automatically restored.

### ⚠️ Important Behavior

The default instance stack is never empty. It is initialized with a single root instance when the application starts. If all instances are cleared via [pseudocode]`uCalc.DefaultClear()`, the stack is reset to this single root instance. Therefore, `DefaultCount` will always return a value of at least `1`.

**Examples:**

### Example ID: 62

**Description:** Number of uCalc instances on the default uCalc instance list

**Code:**
```pseudocode
wl(uCalc::@DefaultCount())

uc.@IsDefault(true);
wl(uCalc::@DefaultCount())

New(uCalc, ucB)
ucB.@IsDefault(true);
wl(uCalc::@DefaultCount())

New(uCalc, ucC)
ucC.@IsDefault(true);
wl(uCalc::@DefaultCount())

uCalc::DefaultClear();
wl(uCalc::@DefaultCount())
```

**Output:**
```
1
2
3
4
1
```

---

### Example ID: 270

**Description:** Shows the initial count of default instances upon application startup.

**Code:**
```pseudocode
// By default, a single uCalc instance is always available on the stack.
wl("Initial default instance count: ", uCalc::@DefaultCount())
```

**Output:**
```
Initial default instance count: 1
```

---

### Example ID: 271

**Description:** Manage separate parser contexts for different application modules.

**Code:**
```pseudocode
// --- Main Application Context ---
// Starting with the 'uc' object as the initial default.
uCalc::@DefaultInstance().DefineConstant("PI = 3.14159");
wl("Initial Count: ", uCalc::@DefaultCount())

// --- A Plugin needs a temporary, isolated context ---
NewUsing(uCalc, moduleCalc)
moduleCalc.@IsDefault(true); // Push the new instance onto the stack.
wl("Count after module pushes new default: ", uCalc::@DefaultCount())

// The module's context is now active.
// uCalc::DefaultInstance() would now return 'moduleCalc'.
End Using

// When 'moduleCalc' goes out of scope, it's destroyed and automatically
// removed from the stack, restoring the previous default.

wl("Count after module instance is disposed: ", uCalc::@DefaultCount())

// Verify the original default instance is active again.
var result = uCalc::@DefaultInstance().EvalStr("PI");
wl("Original context restored. PI = ", result)
```

**Output:**
```
Initial Count: 1
Count after module pushes new default: 2
Count after module instance is disposed: 1
Original context restored. PI = 3.14159
```

---

### Example ID: 272

**Description:** Internal Test: Verify stack count during creation, stacking, and clearing.

**Code:**
```pseudocode
wl("Initial: ", uCalc::@DefaultCount())

// The implicit 'uc' is the first default. Pushing it again adds to the stack.
uc.@IsDefault(true);
wl("After pushing 'uc' again: ", uCalc::@DefaultCount())

New(uCalc, ucB)
ucB.@IsDefault(true);
wl("After pushing ucB: ", uCalc::@DefaultCount())

New(uCalc, ucC)
ucC.@IsDefault(true);
wl("After pushing ucC: ", uCalc::@DefaultCount())

// Clear all user-defined defaults, leaving only the mandatory root instance.
uCalc::DefaultClear();
wl("After Clear: ", uCalc::@DefaultCount())
```

**Output:**
```
Initial: 1
After pushing 'uc' again: 2
After pushing ucB: 3
After pushing ucC: 4
After Clear: 1
```

---

### Example ID: 273

**Description:** Inspecting the stack depth as new defaults are added and cleared

**Code:**
```pseudocode
// Check initial state (Root instance only)
wl(uCalc::@DefaultCount()) 

// Push the current 'uc' instance onto the stack
uc.@IsDefault(true);
wl(uCalc::@DefaultCount()) 

// Create a new instance and push it
New(uCalc, ucB)
ucB.@IsDefault(true);
wl(uCalc::@DefaultCount())

// Create another instance and push it
New(uCalc, ucC)
ucC.@IsDefault(true);
wl(uCalc::@DefaultCount()) 

// Clear all custom defaults, reverting to the root instance
uCalc::DefaultClear();
wl(uCalc::@DefaultCount())
```

**Output:**
```
1
2
3
4
1
```

---

---

## DefaultDataType = [DataType] - ID: 28
/doc/reference/classes/ucalc/defaultdatatype-=-[datatype]/

**Description:** Gets or sets the default data type used for implicit typing during definitions and evaluation.

**Remarks:**

The `DefaultDataType` property determines the fallback data type used by the uCalc engine when a type is not explicitly specified or cannot be inferred from context.

### Default Behavior
At startup, the default data type is **Double** (64-bit floating point). This means that generic variable definitions and math operations default to double-precision floating-point arithmetic.

### Getter / Setter Pattern
*   **Get:** Call this method without arguments to retrieve the current default type object.
*   **Set:** Pass a [DataType](/classes/datatype/) object, a [BuiltInType](/enums/builtintype/) enum member, or a type name string to set a new default. The method returns the newly set type.

### Impact on Operations
Changing the default data type affects the following areas:

1.  **Implicit Variable Definition:** Variables defined without an `As Type` clause or an initialization expression will assume this type.
2.  **Function Signatures:** Function parameters and return values defined without explicit types will assume this type.
3.  **Evaluation Output:** 
    *   [Eval](/classes/ucalc/eval/): Returns `double`. If the default type is set to something else (e.g., Integer), the result is converted to that type internally, then cast back to `double` for the return value.
    *   [EvalStr](/classes/ucalc/evalstr/): Converts the result to the default type before formatting it as a string.

### Shortcuts
While the method signature expects a `DataType` object, uCalc provides internal overloads allowing you to pass:
*   **Enum:** `uc.DefaultDataType(BuiltInType::Integer_32)`
*   **String:** `uc.DefaultDataType("Int32")`

These are equivalent to calling `uc.DefaultDataType(uc.DataTypeOf("Int32"))`.

### Comparative Analysis
In statically typed languages like C# (`var`) or C++ (`auto`), types are inferred from the initialization value (e.g., `var x = 5` implies `int`). If no initialization exists, code usually fails to compile.

uCalc is more dynamic; if a user defines `Variable: x` without initialization, uCalc must choose a type to allocate memory. `DefaultDataType` controls this choice. This is similar to VB's `Option Strict Off` where untyped variables might default to `Object`, except uCalc defaults to `Double` (or your custom setting) for mathematical efficiency.

**Examples:**

### Example ID: 4

**Description:** Setting/retrieving default data type

**Code:**
```pseudocode
// Check default data type
wl(uc.@DefaultDataType().@Name())

// This examples shows setting the default data type in 3
// different ways: by BuiltInType enum, DataType ojbect,
// or data type by name (string)

// Change default default data type
uc.@DefaultDataType(uc.DataTypeOf(BuiltInType::Integer_16));
wl(uc.@DefaultDataType().@Name())

// Test new default (returns integers instead of double)

uc.DefineFunction("ff(x, y) = (x + y)/3");
// same as ff(x As int16, y As int16) As int16 = ...

uc.DefineFunction("gg(x) = x*100");
// same as gg(x As int16) As int16 = ...

wl(uc.Eval("ff(4, 12)"))
wl(uc.Eval("gg(6.1)"))

uc.SetDefaultDataType("Single");
wl(uc.@DefaultDataType().@Name())

// Change back to original default (double)
uc.SetDefaultDataType(BuiltInType::Float_Double);

// Verify that default is now double
wl(uc.@DefaultDataType().@Name())
```

**Output:**
```
double
int16
5
600
single
double
```

---

### Example ID: 4

**Description:** Setting/retrieving default data type

**Code:**
```pseudocode
// Check default data type
wl(uc.@DefaultDataType().@Name())

// This examples shows setting the default data type in 3
// different ways: by BuiltInType enum, DataType ojbect,
// or data type by name (string)

// Change default default data type
uc.@DefaultDataType(uc.DataTypeOf(BuiltInType::Integer_16));
wl(uc.@DefaultDataType().@Name())

// Test new default (returns integers instead of double)

uc.DefineFunction("ff(x, y) = (x + y)/3");
// same as ff(x As int16, y As int16) As int16 = ...

uc.DefineFunction("gg(x) = x*100");
// same as gg(x As int16) As int16 = ...

wl(uc.Eval("ff(4, 12)"))
wl(uc.Eval("gg(6.1)"))

uc.SetDefaultDataType("Single");
wl(uc.@DefaultDataType().@Name())

// Change back to original default (double)
uc.SetDefaultDataType(BuiltInType::Float_Double);

// Verify that default is now double
wl(uc.@DefaultDataType().@Name())
```

**Output:**
```
double
int16
5
600
single
double
```

---

### Example ID: 274

**Description:** Quick Start: Getting and Setting the Default Type

**Code:**
```pseudocode
// 1. Check startup default (usually Double)
wl("Start: ", uc.@DefaultDataType().@Name())

// 2. Change default to 32-bit Integer
uc.SetDefaultDataType(BuiltInType::Integer_32);
wl("New: ", uc.@DefaultDataType().@Name())

// 3. Reset to Double using string shortcut
uc.SetDefaultDataType("Double");
wl("Reset: ", uc.@DefaultDataType().@Name())

```

**Output:**
```
Start: double
New: int
Reset: double
```

---

### Example ID: 276

**Description:** Internal Test: Default Type Scope and Isolation

**Code:**
```pseudocode
// Create a separate instance to verify isolation
New(uCalc, uc2)

// Set main instance to String
uc.SetDefaultDataType("String");

// Set second instance to Int32
uc2.SetDefaultDataType("Int32");

wl("uc1 Default: ", uc.@DefaultDataType().@Name())
wl("uc2 Default: ", uc2.@DefaultDataType().@Name())

uc2.DefineFunction("Add(a, b) = a + b");
wl("Numeric Add: ", uc2.EvalStr("Add(5, 5)"))

// Check Eval behavior with String default
// "5" + "5" should be string concatenation "55"
uc.DefineFunction("Add(a, b) = a + b");
wl("String Add: ", uc.EvalStr("Add(5, 5)"))
```

**Output:**
```
uc1 Default: string
uc2 Default: int
Numeric Add: 10
String Add: 55
```

---

---

## DefaultInstance = [uCalc] - ID: 25
/doc/reference/classes/ucalc/defaultinstance-=-[ucalc]/

**Description:** Gets/sets the globally accessible default uCalc instance.
[Static = true]
**Remarks:**

This static method provides access to the default `uCalc` instance, which serves as a convenient global singleton and a template for newly created instances.

### 🎯 Core Concept

Every uCalc environment has a default instance. You can access it anytime using [pseudocode]`uCalc::GetDefaultInstance()` without needing to create or track an object manually. This is useful for simple, one-off calculations or for establishing a shared configuration across different parts of an application.

### ⚙️ How It Works

1.  **Inheritance**: When a new `uCalc` instance is created (e.g., [pseudocode]`New(uCalc, uc);`), it inherits a complete copy of the settings, functions, variables, and operators from the *current* default instance. This allows you to pre-configure the default instance with a standard library of features that all subsequent instances will automatically receive.

2.  **Stack-Based Defaults**: The default instance is not a single, fixed object. Instead, uCalc manages a stack of default instances. You can promote any instance to be the new default using [pseudocode]`myInstance.IsDefault(true);`. This pushes `myInstance` onto the top of the stack. When that instance is unset ([pseudocode]`myInstance.IsDefault(false);`) or goes out of scope (if created with `using`), it is popped from the stack, and the previous instance becomes the default again. This provides a predictable, scoped approach to managing global settings.

### 💡 Why Use a Default Instance?

*   **Convenience**: For quick calculations, you don't need to instantiate a new `uCalc` object. You can directly use [pseudocode]`uCalc::GetDefaultInstance().Eval(...)`.
*   **Global Configuration**: Define custom functions, units, or variables once in a dedicated instance, set it as the default, and they become available everywhere. This avoids the need for dependency injection or passing `uCalc` objects throughout your application's call stack.
*   **Implicit Context**: Other components, like [topic:uCalc.Expression] or [topic:uCalc.String], use the default instance implicitly when no specific instance is provided in their constructors.

### ⚠️ Best Practices

While you can modify the original default instance directly, the recommended approach is to:
1.  Create and configure a new `uCalc` instance.
2.  Set this new, configured instance as the default using [pseudocode]`.IsDefault(true)`.

This practice leads to cleaner, more maintainable code by clearly separating your application's custom configuration from the initial built-in state.

### Thread Safety

The default instance stack is managed on a per-thread basis (using thread-local storage). This means that changes to the default instance in one thread will not affect the default instance in another, ensuring thread safety in multi-threaded applications.

**Examples:**

### Example ID: 60

**Description:** Using the default uCalc.GetDefaultInstance() instance

**Code:**
```pseudocode
uCalc::@DefaultInstance().DefineVariable("instance = 'original default'");

New(uCalc, ucB)
New(uCalc, ucC)
New(uCalc, ucD)

ucB.Eval("instance = 'B derived from -> ' + instance");
ucC.Eval("instance = 'C derived from -> ' + instance");
ucD.Eval("instance = 'D derived from -> ' + instance");

ucC.@IsDefault(true);

New(uCalc, ucE)
ucE.Eval("instance = 'E derived from -> ' + instance");

wl(uCalc::@DefaultInstance().EvalStr("'Default: ' + instance"))

wl(uc.EvalStr("instance")) // Note: this is not, nor was the default
wl(ucB.EvalStr("instance"))
wl(ucC.EvalStr("instance"))
wl(ucD.EvalStr("instance"))
wl(ucE.EvalStr("instance"))

// Note: Unlike this example, it is generally best to always
// create a new instance first and then set it as default
```

**Output:**
```
Default: C derived from -> original default
Undefined identifier
B derived from -> original default
C derived from -> original default
D derived from -> original default
E derived from -> C derived from -> original default
```

---

### Example ID: 61

**Description:** Setting default uCalc instance with uCalc.IsDefault(); also clearing all uCalc instances from default list

**Code:**
```pseudocode
uCalc::@DefaultInstance().DefineVariable("val = 'original default'");
wl(uCalc::@DefaultInstance().EvalStr("val"))

uc.DefineVariable("val = 'uc'");
uc.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("val"))

New(uCalc, ucB)
ucB.DefineVariable("val = 'ucB'");
ucB.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("val"))

New(uCalc, ucC)
ucC.DefineVariable("val = 'ucC'");
ucC.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("val"))

uCalc::DefaultClear();

// The original unnamed default instance is reset so user variable val no longer exists
wl(uCalc::@DefaultInstance().EvalStr("val"))

// The other instances are removed from Default list but remain active
wl(uc.EvalStr("val"))
wl(ucB.EvalStr("val"))
wl(ucC.EvalStr("val"))
```

**Output:**
```
original default
uc
ucB
ucC
Undefined identifier
uc
ucB
ucC
```

---

### Example ID: 161

**Description:** "using" (C#) and Owned (C++) for auto-releasing uCalc object

**Code:**
```pseudocode

// In C# and VB you should use "using".
// In C++ you can flag a uCalc object for
// auto-release with Owned(), or by setting
// the last parameter of the constructor to true.

uc.@IsDefault(true); // Set uc as the default uCalc object
uCalc::@DefaultInstance().DefineVariable("Value = 'Original uc object'");
wl(uCalc::@DefaultInstance().EvalStr("Value")) // Outputs: Original uc object

[NotCpp]// Use "using" so that the object is auto-released when it it goes out of scope[/NotCpp]
   NewUsing(uCalc, uCalcTemp) [cpp]// Make uCalcTemp owned so it reverts back to uc when uCalcTemp goes out of scope[/cpp]
   uCalcTemp.@IsDefault(true); // Set uCalcTemp as the default uCalc object
   uCalc::@DefaultInstance().DefineVariable("Value = 'uCalcTemp object'");
   wl(uCalc::@DefaultInstance().EvalStr("Value")) // uCalcTemp object
End Using
// uCalcTemp goes out of scope here, and the default uCalc object reverts back to uc

wl(uCalc::@DefaultInstance().EvalStr("Value")) // Original uc object

[c]{!Eval: Chr(123)}[/c][vb]If True Then[/vb]
   [cs]/*using*/[/cs] New(uCalc, uCalcSticky) // remains the default even after going out of scope
   uCalcSticky.@IsDefault(true); // Set uCalcSticky as the default uCalc object
   uCalc::@DefaultInstance().DefineVariable("Value = 'uCalcSticky object'");
   wl(uCalc::@DefaultInstance().EvalStr("Value")) // Outputs: uCalcSticky object
[c]{!Eval: Chr(125)}[/c][vb]End If[/vb]    // The uCalcSticky object itself goes out of scope here, but internally it remains the default uCalc object

wl(uCalc::@DefaultInstance().EvalStr("Value"))
```

**Output:**
```
Original uc object
uCalcTemp object
Original uc object
uCalcSticky object
uCalcSticky object
```

---

### Example ID: 269

**Description:** Internal Test: Verifies the stack-like (LIFO) behavior of default instances using a scoped object.

**Code:**
```pseudocode
// Original default instance
uCalc::@DefaultInstance().DefineVariable("id = 'Original'");
wl("Current Default ID: ", uCalc::@DefaultInstance().EvalStr("id"))

// Push a new default instance onto the stack
New(uCalc, ucA)
ucA.DefineVariable("id = 'Instance A'");
ucA.@IsDefault(true);
wl("Current Default ID: ", uCalc::@DefaultInstance().EvalStr("id"))

// The 'NewUsing' block creates a temporary, scoped default instance

   // The following instance will be auto-released at the end of the block
  NewUsing(uCalc, ucB)
  ucB.DefineVariable("id = 'Instance B (temp)'");
  ucB.@IsDefault(true); // Pushes 'ucB' onto the stack
  wl("Current Default ID: ", uCalc::@DefaultInstance().EvalStr("id"))
End Using

// 'ucB' has gone out of scope, so the default reverts to the previous one ('ucA')
wl("Current Default ID (after scope exit): ", uCalc::@DefaultInstance().EvalStr("id"))

// Manually unset 'ucA'
ucA.@IsDefault(false);
wl("Current Default ID (after unset): ", uCalc::@DefaultInstance().EvalStr("id"))
```

**Output:**
```
Current Default ID: Original
Current Default ID: Instance A
Current Default ID: Instance B (temp)
Current Default ID (after scope exit): Instance A
Current Default ID (after unset): Original
```

---

### Example ID: 271

**Description:** Manage separate parser contexts for different application modules.

**Code:**
```pseudocode
// --- Main Application Context ---
// Starting with the 'uc' object as the initial default.
uCalc::@DefaultInstance().DefineConstant("PI = 3.14159");
wl("Initial Count: ", uCalc::@DefaultCount())

// --- A Plugin needs a temporary, isolated context ---
NewUsing(uCalc, moduleCalc)
moduleCalc.@IsDefault(true); // Push the new instance onto the stack.
wl("Count after module pushes new default: ", uCalc::@DefaultCount())

// The module's context is now active.
// uCalc::DefaultInstance() would now return 'moduleCalc'.
End Using

// When 'moduleCalc' goes out of scope, it's destroyed and automatically
// removed from the stack, restoring the previous default.

wl("Count after module instance is disposed: ", uCalc::@DefaultCount())

// Verify the original default instance is active again.
var result = uCalc::@DefaultInstance().EvalStr("PI");
wl("Original context restored. PI = ", result)
```

**Output:**
```
Initial Count: 1
Count after module pushes new default: 2
Count after module instance is disposed: 1
Original context restored. PI = 3.14159
```

---

---

## Define - ID: 33
/doc/reference/classes/ucalc/define/

**Description:** Creates functions, operators, variables, and other symbols using a single, versatile definition string.

**Syntax:** Define(string, ADDR, DataType)
**Parameters:**
definitionString - string - A string containing the definition command and syntax (e.g., "Function: f(x) = x+1").
targetAddress - ADDR [default = 0] - An optional memory address to bind a variable or function to an external value or callback.
targetType - DataType [default = Empty] - An optional data type to associate with the item, used when the type cannot be inferred from the definition string.
**Return:** Item - An [Item](/Classes/Item/) object representing the newly created symbol.
**Remarks:**

The `Define` method is the core, string-based engine for creating all uCalc symbols, such as functions, operators, variables, and data types. It parses a special definition string that specifies both the type of symbol to create and its properties.

While powerful, developers should generally prefer the specialized, type-safe methods like [DefineFunction()](/Classes/uCalc/DefineFunction/), [DefineOperator()](/Classes/uCalc/DefineOperator/), and [DefineVariable()](/Classes/uCalc/DefineVariable/). `Define` is best suited for scenarios requiring dynamic symbol creation or for enabling end-users to define symbols within an evaluated expression (e.g., `Eval("Define('Function: MyFunc(x)=x*2')")`), or with the [{@Define}](/patterns/pattern_methods/define) Transformer pattern method.

---

## ⚙️ Definition Syntax

A definition string consists of a command keyword, a colon `:`, and the definition body. Some commands can be chained using `~~` as a separator.

### Command Reference

| Command | Description | Example | 
|---|---|---|
| **Function** | Defines a function. | `"Function: f(x) = x + 5"` |
| **Operator** | Defines an operator. | `"Operator: {x} %% {y} = x * y"` |
| **Variable** | Defines a variable. | `"Variable: MyVar = 1234"` |
| **DataType** | Creates a new data type. | `"DataType: Int16 : Type_Integer_16"` |
| **Token** | Defines a parser token using regex. | `"Token: //.*"` |
| **TokenType** | Sets the token type. | `"TokenType: whitespace ~~ Token: //.*"`|
| **Lock** | Makes a symbol read-only (a constant). | `"Lock ~~ Variable: pi = 3.14"` |
| **Overwrite** | Replaces a definition, updating all dependent expressions. | `"Overwrite ~~ Function: f(x) = x + 1"` |
| **Bootstrap** | Redefines a function using its previous definition. | `"Bootstrap ~~ Function: Cos(x) = Cos(x*pi/180)"` |
| **Precedence**| Sets an operator's precedence level. | `"Precedence: 25 ~~ Operator: ..."` |
| **Associativity**| Sets operator associativity (LeftToRight or RightToLeft).| `"Associativity: RightToLeft ~~ Operator: ..."` |
| **Format** | Defines output formatting for [EvalStr()](/Classes/uCalc/EvalStr/). | `"Format: Result = 'Ans: ' + Result"` |
| **Boolean** | Configures boolean values and string representations. | `"Boolean: -1, Yes, No"` |
| **Converts...** | Defines type conversion rules (`ConvertsBetween`, `ConvertsFrom`, `ConvertsTo`). | `"ConvertsBetween: Int, Double"` |


### Function and Operator Definitions
These follow the same syntax as their dedicated methods. For details, see [DefineFunction()](/Classes/uCalc/DefineFunction/) and [DefineOperator()](/Classes/uCalc/DefineOperator/).
*   **Functions**: `Function: name(param As Type) As ReturnType = expression`
*   **Operators**: `Operator: {operand1} op_symbol {operand2} = expression`

### Shortcuts
Some commands have an alternative shortened keyword, such as `Var` for `Variable`, `Func` for `Function`, and `Op` for `Operator`. You can use `RL` in place of `RightToLeft` and `LR` in place of `LeftToRight`.

Associativity can be combined with precedence with by with the precedence numerical value followed by a `:` and followed by `RL` or `LF` (e.g., `Operator: 15:RL {ByRef x As String} = {y As String} As String`)

### Property Modifiers (`Lock`, `Overwrite`, `Bootstrap`)
These commands precede another definition, separated by `~~`, to alter its behavior.

*   [pseudocode]`uc.Define("Lock ~~ Variable: PI = 3.14159");` is equivalent to calling [DefineConstant()](/Classes/uCalc/DefineConstant/).
*   **`Overwrite`** is essential for spreadsheet-like applications where changing one cell's formula must automatically update all cells that depend on it.
*   **`Bootstrap`** allows you to wrap an existing function without causing infinite recursion. The function call on the right side of the `=` refers to the *old* implementation.

### Token Definitions
`Define` can add or modify parser tokens recognized by [Parse()](/Classes/uCalc/Parse/).

```pseudocode
// Define C-style line comments as whitespace
uc.Define("TokenType: Whitespace ~~ Token: //.* ");
// Now, expressions with comments will parse correctly
wl(uc.Eval("10 + 5 // This is ignored"));
```
For more control, use [ExpressionTokens()](/Classes/uCalc/ExpressionTokens/).

---

## Comparative Analysis: `Define` vs. Specialized Methods

| Aspect | `uc.Define("Function: f(x)=x+1")` | `uc.DefineFunction("f(x)=x+1")` |
|---|---|---|
| **Type Safety** | 🔴 Low. Typos in `"Function: ..."` are runtime errors. | 🟢 High. The method call is checked by the compiler. |
| **Clarity** | 🟡 Medium. The intent is inside a string. | 🟢 High. The method name clearly states the intent. |
| **Flexibility** | 🟢 High. Can combine multiple commands in one string. | 🟡 Medium. Parameters control behavior, which is less compact but clearer. |
| **Use Case** | Dynamic/scripted definitions, end-user input. | Direct API usage by developers. |

**Conclusion**: Always prefer the specialized methods (`DefineFunction`, `DefineVariable`, etc.) in your application code. Use `Define` only when you need to construct definitions dynamically at runtime.

**Examples:**

### Example ID: 293

**Description:** Defining a simple variable and function.

**Code:**
```pseudocode
// Define a variable and a function using the core Define method
uc.Define("Variable: my_var = 100");
uc.Define("Function: square(x) = x * x");

wl(uc.Eval("my_var * square(5)"))
```

**Output:**
```
2500
```

---

### Example ID: 1380

**Description:** A practical example simulating a small spreadsheet with interdependent cells.

**Code:**
```pseudocode
// Define interdependent 'cells' using the Overwrite command.
uc.Define("Overwrite ~~ Function: A1() = 10");
uc.Define("Overwrite ~~ Function: B1() = A1() * 2");
uc.Define("Overwrite ~~ Function: C1() = A1() + B1()");

wl("Initial C1: ", uc.Eval("C1()")) // Should be 10 + (10 * 2) = 30

// Now, overwrite the source cell A1. All dependent cells should automatically update.
uc.Define("Overwrite ~~ Function: A1() = 50");

wl("Updated B1: ", uc.Eval("B1()")) // Should now be 50 * 2 = 100
wl("Updated C1: ", uc.Eval("C1()")) // Should now be 50 + 100 = 150
```

**Output:**
```
Initial C1: 30
Updated B1: 100
Updated C1: 150
```

---

### Example ID: 295

**Description:** Internal Test: Verifying 'Overwrite' for interdependent definitions in a spreadsheet simulation.

**Code:**
```pseudocode
// Define interdependent 'cells' using the Overwrite command.
uc.Define("Overwrite ~~ Function: A1() = 10");
uc.Define("Overwrite ~~ Function: B1() = A1() * 2");
uc.Define("Overwrite ~~ Function: C1() = A1() + B1()");

wl("Initial C1: ", uc.Eval("C1()")) // Should be 10 + (10 * 2) = 30

// Now, overwrite the source cell A1. All dependent cells should automatically update.
uc.Define("Overwrite ~~ Function: A1() = 50");

wl("Updated B1: ", uc.Eval("B1()")) // Should now be 50 * 2 = 100
wl("Updated C1: ", uc.Eval("C1()")) // Should now be 50 + 100 = 150
```

**Output:**
```
Initial C1: 30
Updated B1: 100
Updated C1: 150
```

---

### Example ID: 6

**Description:** How to define a constant, variable, operator, function, output format, and token with Define()

**Code:**
```pseudocode
wl("------ Basic examples -------")
uc.Define("Function: f(x, y) = x + y");
uc.Define("Operator: {x} %% {y} = x * y");
uc.Define("Variable: MyVar = 123");

wl(uc.Eval("f(5, 10)"))
wl(uc.Eval("5 %% 10"))
wl(uc.Eval("MyVar * 100"))

// End users can also call Define()
wl("------ End user definition -------")
uc.Eval("Define('Function: ff(x) = x * 1000')");
wl(uc.Eval("ff(987)"))

wl("------ Boolean format -------")
wl(uc.EvalStr("1 < 2"))
wl(uc.EvalStr("1 > 2"))
wl(uc.EvalStr("Int(1 < 2)"))
wl(uc.EvalStr("(True Or False) And (True And False)"))
uc.Define("Boolean: 55, TotallyTrue, CompletelyFalse");
wl(uc.EvalStr("1 < 2"))
wl(uc.EvalStr("1 > 2"))
wl(uc.EvalStr("Int(1 < 2)"))
wl(uc.EvalStr("(TotallyTrue Or CompletelyFalse) And (TotallyTrue And CompletelyFalse)"))

// Format - configures the formatting for the output given by EvalStr
wl("------ Format -------")
uc.Define("Format: Result = 'Answer: <' + Result + '>'");
uc.Define("Format: String, val = 'String Value --> ' + val");
wl(uc.EvalStr("1+2"))
wl(uc.EvalStr("'Hello ' + 'world!'"))
var Additional = uc.Define("Format: ret = 'Additional format: ' + ret");
wl(uc.EvalStr("1+2"))
uc.Define("Format: InsertAt: 0, result = 'The ' + result");
wl(uc.EvalStr("1+2"))
Additional.Release();
wl(uc.EvalStr("1+2"))
uc.FormatRemove();

// Bootstrap - builds new def on top of existing one
wl("------ Bootstrap -------")
wl(uc.EvalStr("Hex(123)")) // uses "built-in" version of Hex()
var MyHex = uc.Define("Bootstrap ~~ Function: Hex(number As Int) As String = '0x' + UCase(Hex(number))");
wl(uc.EvalStr("Hex(123)"))
MyHex.Release();
wl(uc.EvalStr("Hex(123)"))

// Overwrite - useful for spreadsheet-like functionality
wl("------ Overwrite -------")
uc.Define("Overwrite ~~ Func: SpreadsheetCell_A1() = 5");
uc.Define("Overwrite ~~ Func: SpreadsheetCell_B2() = SpreadsheetCell_A1() * 10");
uc.Define("Overwrite ~~ Func: SpreadsheetCell_C3() = SpreadsheetCell_A1() + SpreadsheetCell_B2()");
wl(uc.Eval("SpreadsheetCell_A1()"))
wl(uc.Eval("SpreadsheetCell_B2()"))
wl(uc.Eval("SpreadsheetCell_C3()"))
// SpreadsheetCell_C3() will be affected by the definition changes of SpreadsheetCell_A1() and  SpreadsheetCell_B3()
uc.Define("Overwrite ~~ Func: SpreadsheetCell_B2() = SpreadsheetCell_A1() * 100");
uc.Define("Overwrite ~~ Func: SpreadsheetCell_A1() = 25");
wl("-------")
// Note: Empty parenthesis are optional for functions with no parameters
wl(uc.Eval("SpreadsheetCell_A1"))
wl(uc.Eval("SpreadsheetCell_B2"))
wl(uc.Eval("SpreadsheetCell_C3"))

// Lock
wl("------ Lock -------")
uc.Define("Variable: xy = 555");
uc.Define("Lock ~~ Variable: pi = 3.14"); // like using DefineConstant()
wl(uc.EvalStr("xy"))
wl(uc.EvalStr("pi"))
wl(uc.EvalStr("xy = 222")) // This variable is being changed
wl(uc.EvalStr("pi = 3.14159")) // This one is locked and cannot be changed
wl(uc.EvalStr("xy")) // Returns the new value of xy
wl(uc.EvalStr("pi")) // pi did not change; returns original value
wl("-------")
uc.Define("Function: f1(x) = x + 100");
uc.Define("Lock ~~ Function: f2(x) = x + 200"); // End-user can't change f2
wl(uc.Eval("f1(5)"))
wl(uc.Eval("f2(5)"))
uc.Eval("Define('Function: f1(x) = x + 300')");
uc.Eval("Define('Function: f2(x) = x + 400')"); // This re-definition is ignored
wl(uc.Eval("f1(5)"))
wl(uc.Eval("f2(5)"))

// Tokens
wl("------ Tokens -------")
wl(uc.EvalStr("5 + 4 // This comment causes an error"));
wl(uc.EvalStr("5 + /* comment not recognized yet */ 10"))
uc.Define("TokenType: Whitespace ~~ Token: //.*"); // // C-style to end-of-line comment 
uc.Define("TokenType: Whitespace ~~ Token: /[*].*?[*]/"); // /* C-style enclosed comment */
wl(uc.EvalStr("5 + 4 // This comment will be ignored"));
wl(uc.EvalStr("5 + /* comment ignored */ 10"))

// Precedence
wl("------ Precedence -------")
uc.Define("Precedence: 1    ~~ Operator: {a As Int32} OpA {b As Int32} = a + b");
uc.Define("Precedence: 1000 ~~ Operator: {a As Int32} OpB {b As Int32} = a + b");
wl(uc.Eval("5 OpA 4 * 10"))
wl(uc.Eval("5 OpB 4 * 10"))

// Associativity
wl("------ Associativity -------")
uc.Define("Associativity: LeftToRight ~~ Operator: {x} OpX {y} = x / y");
uc.Define("Associativity: RightToLeft ~~ Operator: {x} OpY {y} = x / y");
wl(uc.Eval("3 OpX 4 OpX 5"))
wl(uc.Eval("3 OpY 4 OpY 5"))
```

**Output:**
```
------ Basic examples -------
15
50
12300
------ End user definition -------
987000
------ Boolean format -------
true
false
1
false
TotallyTrue
CompletelyFalse
55
CompletelyFalse
------ Format -------
Answer: <3>
Answer: <String Value --> Hello world!>
Answer: <Additional format: 3>
The Answer: <Additional format: 3>
The Answer: <3>
------ Bootstrap -------
7b
0x7B
7b
------ Overwrite -------
5
50
55
-------
25
2500
2525
------ Lock -------
555
3.14
222
Value cannot be assigned here
222
3.14
-------
105
205
305
205
------ Tokens -------
Undefined identifier
Undefined identifier
9
15
------ Precedence -------
45
90
------ Associativity -------
0.15
3.75
```

---

---

## DefineConstant - ID: 34
/doc/reference/classes/ucalc/defineconstant/

**Description:** Defines a named, read-only constant for use in expressions.

**Syntax:** DefineConstant(string, ADDR, DataType)
**Parameters:**
constantDefinition - string - A string defining the constant's name and value, typically in the format 'NAME = VALUE'. For example, 'PI = 3.14159'.
hostVariableAddress - ADDR [default = 0] - Optional memory address of a variable in the host application. If provided, the constant's value will be linked to this variable, allowing the host application to update it dynamically while still preventing end-user modification.
targetType - DataType [default = Empty] - Optional data type for the constant. If omitted, the type is inferred from the value, defaulting to `Double` if ambiguous.
**Return:** Item - Returns an `Item` object representing the newly defined constant, which can be used for further programmatic manipulation (e.g., renaming or deleting).
**Remarks:**

The `DefineConstant` method provides a straightforward way to create a named, read-only value within the uCalc engine. Constants are ideal for representing fixed values like mathematical constants, physical constants, or application configuration settings that should not be modified by end-user scripts.

### ✍️ Syntax & Usage

The most common usage involves passing a single string that defines both the name and the value of the constant.

```pseudocode
// Defines a constant named PI with the value 3.14159
uc.DefineConstant("PI = 3.14159");

// Defines a string constant for an application version
uc.DefineConstant("APP_VERSION = 'v1.2.0'");
```

### 🛡️ Key Behaviors

*   **Read-Only for End-Users**: Once a constant is defined, any attempt by an end-user script to assign a new value to it will result in an error. This ensures the integrity of important values.

*   **Host Application Control**: While end-users cannot modify constants, the host application retains full control. You can programmatically delete the constant using the returned `Item` object's `Release()` method and redefine it, or you can link it to a host variable by providing the `hostVariableAddress`.

*   **Syntactic Sugar**: Using `DefineConstant` is a more readable and convenient shorthand for the generic [topic: Define] method with the `Lock` modifier. The following two lines are functionally identical:

    [pseudocode]`uc.DefineConstant("PI = 3.14");`
    [pseudocode]`uc.Define("Lock ~~ Variable: PI = 3.14");`

### 🆚 Comparison with Native Languages

Unlike compile-time constants in languages like C# (`const`) or C++ (`const`, `constexpr`), uCalc constants are defined at **runtime**. This provides a significant advantage for dynamic applications.

*   **C# (`const`)**: Must be known at compile time.
*   **uCalc (`DefineConstant`)**: Can be defined at runtime, for example, by loading values from a configuration file, a database, or user input when the application starts.

This runtime flexibility allows you to expose application settings to the scripting engine in a safe, read-only manner.

### 💡 Best Practices

*   Use constants for any value that is set by the application and should not be changed by a user's formula or script.
*   Prefix constants with a consistent pattern (e.g., `CFG_`, `SYS_`) to easily distinguish them from user variables in complex expressions.
*   For more advanced scenarios involving variables, see the [topic: DefineVariable] topic.

**Examples:**

### Example ID: 286

**Description:** Quickly defines the mathematical constant PI and uses it in a simple calculation.

**Code:**
```pseudocode
uc.DefineConstant("PI = 3.14159");
wl(uc.Eval("2 * PI"))
```

**Output:**
```
6.28318
```

---

### Example ID: 287

**Description:** Defines several application-level configuration constants for use in expressions.

**Code:**
```pseudocode
uc.DefineConstant("MAX_USERS = 100");
uc.DefineConstant("API_VERSION = 'v2.1'");
uc.DefineConstant("ENABLE_LOGGING = true");

wl("Configuration Settings:")
wl("Max Users: ", uc.Eval("MAX_USERS"))
wl("API Version: ", uc.EvalStr("API_VERSION"))
wl("Logging Enabled: ", uc.EvalStr("ENABLE_LOGGING"))

// Use in a conditional expression
var(int, currentUserCount) = 99;
if (uc.EvalStr(to_string(currentUserCount) + " < MAX_USERS") == "true")
    wl("System capacity is OK.")
end if
```

**Output:**
```
Configuration Settings:
Max Users: 100
API Version: v2.1
Logging Enabled: true
System capacity is OK.
```

---

### Example ID: 288

**Description:** Internal Test: Validates that end-users cannot modify a locked constant.

**Code:**
```pseudocode
uc.DefineConstant("LOCKED_VAL = 1000");
wl("Initial value: ", uc.Eval("LOCKED_VAL"))

// 1. End-user attempts to assign a value. This should fail.
uc.Eval("LOCKED_VAL = 2000");
wl("Error after assignment attempt: ", uc.@Error().@Message())
wl("Value remains unchanged: ", uc.Eval("LOCKED_VAL"))

```

**Output:**
```
Initial value: 1000
Error after assignment attempt: Value cannot be assigned here
Value remains unchanged: 1000
```

---

### Example ID: 8

**Description:** Defining a constant

**Code:**
```pseudocode
uc.DefineVariable("MyVar = 10");
uc.DefineConstant("MyPi = 3.14");

wl(uc.Eval("MyVar"))
wl(uc.Eval("MyPi"))

uc.EvalStr("MyVar = 20"); // Attempt to change MyVar
wl(uc.@Error().@Message())

uc.EvalStr("MyPi = 25"); // Attempt to change MyPi
wl(uc.@Error().@Message())

wl(uc.EvalStr("MyVar"))
wl(uc.EvalStr("MyPi"))
```

**Output:**
```
10
3.14
No error
Value cannot be assigned here
20
3.14
```

---

---

## DefineFunction - ID: 35
/doc/reference/classes/ucalc/definefunction/

**Description:** Registers a user-defined function for use in expressions, supporting inline definitions, external callbacks, and advanced features like overloading and recursion.

**Syntax:** DefineFunction(string, OpCallback, DataType, bool, bool)
**Parameters:**
definition - string - The function signature and body, e.g., "MyFunc(x, y) = x + y".
functionAddr - OpCallback [default = 0] - The address of a native callback function that implements the function's logic. If provided, the expression body in the definition string is ignored.
returnType - DataType [default = Empty] - The return [DataType] of the function. If omitted, the type is often inferred from the expression body.
bootstrap - bool [default = false] - If true, allows the new function definition to call a pre-existing function of the same name, preventing recursion. Useful for wrapping or extending existing functions.
overwrite - bool [default = false] - If true, this definition replaces any existing function with the same signature, and automatically updates all previously parsed expressions that use it. Essential for reactive, spreadsheet-like behavior.
**Return:** Item - An [Item] object representing the newly defined function, which can be used for later modification or release.
**Remarks:**

The `DefineFunction` method is a cornerstone of uCalc, allowing you to create custom functions for use in expressions. You can define functions in two primary ways:

1.  **Inline Definition**: Provide the entire function signature and logic as a single string.
2.  **Callback Binding**: Provide a function signature and link it to a native C#, C++, or VB function in your host application.

This flexibility makes it ideal for everything from simple user-defined helpers to complex integrations with existing code.

### 📖 Function Syntax

A function definition string follows this pattern:

`FunctionName(param1, param2, ...) As ReturnType = expression`

*   **Parameters**: A comma-separated list of parameter names. You can optionally assign a data type to a parameter by following it with `As [typename]`. Parentheses `()` are required even for functions with no parameters.
*   **Return Type**: Optional. If omitted, uCalc attempts to infer it. If it can't, it uses the instance's [DefaultDataType](/reference/ucalc/defaultdatatype).
*   **Expression**: The logic to be executed when the function is called.

### ⚙️ Core Features

| Feature | Description |
| :--- | :--- |
| **Overloading** | Define multiple functions with the same name but different parameter types or counts. uCalc selects the correct one at runtime based on the arguments provided. |
| **Optional Parameters** | Specify default values for parameters, e.g., `MyFunc(x, y = 5)`. |
| **Variadic Functions** | Create functions that accept a variable number of arguments using the `...` syntax, e.g., `Average(x ...)` |
| **Recursion** | Functions can call themselves, enabling classic recursive algorithms like factorial or Fibonacci. |
| **Shadowing vs. Overwriting** | By default, a new definition *shadows* an old one; existing expressions still use the old version. Setting `overwrite: true` replaces the old definition everywhere, enabling powerful spreadsheet-like reactive updates. |
| **Bootstrapping** | Setting `bootstrap: true` lets you redefine a function by calling the *original* version within its new definition, which is perfect for extending or wrapping built-in functions without causing a recursive loop. |

### 🔗 Argument Passing Modifiers

uCalc extends standard argument passing with powerful custom modifiers that provide deep introspection and control.

| Modifier | Description |
| :--- | :--- |
| `ByVal` | (Default) Passes the evaluated result of the argument. |
| `ByRef` | Passes a reference to a variable, allowing the function to modify its value. |
| `ByHandle` | Passes the argument's underlying [Item](/reference/item) object. This allows the callback to inspect metadata like the argument's name, data type, or original expression text. |
| `ByExpr` | Passes the argument as an unevaluated [Expression](/reference/expression) object. This enables powerful lazy-evaluation and short-circuiting logic, as seen in the built-in `IIf` function. |

### 💡 Comparative Analysis

*   **vs. Compiled Languages (C#/C++)**: The primary advantage is dynamism. Functions can be defined at runtime from user input, configuration files, or database entries without requiring recompilation. This is fundamental for applications like report generators, scripting environments, and scientific modelers.

*   **vs. Other Scripting Engines (Lua, Python)**: While full scripting engines are more powerful, they are also much heavier. uCalc is a lightweight, specialized component. Its key differentiators are:
    *   **`ByExpr` and `ByHandle`**: These provide metaprogramming capabilities that are often complex or impossible to achieve in other embedded script engines.
    *   **`Overwrite` Flag**: This built-in feature for creating reactive dependencies is a unique and powerful concept that simplifies building spreadsheet-like applications, a task that would require significant manual dependency tracking in other systems.

### 📋 Retrieving Defined Functions
You can get a list of all currently defined functions using [uc.ListOfItems(ItemIs.Function)](/reference/ucalc/listofitems).

**Examples:**

### Example ID: 296

**Description:** A minimal example defining a function inline to calculate the area of a rectangle.

**Code:**
```pseudocode
uc.DefineVariable("x = 5");
uc.DefineFunction("Area(length, width) = length * width");
wl(uc.Eval("Area(4, x) + 7"))
```

**Output:**
```
27
```

---

### Example ID: 297

**Description:** Demonstrates defining a function that is implemented by a native callback in the host application.

**Code:**
```pseudocode
[head]
[callback MyAreaCallback]
  var length = cb.Arg(1);
  var width = cb.Arg(2);
  cb.Return(length * width);
[/callback]

[body]
// The signature is defined, but the logic is provided by 'MyAreaCallback'.
uc.DefineFunction("Area(x, y)", MyAreaCallback);
wl(uc.Eval("Area(3, 4)"))
```

**Output:**
```
12
```

---

### Example ID: 298

**Description:** Shows how to create overloaded functions that uCalc distinguishes based on parameter count and type.

**Code:**
```pseudocode
// Overload for two numbers
uc.DefineFunction("Combine(x, y) = x + y");

// Overload for two strings
uc.DefineFunction("Combine(x As String, y As String) As String = x + y");

// Overload for three numbers
uc.DefineFunction("Combine(x, y, z) = x + y + z");

wl("Two numbers: ", uc.EvalStr("Combine(5, 10)"))
wl("Two strings: ", uc.EvalStr("Combine('Hello, ', 'World!')"))
wl("Three numbers: ", uc.EvalStr("Combine(5, 10, 20)"))
```

**Output:**
```
Two numbers: 15
Two strings: Hello, World!
Three numbers: 35
```

---

### Example ID: 299

**Description:** Defines a recursive Factorial function using the IIf function for conditional logic.

**Code:**
```pseudocode
uc.DefineFunction("Factorial(n) = IIf(n > 1, n * Factorial(n - 1), 1)");
wl(uc.Eval("Factorial(5)"))
```

**Output:**
```
120
```

---

### Example ID: 10

**Description:** Miscellaneous end-user functions defined with DefineFunction()

**Code:**
```pseudocode
wl("---- Simple function def ----")
uc.DefineFunction("f(x) = x ^ 2 + 5");
wl(uc.Eval("f(10)"))

wl("---- Function overloading ----")
// Overloading based on parameter type or number of parameters
uc.DefineFunction("MyOverload(x As Double) = x + x");
uc.DefineFunction("MyOverload(x As String) As String = x + x");
uc.DefineFunction("MyOverload(x As String, y As String) As String = x + y");
uc.DefineFunction("MyOverload(x, y) = x + y");
wl(uc.EvalStr("MyOverload(5)"))
wl(uc.EvalStr("MyOverload('Ha')"))
wl(uc.EvalStr("MyOverload('Hello ', 'world!')"))
wl(uc.EvalStr("MyOverload(5, 10)"))

wl("---- Definition hiding/un-hiding ----")
// Shadowing (hiding) definitions
uc.DefineFunction("h(x) = x * 10");
wl(uc.Eval("h(3)"))
var hFunc = uc.DefineFunction("h(x) = x * 100"); // hides previous def
wl(uc.Eval("h(3)"))
hFunc.Release(); // Releasing this restores previous def
wl(uc.Eval("h(3)"))

wl("---- Optional parameters ----")
uc.DefineFunction("Opt(x, y = 5, z As String = 'Hello') = x + y + Length(z)");
wl(uc.Eval("Opt(10)"))
wl(uc.Eval("Opt(10, 20)"))
wl(uc.Eval("Opt(10, 20, 'Just a test 123')"))

wl("---- Recursion ----")
uc.DefineFunction("Factorial(x) = iif(x > 1, x * Factorial(x - 1), 1)");
uc.DefineFunction("Fib(n) = IIf(n < 2, n, Fib(n - 1) + Fib(n - 2))");
wl(uc.Eval("Factorial(5)"))
wl(uc.Eval("Fib(10)"))

// Bootstrap - builds new def on top of existing one
wl("------ Bootstrapping -------")
wl(uc.EvalStr("Hex(123)")) // uses "built-in" version of Hex()
[cpp]auto MyHex = uc.DefineFunction("Hex(number As Int) As String = '0x' + UCase(Hex(number))", 0, uCalc::DataType::Empty, true);[/cpp]
[cs]var MyHex = uc.DefineFunction("Hex(number As Int) As String = '0x' + UCase(Hex(number))", bootstrap: true);[/cs]
[vb]Dim MyHex = uc.DefineFunction("Hex(number As Int) As String = '0x' + UCase(Hex(number))", bootstrap:=True);[/vb]
wl(uc.EvalStr("Hex(123)"))
MyHex.Release();
wl(uc.EvalStr("Hex(123)"))

// Overwrite - useful for spreadsheet-like functionality
wl("------ Overwrite -------")
[cpp]uc.DefineFunction("SpreadsheetCell_A1() = 5", 0, uCalc::DataType::Empty, false, true);
uc.DefineFunction("SpreadsheetCell_B2() = SpreadsheetCell_A1() * 10", 0, uCalc::DataType::Empty, false, true);
uc.DefineFunction("SpreadsheetCell_C3() = SpreadsheetCell_A1() + SpreadsheetCell_B2()", 0, uCalc::DataType::Empty, false, true);[/cpp]
[cs]uc.DefineFunction("SpreadsheetCell_A1() = 5", overwrite: true);
uc.DefineFunction("SpreadsheetCell_B2() = SpreadsheetCell_A1() * 10", overwrite: true);
uc.DefineFunction("SpreadsheetCell_C3() = SpreadsheetCell_A1() + SpreadsheetCell_B2()", overwrite: true);[/cs]
[vb]uc.DefineFunction("SpreadsheetCell_A1() = 5", overwrite:=true);
uc.DefineFunction("SpreadsheetCell_B2() = SpreadsheetCell_A1() * 10", Overwrite:=true);
uc.DefineFunction("SpreadsheetCell_C3() = SpreadsheetCell_A1() + SpreadsheetCell_B2()", overwrite:=true);[/vb]
wl(uc.Eval("SpreadsheetCell_A1()"))
wl(uc.Eval("SpreadsheetCell_B2()"))
wl(uc.Eval("SpreadsheetCell_C3()"))
// SpreadsheetCell_C3() will be affected by the definition changes of SpreadsheetCell_A1() and  SpreadsheetCell_B3()
[cpp]uc.DefineFunction("SpreadsheetCell_B2() = SpreadsheetCell_A1() * 100", 0, uCalc::DataType::Empty, false, true);
uc.DefineFunction("SpreadsheetCell_A1() = 25", 0, uCalc::DataType::Empty, false, true);[/cpp]
[cs]uc.DefineFunction("SpreadsheetCell_B2() = SpreadsheetCell_A1() * 100", overwrite: true);
uc.DefineFunction("SpreadsheetCell_A1() = 25", overwrite: true);[/cs]
[vb]uc.DefineFunction("SpreadsheetCell_B2() = SpreadsheetCell_A1() * 100", overwrite:=true);
uc.DefineFunction("SpreadsheetCell_A1() = 25", overwrite:=true);[/vb]
wl("-------")
// Note: Empty parenthesis are optional for functions with no parameters
wl(uc.Eval("SpreadsheetCell_A1"))
wl(uc.Eval("SpreadsheetCell_B2"))
wl(uc.Eval("SpreadsheetCell_C3"))

// See Define() topic for more





```

**Output:**
```
---- Simple function def ----
105
---- Function overloading ----
10
HaHa
Hello world!
15
---- Definition hiding/un-hiding ----
30
300
30
---- Optional parameters ----
20
35
45
---- Recursion ----
120
55
------ Bootstrapping -------
7b
0x7B
7b
------ Overwrite -------
5
50
55
-------
25
2500
2525
```

---

### Example ID: 11

**Description:** How to define a custom function using a native callback.

**Code:**
```pseudocode
[head]
[callback MyArea]
// Retrieve the 1st and 2nd arguments passed to the function
var Length = cb.Arg(1); 
var Width = cb.Arg(2);

// Calculate the area and return the result to the uCalc engine.
// This logic pattern translates seamlessly across languages.
cb.Return(Length * Width); // Same as cb.ReturnDbl
[/callback]
[body]
uc.DefineFunction("Area(x, y)", MyArea);
wl(uc.Eval("Area(3, 4)"))
```

**Output:**
```
12
```

---

### Example ID: 12

**Description:** Defining a callback function with a variable number of arguments

**Code:**
```pseudocode
[head]
[callback MyAverage]
var(double, Total) = 0;
for(int x = 1 to cb.ArgCount())
   Total = Total + cb.Arg(x);
end for
cb.Return(Total / cb.ArgCount());
[/callback]
[body]
uc.DefineFunction("Average(x ...)", MyAverage);
wl(uc.Eval("Average(10, 3, 7, 4)"))
```

**Output:**
```
6
```

---

### Example ID: 13

**Description:** Passing arg ByHandle to retrieve meta data such as arg data type; and AnyType

**Code:**
```pseudocode
[head]
[callback DisplayArgs]
for(int x = 1 to cb.ArgCount())
   wl(cb.ArgItem(x).ValueStr() + "  Type: " + cb.ArgItem(x).@DataType().@Name())
end for
[/callback]
[body]
uc.DefineFunction("DisplayArgs(ByHandle Arg As AnyType ...)", DisplayArgs);
uc.Eval("DisplayArgs(5, 3+2*#i, 'Hello', True, False, Int16(5+4.1))");
```

**Output:**
```
5  Type: double
3+2i  Type: complex
Hello  Type: string
true  Type: bool
false  Type: bool
9  Type: int16
```

---

### Example ID: 14

**Description:** Passing arg ByExpr (delayed lazy eval) and ByHandle

**Code:**
```pseudocode
[head]
[callback MySum]
   var Total = 0.0;
   var Expr = cb.ArgExpr(1);
   var Start = cb.Arg(2);
   var Finish = cb.Arg(3);
   var Variable = cb.ArgItem(4);

   for(double x = Start to Finish)
      Variable.Value(x);
      Total += Expr.Evaluate();
   end for
   cb.Return(Total);
[/callback]
[body]
uc.DefineVariable("x");
uc.DefineFunction("Sum(ByExpr Expr, Start, Finish, ByHandle Var)", MySum);
wl(uc.Eval("Sum(x ^ 2, 1, 10, x)"))

```

**Output:**
```
385
```

---

### Example ID: 15

**Description:** Returning a string (from a callback)

**Code:**
```pseudocode
[head]
[callback TwiceStr]
   cb.ReturnStr(cb.ArgStr(1) + cb.ArgStr(1));
[/callback]
[body]
uc.DefineFunction("Twice(Txt As String) As String", TwiceStr);
wl(uc.EvalStr("Twice('Bye')"))
```

**Output:**
```
ByeBye
```

---

### Example ID: 16

**Description:** How to handle and retrieve various data types (including pointers) within a callback.

**Code:**
```pseudocode
[head]
[callback MyFunction]
   var uc = cb.@uCalc();
   wl("------ MyFunc ------")

   // Retrieve standard 32-bit and 64-bit integer arguments directly
   wl(cb.ArgInt32(1))
   wl(cb.ArgInt64(2))

   // Retrieve the value of a pointer argument by referencing its exact data type.
   wl(uc.ItemOf("Int8").@DataType().ToString(cb.ArgAddr(3)))

   // The Item object correctly identifies the type before conversion
   wl(uc.ItemOf("Int").@DataType().ToString(cb.ArgPtr(4)))
[/callback]

[callback MyFunction2]
   var uc = cb.@uCalc();
   wl("------ MyFunc2 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_8).ToString(cb.ArgPtr(1)))
[/callback]

[callback MyFunction3]
   var uc = cb.@uCalc();
   wl("------ MyFunc3 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_16).ToString(cb.ArgPtr(1)))
[/callback]
[body]
uc.DefineVariable("x As Int = 123"); // Int32
uc.DefineVariable("xPtr As Int Ptr = AddressOf(x)");
uc.DefineFunction("MyFunc(a As Int32, b As Int64, c As Byte, d As Int Ptr)", MyFunction);
uc.Eval("MyFunc(x*10, 1+1, 255, xPtr)");

uc.DefineVariable("x2 As Int8 = -123");
uc.DefineVariable("xPtr2 As Int8 Ptr = AddressOf(x2)");
uc.DefineFunction("MyFunc2(d As Int8 Ptr)", MyFunction2);
uc.Eval("MyFunc2(xPtr2)");

uc.DefineVariable("x3 As Int16 = 1234");
uc.DefineVariable("xPtr3 As Int16 Ptr = AddressOf(x3)");
uc.DefineFunction("MyFunc3(d As Int16 Ptr)", MyFunction3);
uc.Eval("MyFunc3(xPtr3)");
```

**Output:**
```
------ MyFunc ------
1230
2
-1
123
------ MyFunc2 ------
-123
------ MyFunc3 ------
1234
```

---

### Example ID: 40

**Description:** Determining properties of an expression part

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   wl("Name: ", cb.@Item().@Name())
   wl("Data type: ", cb.@Item().@DataType().@Name())
   wl("Param count: ", cb.@Item().@Count())
   w("Procedure type: ")
   if (cb.@Item().IsProperty(ItemIs::Operator))
      wl("Operator")
   else if (cb.@Item().IsProperty(ItemIs::Function))
      wl("Function")
   end if
   wl(cb.@Item().@Text())
   wl(cb.@Item().@Description())
   wl("---")
[/callback]
[body]

uc.DefineFunction("AAA() As Double", ItemCallback).@Description("Does this and that");
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).@Description("Does something else");
uc.DefineOperator("{x} CCC {y} As Int32", 0, Associativity::LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");

```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Function: AAA() As Double
Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Function: BBB(x, y, z) As String
Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Operator: {x} CCC {y} As Int32

---
```

---

### Example ID: 1296

**Description:** A quick start example showing defining a variable, a function, and evaluating an expression.

**Code:**
```pseudocode
uc.DefineVariable("x = 10");
uc.DefineFunction("DoubleThis(n) = n * 2");

wl(uc.Eval("DoubleThis(x) + 5"))
```

**Output:**
```
25
```

---

---

## DefineOperator - ID: 36
/doc/reference/classes/ucalc/defineoperator/

**Description:** Defines a custom operator to extend or modify the expression syntax at runtime.

**Syntax:** DefineOperator(string, int, Associativity, OpCallback, DataType, bool, bool)
**Parameters:**
definition - string - The operator's signature and body, e.g., `{x} op {y} = x + y`.
precedence - int - The operator's precedence level, which determines its binding strength relative to other operators.
associativity - Associativity [default = Associativity::LeftToRight] - The operator's associativity, either left-to-right or right-to-left.
callbackAddress - OpCallback [default = 0] - Optional address of a native callback function to implement the operator's logic.
returnType - DataType [default = Empty] - Optional return data type for the operator. If omitted, the type is often inferred from the expression body.
bootstrap - bool [default = false] - If true, allows redefining an operator using its previous definition, useful for extending functionality.
overwrite - bool [default = false] - If true, this definition replaces the previous definition of the same operator, affecting already-parsed expressions.
**Return:** Item - An [Item](/Classes/Item/Constructor) object representing the newly defined operator, which can be used to modify or release it later.
**Remarks:**

The `DefineOperator` method allows you to create new operators, giving you the power to define custom syntax for your expressions. This is a cornerstone feature for building Domain-Specific Languages (DSLs) within uCalc.

Operator definitions share many concepts with function definitions (see [DefineFunction](/Classes/uCalc/DefineFunction)), but this topic focuses on their unique characteristics.

## Operator Anatomy (Prefix, Infix, Postfix)

You can define three kinds of operators:

*   **Infix (Binary)**: Sits between two operands (e.g., `x + y`).
*   **Prefix (Unary)**: Comes before a single operand (e.g., `-x`).
*   **Postfix (Unary)**: Comes after a single operand (e.g., `x!`).

Operands in the definition string must be enclosed in curly braces `{}`.

```pseudocode
// Infix operator with an alphanumeric name
uc.DefineOperator("{x} Plus {y} = x + y");

// Prefix operator with a symbolic name
uc.DefineOperator("neg {x} = -x");

// Postfix operator with a symbolic name
uc.DefineOperator("{x}% = x / 100");
```

### Data type placement

To specify a data type for a parameter, add `As [type]` next to the operand within curly braces.  You can also have a return type (e.g., `{x As Int} + {y As Int} As Int = x + y`).

---

## Key Concepts

### Operator Names
Unlike functions, an operator name can be either fully alphanumeric (e.g., `Plus`, `times`) or consist entirely of non-alphanumeric symbols (e.g., `+`, `++`, `&&`, `@#%`). A mix of character types is not allowed.

### Reducible Tokens
When the parser encounters a sequence of symbols, it greedily matches the **longest defined operator**. This is known as using *reducible tokens*. For example, if you have operators for `-` (prefix and infix) and `--` (postfix), an expression like `a---b` is parsed as `a-- - b` because `a--` is the first and longest valid match.

The set of characters that can form a symbolic operator is configurable. You can inspect the current definition via `uc.ItemOf("_Token_Reducible").Regex()`.

### Precedence
Every operator requires a precedence level. This numeric value determines the order of operations. Higher numbers bind more tightly. For example, `*` has a higher precedence than `+`, so `2 + 3 * 4` is `2 + (3 * 4)`.

Rather than using arbitrary numbers, it's best practice to base new operator precedence on existing ones:

```pseudocode
// Give 'times' the same precedence as the multiplication operator '*'
var prec = uc.ItemOf("*", ItemIs::Infix).Precedence();
uc.DefineOperator("{a} times {b} = a * b", prec);

// Place a new operator between '+' and '*'
var prec_between = (uc.ItemOf("+").Precedence() + uc.ItemOf("*").Precedence()) / 2;
uc.DefineOperator("{a} custom {b} = ...", prec_between);
```

### Associativity
When operators of the same precedence appear together, associativity determines their grouping. The default is `LeftToRight`.

*   **LeftToRight**: `a - b - c` is parsed as `(a - b) - c`.
*   **RightToLeft**: `a = b = c` is parsed as `a = (b = c)`.

This is controlled by the `associativity` parameter, using the [Associativity](/Enums/Associativity) enum.

---

## Definition Shortcuts

You can embed the precedence and associativity directly into the definition string, which will override the method parameters:

```pseudocode
// Define 'MyOp' with precedence 123 and default LeftToRight associativity
uc.DefineOperator("123 {a} MyOp {b} = a + b");

// Define 'MyOp' with precedence 123 and RightToLeft (RL) associativity
uc.DefineOperator("123:RL {a} MyOp {b} = a + b");
```

---

## 💡 Comparative Analysis: uCalc vs. Native Operator Overloading

Many compiled languages like C++ and C# support *operator overloading*, which allows developers to redefine how operators work for their custom classes. However, this has key limitations:

1.  **Compile-Time Only**: You can only overload a fixed set of existing operators (`+`, `-`, `*`, `==`, etc.). You cannot invent new ones, and the definitions are baked into the compiled binary.
2.  **Fixed Precedence**: You cannot change the precedence or associativity of operators. `+` will always have lower precedence than `*`.

**uCalc's `DefineOperator` is fundamentally different and more powerful:**

*   **Runtime Definition**: Operators can be defined, redefined, or removed *dynamically at runtime*. This allows an application to adapt its syntax based on user input, configuration files, or different modes of operation.
*   **New Syntax**: You can invent entirely new operators (e.g., `within`, `matches`, `$$`) with custom precedence and associativity, enabling the creation of highly readable, domain-specific languages (DSLs) without an external compiler or pre-processor.

This makes uCalc an ideal engine for applications requiring configurable or user-extendable logic.

**Examples:**

### Example ID: 64

**Description:** Operator definitions; infix, prefix, postfix, data types, precedence

**Code:**
```pseudocode
uc.DefineOperator("{x} MyOp {y} = x + y", 0); // Infix operator with alphanumeric name
uc.DefineOperator("@@ {number} = number * 2", 0); // Prefix operator with symbolic name
uc.DefineOperator("{val} % = val / 100", 0); // Postfix operator with symbolic name
uc.DefineOperator("{a} times {b} = a * b", uc.ItemOf("*").@Precedence()); // Specifying precedence
uc.DefineOperator("{TextA As String} concat {TextB As String} As String = TextA + TextB", 0); // Specifying types

wl(uc.Eval("5 MyOp 4"))
wl(uc.Eval("@@5"))
wl(uc.Eval("5 %"))
wl(uc.Eval("3 times 5"))
wl(uc.EvalStr("'Hello' concat ' world!'"))
```

**Output:**
```
9
10
0.05
15
Hello world!
```

---

### Example ID: 66

**Description:** Operator ByRef, AnyType, SameTypeAs, Precedence, RightToLeft, callback

**Code:**
```pseudocode
[head]
[callback AssignValueA]
   cb.@uCalc().DataTypeOf(BuiltInType::Integer_64).SetScalar(cb.ArgPtr(1), cb.ArgAddr(2));
   // C++ can do it with pointers instead like the commented line below:
   // *(int64_t *)cb.ArgInt64(1) = cb.ArgInt64(2);
[/callback]
[callback AssignValueB]
   if (cb.ArgItem(1).@DataType().@BuiltInTypeEnum() == BuiltInType::String)
      cb.ArgItem(1).ValueStr(cb.ArgItem(2).ValueStr());
   else
      cb.ArgItem(1).@DataType().SetScalar(cb.ArgItem(1).ValueAddr(), cb.ArgItem(2).ValueAddr());
   end if
[/callback]
[body]

// ByRef approach (only for primitive types only, like double, int, etc., not composite types like strings)
wl("-- ByRef approach --")
uc.DefineOperator("{ByRef variable As AnyType} SetValA {value As SameTypeAs:0} As SameTypeAs:0", uc.ItemOf("=").@Precedence(), Associativity::RightToLeft, AssignValueA);
uc.DefineVariable("MyDbl As Double");
uc.DefineVariable("MyInt As Int");
uc.DefineVariable("MyStr As String");

uc.Eval("MyDbl SetValA 3.14");
uc.Eval("MyInt SetValA Int(3.14 * 10)");

wl("MyDbl: " + uc.EvalStr("MyDbl"))
wl("MyInt: " + uc.EvalStr("MyInt"))

// ByHandle approach
wl("-- ByHandle approach --")
uc.DefineOperator("{ByHandle variable As AnyType} SetValB {ByHandle val As SameTypeAs:0}", uc.ItemOf("=").@Precedence(), Associativity::RightToLeft, AssignValueB);
uc.Eval("MyDbl SetValB 123.456");
uc.Eval("MyInt SetValB Int(555.123)");
uc.Eval("MyStr SetValB 'Hello World'");

wl("MyDbl: " + uc.EvalStr("MyDbl"))
wl("MyInt: " + uc.EvalStr("MyInt"))
wl("MyStr: " + uc.EvalStr("MyStr"))

```

**Output:**
```
-- ByRef approach --
MyDbl: 3.14
MyInt: 31
-- ByHandle approach --
MyDbl: 123.456
MyInt: 555
MyStr: Hello World
```

---

---

## DefineVariable - ID: 37
/doc/reference/classes/ucalc/definevariable/

**Description:** Defines a new variable or array within the uCalc engine, with an optional initial value and data type.

**Syntax:** DefineVariable(string, ADDR, DataType)
**Parameters:**
definition - string - Text containing the variable definition, including its name, optional type, and initial value.
variableAddress - ADDR [default = 0] - Optional memory address of a variable in the host program. If provided, the uCalc variable becomes a direct proxy to the host variable.
targetType - DataType [default = Empty] - Optional data type for the variable. If omitted, the type is inferred from the initial value or defaults to the engine's `DefaultDataType`.
**Return:** Item - An `Item` object representing the newly defined variable.
**Remarks:**

`DefineVariable` is the primary method for creating variables and arrays within a uCalc instance. It uses a flexible string-based syntax that allows for defining a variable's name, data type, and initial value in a single statement. This is the counterpart to [DefineConstant](/reference/ucalc/mainclassgroup/defineconstant), with the key difference that variables can be modified at runtime.

---

# ⚙️ Syntax Breakdown
The `definition` string follows a simple pattern:

[pseudocode]`"VariableName [As DataType] [= InitialValueExpression]"`

*   **VariableName**: The name of the variable. Must follow the alphanumeric token rules, which can be inspected via [pseudocode]`uc.ItemOf("_Token_Alphanumeric").Regex()`.
*   **`As DataType`** (Optional): Explicitly assigns a data type (e.g., `Int`, `String`, `Bool`).
*   **`= InitialValueExpression`** (Optional): Assigns an initial value. The expression is evaluated, and its result becomes the variable's starting value.

If no initial value is provided, the variable is initialized to the default for its type (e.g., `0` for numbers, `""` for strings).

---

# 💡 Type System
uCalc employs a flexible type system for variables:

*   **Explicit Typing**: Use the `As` keyword to specify a type (e.g., [pseudocode]`"MyInt As Int"`).
*   **Type Inference**: If `As` is omitted but an initial value is given, uCalc infers the type (e.g., [pseudocode]`"MyStr = 'hello'"` becomes a `String`).
*   **Default Typing**: If neither a type nor an initial value is specified, the variable receives the engine's default data type, which can be managed with [DefaultDataType](/reference/ucalc/mainclassgroup/defaultdatatype).
*   **Pointer Types**: Append `Ptr` to a data type name to create a pointer variable (e.g., `Int Ptr`).

By default, variable names are not case-sensitive.

---

# 📊 Defining Arrays
You can define arrays in two ways:

1.  **Fixed-Size Declaration**: Specify the size within square brackets.
    [pseudocode]`uc.DefineVariable("MyArray[10] As Int"); // An array of 10 integers`

2.  **Initializer List**: Leave the brackets empty and provide a comma-separated list of initial values in curly braces. The size is inferred from the list.
    [pseudocode]`uc.DefineVariable("MyStrings[] = {'apple', 'banana', 'cherry'}");`

---

# 🔗 Memory Binding
A powerful feature of `DefineVariable` is its ability to bind a uCalc variable directly to a variable in your host application (C#, C++, etc.) via the `variableAddress` parameter. This creates a two-way link:

*   Changes to the host variable are immediately reflected in uCalc.
*   Changes made to the variable within a uCalc expression (e.g., `Eval("myVar = 10")`) directly modify the memory of the host variable.

This technique avoids the need for manually updating variables before each evaluation and is highly efficient. In C++, you can pass an address directly (e.g., `&myHostVar`). In C#, this typically requires pinning the object in memory using `GCHandle` within an `unsafe` context.

---

# 🆚 Comparative Analysis

### vs. Statically-Typed Languages (C#, C++)
*   **Declaration**: In C# or C++, variables are declared with compile-time type safety (`int x = 10;`). uCalc's string-based approach ([pseudocode]`"x = 10"`) is dynamic, evaluated at runtime.
*   **Flexibility**: uCalc's method is ideal for scripting, configuration files, or user-defined formulas where variable names and types are not known at compile time.
*   **Safety**: The trade-off is a lack of compile-time checking. A typo in a variable name (`"MyVarr = 10"`) will result in a runtime error, not a compiler error.

### vs. Dynamic Languages (Python, JavaScript)
*   **Syntax**: The concept is similar to dynamic languages where variables are created on first assignment. However, uCalc provides optional strong typing (`As Int`), which is more akin to TypeScript than plain JavaScript.

The unique advantage of `DefineVariable` lies in its memory binding capability, which provides a level of integration with native code that is uncommon in most high-level expression evaluators.

To see all defined variables, you can use [ListOfItems](/reference/ucalc/mainclassgroup/listofitems) with the property [ItemIs.Variable](/reference/enums/itemis).

**Examples:**

### Example ID: 305

**Description:** A minimal example defining a variable and using it in an expression.

**Code:**
```pseudocode
uc.DefineVariable("x = 10");
wl(uc.Eval("x * 5"))
```

**Output:**
```
50
```

---

### Example ID: 306

**Description:** Defines variables with explicit types, inferred types, and default types.

**Code:**
```pseudocode
// Explicit type definition
uc.DefineVariable("explicitInt As Int = 123");

// Type inferred from the initial string value
uc.DefineVariable("inferredStr = 'hello'");

// Type defaults to Double as no type or value is given
var defaultVar = uc.DefineVariable("defaultVar");

wl("explicitInt type: ", uc.ItemOf("explicitInt").@DataType().@Name())
wl("inferredStr type: ", uc.ItemOf("inferredStr").@DataType().@Name())
wl("defaultVar type: ", defaultVar.@DataType().@Name())
```

**Output:**
```
explicitInt type: int
inferredStr type: string
defaultVar type: double
```

---

### Example ID: 17

**Description:** DefineVariable examples

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var MyInt = uc.DefineVariable("MyInt As Int");
var MyStr = uc.DefineVariable("MyStr As String");
uc.DefineVariable("OtherStr = 'string type inferred'");
uc.DefineVariable("MyInt16 = Int16(100/3)"); // type inferred
uc.DefineVariable("MyBool = True"); // type inferred
uc.DefineVariable("MyComplex = 3 + 4*#i"); // type inferred

MyVar.Value(123);
MyInt.ValueInt32(456);
MyStr.ValueStr("This is a test");

wl("MyVar = " + uc.EvalStr("MyVar"))
wl("MyInt = " + uc.EvalStr("MyInt"))
wl("MyStr = " + uc.EvalStr("MyStr"))
wl("OtherStr = " + uc.EvalStr("OtherStr"))
wl("MyInt16 = " + uc.EvalStr("MyInt16"))
wl("MyBool = " + uc.EvalStr("MyBool"))
wl("MyComplex = " + uc.EvalStr("MyComplex"))
wl("---")
wl(MyVar.Value())
wl(MyInt.ValueInt32())
wl(MyStr.ValueStr())
wl("---")
wl(uc.ItemOf("MyVar").@DataType().@Name())
wl(uc.ItemOf("MyInt").@DataType().@Name())
wl(uc.ItemOf("MyStr").@DataType().@Name())
wl(uc.ItemOf("OtherStr").@DataType().@Name())
wl(uc.ItemOf("MyInt16").@DataType().@Name())
wl(uc.ItemOf("MyBool").@DataType().@Name())
wl("---")

var Expression = "x^2 * 10";
var VarX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse(Expression);

w("Expression = ")
wl(Expression)
for (int x = 1 to 10)
   VarX.Value(x); // In C++ you can skip this by passing &x to DefineVariable
   wl("x = " + VarX.ValueStr() + "  Result = " + ParsedExpr.EvaluateStr())
end for

ParsedExpr.Release();
VarX.Release();
```

**Output:**
```
MyVar = 123
MyInt = 456
MyStr = This is a test
OtherStr = string type inferred
MyInt16 = 33
MyBool = true
MyComplex = 3+4i
---
123
456
This is a test
---
double
int
string
string
int16
bool
---
Expression = x^2 * 10
x = 1  Result = 10
x = 2  Result = 40
x = 3  Result = 90
x = 4  Result = 160
x = 5  Result = 250
x = 6  Result = 360
x = 7  Result = 490
x = 8  Result = 640
x = 9  Result = 810
x = 10  Result = 1000
```

---

### Example ID: 18

**Description:** DefineVariable; using pointers

**Code:**
```pseudocode
var Int8Var = uc.DefineVariable("x As Int8 = -1");
var Int16Var = uc.DefineVariable("y As Int16 = -1");
var StrVar = uc.DefineVariable("MyStr = 'Hello there'");
wl(uc.EvalStr("x"))
wl(uc.EvalStr("y"))
wl(uc.EvalStr("MyStr"))

var xPtr = uc.DefineVariable("xPtr As Pointer"); // General pointer
var yPtr = uc.DefineVariable("yPtr As Int16u Ptr"); // pointer specific to unsigned Int16
var yPtrB = uc.DefineVariable("yPtrB As Int16 Ptr = AddressOf(y)"); // Using AddressOf
var StrPtr = uc.DefineVariable("StrPtr As String Ptr");
xPtr.ValuePtr(Int8Var.ValueAddr()); // Sets the pointer address
yPtr.ValuePtr(Int16Var.ValueAddr()); // Note: address of signed Int16 going to an unsigned Ptr
StrPtr.ValuePtr(StrVar.ValueAddr());

// Note: for the ints we are now returning unsigned values; so -1 turns into positive numbers
wl(uc.EvalStr("ValueAt(Int8u, xPtr)")) // Type required because it's defined as generar pointer
wl(uc.EvalStr("ValueAt(yPtr)")) // Type name not needed because it's defined as Int16u Ptr
wl(uc.EvalStr("ValueAt(yPtrB)"))
wl(uc.EvalStr("ValueAt(StrPtr)"))

// Iterate through uc.ItemOf(ItemIs.DataType, n).Name()
// to see data type names you can use with ValueAt

var OtherInt = uc.DefineVariable("OtherInt As Int16 = 1234");
uc.DataTypeOf(BuiltInType::Integer_16).SetScalar(Int16Var.ValueAddr(), OtherInt.ValueAddr());

wl(uc.EvalStr("OtherInt"))
wl(uc.EvalStr("ValueAt(yPtrB)"))





```

**Output:**
```
-1
-1
Hello there
255
65535
-1
Hello there
1234
1234
```

---

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

### Example ID: 67

**Description:** Arrays with DefineVariable

**Code:**
```pseudocode
var MyArray = uc.DefineVariable("MyArray[3]");
uc.DefineVariable("MyArrayStr[] = {'aa', 'bb', 'cc'}");

uc.Eval("MyArray[0] = 111; MyArray[1] = 222; MyArray[2] = 333");

wl(uc.EvalStr("MyArray[0]"))
wl(uc.EvalStr("MyArray[1]"))
wl(uc.EvalStr("MyArray[2]"))
wl(uc.EvalStr("MyArrayStr[0]"))
wl(uc.EvalStr("MyArrayStr[1]"))
wl(uc.EvalStr("MyArrayStr[2]"))
wl(MyArray.@Count())
wl(uc.ItemOf("MyArrayStr").@Count())
```

**Output:**
```
111
222
333
aa
bb
cc
3
3
```

---

### Example ID: 1460

**Description:** Using the parse-evaluate pattern for high-performance calculations in a loop with a changing variable w/ stopwatch.

**Code:**
```pseudocode
var variableX = uc.DefineVariable("x");
var userExpression = "x * 2 + 5";
var Total = 0.0;
var UpperBound = 1000000; // One million

// Parse the expression just once before the loop begins.
var parsedExpr = uc.Parse(userExpression);

[NotCpp]var stopwatch = System.Diagnostics.Stopwatch.StartNew();[/NotCpp]
for(double x = 1 to UpperBound)
   variableX.Value(x);
   Total = Total + parsedExpr.Evaluate();
end for
[NotCpp]stopwatch.Stop();
//Uncomment the following line to reveal the actual speed:
//Console.WriteLine($"Elapsed Milliseconds: {stopwatch.ElapsedMilliseconds} ms");
[/NotCpp]
w("Sum(1, ", UpperBound, ", ", userExpression, ") = ", [cpp](long long)[/cpp]Total)
```

**Output:**
```
Sum(1, 1000000, x * 2 + 5) = 1000006000000
```

---

### Example ID: 1296

**Description:** A quick start example showing defining a variable, a function, and evaluating an expression.

**Code:**
```pseudocode
uc.DefineVariable("x = 10");
uc.DefineFunction("DoubleThis(n) = n * 2");

wl(uc.Eval("DoubleThis(x) + 5"))
```

**Output:**
```
25
```

---

### Example ID: 296

**Description:** A minimal example defining a function inline to calculate the area of a rectangle.

**Code:**
```pseudocode
uc.DefineVariable("x = 5");
uc.DefineFunction("Area(length, width) = length * width");
wl(uc.Eval("Area(4, x) + 7"))
```

**Output:**
```
27
```

---

---

## Description = [string] - ID: 747
/doc/reference/classes/ucalc/description-=-[string]/

**Description:** Retrieves or assigns a user-defined text description to a uCalc object, useful for attaching metadata and for debugging.

**Remarks:**

The `Description` method provides a powerful way to attach arbitrary string metadata to most uCalc objects. This is invaluable for debugging, creating self-documenting configurations, and identifying specific components at runtime.

### ⚙️ Getter and Setter Behavior

This method is overloaded to function as both a getter and a setter:

*   **Getter**: When called with no arguments, [pseudocode]`Description()` returns the current description of the object. If no description has been set, it returns an empty string.
*   **Setter**: When called with a string argument, [pseudocode]`Description("your text")` sets the object's description. The setter supports a fluent interface, meaning it returns a reference to the object itself, allowing you to chain other method calls.

### 🎯 Supported Objects

A consistent description mechanism is available across a wide range of uCalc objects, including:
*   [uCalc](/reference/ucalc) (the main instance)
*   [Transformer](/reference/transformer)
*   `Pass`
*   `Rule`
*   [Item](/reference/item) (functions, operators, variables)
*   `Token`
*   [Tokens](/reference/tokens) (the token collection)

This consistency allows you to build robust logging and debugging tools for complex parsing and transformation tasks.

### 🤔 Why is this useful? (Comparison)

Without a built-in mechanism, developers often resort to external structures to track object metadata:

*   **External Dictionaries**: Managing a dictionary to map objects to strings can be cumbersome and lead to synchronization issues if objects are created or destroyed dynamically.
*   **Wrapper Classes**: Creating custom classes just to add a description field adds unnecessary boilerplate code.
*   **Code Comments**: Comments are static and cannot be accessed programmatically at runtime.

uCalc's integrated `Description` method avoids these issues by keeping the metadata tightly coupled with the object it describes. You can easily iterate through a collection of rules or tokens and print their intended purpose, which is especially useful when debugging why a particular input string was matched (or not matched). See the practical example below for a demonstration.

**Examples:**

### Example ID: 310

**Description:** A quick example demonstrating how to set and get a description on a variable.

**Code:**
```pseudocode
// Define a variable and chain the Description() call to set metadata
var myVar = uc.DefineVariable("x = 10").SetDescription("Stores the current iteration count.");

// Retrieve and display the description
wl("Description for 'x': ", myVar.@Description())
```

**Output:**
```
Description for 'x': Stores the current iteration count.
```

---

### Example ID: 171

**Description:** uCalc Description

**Code:**
```pseudocode
uc.@Description("This is the main uCalc object");
var t = uc.NewTransformer();
wl(t.@Tokens().@uCalc().@Description())
```

**Output:**
```
This is the main uCalc object
```

---

### Example ID: 289

**Description:** Sets and retrieves a description for the main uCalc object.

**Code:**
```pseudocode
// Assign a description to the main uCalc instance
uc.@Description("Primary evaluator for financial calculations");

// Retrieve and print the description
wl(uc.@Description())
```

**Output:**
```
Primary evaluator for financial calculations
```

---

---

## DiagMem - ID: 597
/doc/reference/classes/ucalc/diagmem/

**Description:** Provides a programmatic way to query uCalc's internal memory usage, detailing allocations for specific internal object types or the entire engine.
[Static = true]
**Syntax:** DiagMem(int, BuiltInType, DiagMemCount, DiagMemOption)
**Parameters:**
uCalcIndex - int - Memory index of the target uCalc instance, typically obtained from `uCalc.MemoryIndex()`.
target - BuiltInType - The internal class or type whose memory footprint you want to diagnose.
memCount - DiagMemCount - Selects the metric to count, such as bytes or number of elements.
memOption - DiagMemOption [default = DiagMemOption::Default] - Specifies the type of memory measurement to retrieve, such as current active memory or peak usage.
**Return:** int - Returns the requested memory metric (e.g., total bytes, number of active elements) based on the `Count` and `Option` parameters.
**Remarks:**

The `DiagMem` method offers advanced diagnostic capabilities for monitoring uCalc's internal memory footprint. While primarily intended for internal testing and development, it is invaluable for developers seeking to optimize performance, troubleshoot memory-related issues, or understand the resource consumption of complex expressions within their applications.

### Parameters Explained

*   **`uCalcIndex`**: This parameter identifies the specific uCalc engine instance whose memory you wish to diagnose. The index can be obtained by calling the [uCalc.MemoryIndex](/ucalc/memoryindex) method on any object associated with that engine instance.

*   **`Target`**: Use a member of the [uCalc.BuiltInType](/ucalc/builtintype) enumeration to specify which internal component's memory you want to inspect. Use a `Diag*` member, such as `BuiltInType::DiagParsedExpression` for parsed expression trees, `BuiltInType::DiagDataType` for internal data type definitions, or `BuiltInType::DiagAll` to get a consolidated view.

*   **`Count`**: This parameter, utilizing the [DiagMemCount](enum/DiagMemCount) enumeration, determines what metric `DiagMem` should return. You can choose to count the total `Bytes` consumed, the number of active `Elements`, or other metrics.

*   **`Option`**: This parameter, using the [DiagMemOption](/enum/diagmemoption) enumeration, refines the memory measurement. Options include `Default` (typically `Active`), `Active` (current memory usage), or `Peak` (maximum memory usage observed since the uCalc instance's creation).

###  Comparative Analysis: Why uCalc's DiagMem?

Traditional memory profiling often involves external tools like Valgrind (for C/C++), Visual Studio Diagnostic Tools, or language-specific profilers. While powerful for application-wide analysis, they may not provide granular insight into the specific internal data structures of a component like uCalc.

`DiagMem` offers a unique advantage: it is an **integrated, programmatic memory profiler specifically tailored for the uCalc engine**. Instead of interpreting complex external profiler reports, developers can directly query uCalc's internal state. This allows for:

*   **Fine-grained Component-Level Analysis**: Pinpoint memory usage for specific uCalc elements like parsed expressions, data tables, or internal type definitions.
*   **Runtime Monitoring**: Integrate memory checks directly into application logic for real-time diagnostics or dynamic resource management.
*   **Automated Testing**: Incorporate memory assertions into unit or integration tests to prevent regressions in memory efficiency.
*   **Simplified Troubleshooting**: Quickly identify if a particular type of expression or function definition is consuming excessive memory without needing to attach an external profiler.

**Examples:**

---

## Error = [ErrorInfo] - ID: 847
/doc/reference/classes/ucalc/error-=-[errorinfo]/

**Description:** ErrorInfo object with details like error location, message, etc.

**Examples:**

### Example ID: 1

**Description:** Adding an error handler callback

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Symbol: ", uc.@Error().@Symbol())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);
wl(uc.EvalStr("123+"))
wl("")

uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("5/0"))
```

**Output:**
```
An error has occurred!
Error #: 257
Error Message: Syntax error
Error Symbol: +
Error Location: 3
Error Expression: 123+
Syntax error

An error has occurred!
Error #: 8
Error Message: Division by 0
Error Symbol: 
Error Location: 0
Error Expression: 
Division by 0
```

---

### Example ID: 327

**Description:** Internal Test: Verifies that the error code is correctly cleared after a successful operation.

**Code:**
```pseudocode
// Trigger an error and check the code
uc.EvalStr("1+"); 
wl("1. Error code after failure: ", [C](int)[/C]uc.@Error().@Code()[VB].ToString("D")[/VB])

// A successful evaluation should clear the error code
uc.EvalStr("1+1");
wl("2. Error code after success: ", [C](int)[/C]uc.@Error().@Code()[VB].ToString("D")[/VB])

// Trigger a different type of error
uc.@Error().@TrapOnDivideByZero(true);
uc.EvalStr("1/0");
wl("3. Error code after new failure: ", [C](int)[/C]uc.@Error().@Code()[VB].ToString("D")[/VB])

// A successful definition should also clear the error code
uc.DefineVariable("x=5"); 
wl("4. Error code after successful definition: ", [C](int)[/C]uc.@Error().@Code()[VB].ToString("D")[/VB])
```

**Output:**
```
1. Error code after failure: 257
2. Error code after success: 0
3. Error code after new failure: 8
4. Error code after successful definition: 0
```

---

### Example ID: 326

**Description:** Creating an error handler that automatically defines variables on the fly by checking for an 'Undefined Identifier' error.

**Code:**
```pseudocode
[head]
[callback:u AutoDefineHandler]
  // Check if the error is specifically an undefined identifier
  if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
    // If so, define the missing variable and instruct uCalc to resume
    wl("Auto-defining variable: '", uc.@Error().@Symbol(), "'")
    uc.DefineVariable(uc.@Error().@Symbol());
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
  end if
[/callback]

[body]
uc.@Error().AddHandler(AutoDefineHandler);

// 'x' doesn't exist, but the handler will intercept the error and create it.
var Result = uc.EvalStr("x = 10; x * 5");
wl("Result: ", Result)
```

**Output:**
```
Auto-defining variable: 'x'
Result: 50
```

---

### Example ID: 325

**Description:** Checking the error code for a simple syntax error using a callback.

**Code:**
```pseudocode
[head]
[callback:u MyHandler]
  // Retrieve the error code as an integer for display
  var(int, code) = [C](int)[/C]uc.@Error().@Code();
  wl("Caught Error Code: ", code)
  
  // Compare the error code against the ErrorCode enum for logic
  if (uc.@Error().@Code() == ErrorCode::Syntax_Error)
     wl("This was a syntax error.")
  end if
[/callback]

[body]
// Register the error handler
uc.@Error().AddHandler(MyHandler);

// Intentionally cause a syntax error, which will trigger the handler
wl(uc.EvalStr("5 *"))
```

**Output:**
```
Caught Error Code: 257
This was a syntax error.
Syntax error
```

---

### Example ID: 318

**Description:** An internal test to confirm that ErrorExpression returns an empty string for an error triggered manually by a user function during evaluation.

**Code:**
```pseudocode
[head]
[callback MyFunc]
  // This error occurs during evaluation, not parsing.
  cb.@Error().Raise("Manual evaluation failure!");
[/callback]

[callback:u MyHandler]
  wl("Handler triggered for error: ", uc.@Error().@Message())
  wl("ErrorExpression() returned: '", uc.@Error().@Expression(), "'")
  wl("Is expression empty? ", bool(uc.@Error().@Expression() == ""))
[/callback]

[body]
uc.DefineFunction("MyFunc()", MyFunc);
uc.@Error().AddHandler(MyHandler);

// The expression 'MyFunc()' itself is valid syntactically.
wl(uc.EvalStr("MyFunc()"))
```

**Output:**
```
Handler triggered for error: Manual evaluation failure!
ErrorExpression() returned: ''
Is expression empty? True
Manual evaluation failure!
```

---

### Example ID: 321

**Description:** Capturing both parsing-stage and evaluation-stage errors to see how ErrorLocation behaves differently.

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
wl("--- Error Captured ---")
wl("Message: ", uc.@Error().@Message())
wl("Symbol: '", uc.@Error().@Symbol(), "'")
wl("Location: ", uc.@Error().@Location())
wl("Expression: '", uc.@Error().@Expression(), "'")
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);

wl("Demonstrating a PARSING error:")
uc.EvalStr("123//456");

wl("")
wl("Demonstrating an EVALUATION error:")
uc.@Error().@TrapOnDivideByZero(true);
uc.EvalStr("5/0");
```

**Output:**
```
Demonstrating a PARSING error:
--- Error Captured ---
Message: Syntax error
Symbol: '/'
Location: 3
Expression: '123//456'

Demonstrating an EVALUATION error:
--- Error Captured ---
Message: Division by 0
Symbol: ''
Location: 0
Expression: ''
```

---

### Example ID: 322

**Description:** Demonstrates getting the last error message after a failed operation.

**Code:**
```pseudocode
// Attempt to evaluate an expression with unbalanced parenthesis causing a syntax error.
uc.EvalStr("5 * (10 +");

// Check the error message from the last operation.
wl("Last error message: ", uc.@Error().@Message())
```

**Output:**
```
Last error message: Bracket delimiter error
```

---

### Example ID: 323

**Description:** Retrieves the generic message for a specific error code and compares it to the last error message.

**Code:**
```pseudocode
// Retrieve the built-in message for a specific error code, without triggering an error.
wl("Generic 'Undefined Identifier' message: ", uc.@Error().GetMessage(ErrorCode::Undefined_Identifier))

// Now, trigger a specific error by using an undefined variable.
uc.EvalStr("MyUndefinedVar + 5");

// Check the message and number for the last error that occurred.
wl("Last error message: ", uc.@Error().@Message())
wl("Last error number: ", [c](int)[/c][vb]CType([/vb]uc.@Error().@Code()[vb], Integer)[/vb])
```

**Output:**
```
Generic 'Undefined Identifier' message: Undefined identifier
Last error message: Undefined identifier
Last error number: 258
```

---

### Example ID: 324

**Description:** Internal Test: Verifies that the error state is correctly cleared after a subsequent successful operation.

**Code:**
```pseudocode
// Internal Test: Verify error state is cleared
wl("--- Testing Error State Lifecycle ---")

// 1. Trigger a division-by-zero error.
uc.@Error().@TrapOnDivideByZero(true);
uc.EvalStr("1 / 0");
wl("Message after 1/0: '", uc.@Error().@Message(), "'")
wl("Error number is not None: ", bool(uc.@Error().@Code() != ErrorCode::None))

// 2. Perform a successful operation, which should clear the previous error state.
uc.EvalStr("1 + 1");

// 3. Verify the error message and number have been reset.
wl("Message after successful op: '", uc.@Error().@Message(), "'")
wl("Error number is now None: ", bool(uc.@Error().@Code() == ErrorCode::None))
```

**Output:**
```
--- Testing Error State Lifecycle ---
Message after 1/0: 'Division by 0'
Error number is not None: True
Message after successful op: 'No error'
Error number is now None: True
```

---

### Example ID: 329

**Description:** Practical: Creates a robust error handler that automatically defines variables on-the-fly when an 'Undefined Identifier' error occurs.

**Code:**
```pseudocode
[head]
// This error handler allows you to use variables that were not
// explicitly defined previously by defining unrecognized identifiers
// as variables instead of returning an error.
[callback:u AutoVariableDef]
   if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
      uc.DefineVariable(uc.@Error().@Symbol());
      uc.@Error().@Response(ErrorHandlerResponse::Resume);
   end if
[/callback]

[body]
uc.@Error().AddHandler(AutoVariableDef);
// The handler will automatically define 'AutoTest' on first use.
wl(uc.Eval("AutoTest = 123"))
wl(uc.Eval("AutoTest * 1000"))
```

**Output:**
```
123
123000
```

---

### Example ID: 54

**Description:** Error handler to auto-define variables

**Code:**
```pseudocode
[head]
// This error handler allows you to use variables that were not
// explicitly defined previously, by defining the unrecognized identifiers
// as variables instead of returning an error
[callback:u AutoVariableDef]
   if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
      uc.DefineVariable(uc.@Error().@Symbol());
      uc.@Error().@Response(ErrorHandlerResponse::Resume);
   end if
[/callback]

[body]
uc.@Error().AddHandler(AutoVariableDef);
wl(uc.Eval("AutoTest = 123"))
wl(uc.Eval("AutoTest * 1000"))
```

**Output:**
```
123
123000
```

---

### Example ID: 405

**Description:** Internal Test: Verifies that only the division by zero flag is affected, while other floating-point exceptions like overflow remain unchanged by default.

**Code:**
```pseudocode
// Enable only the division by zero error
uc.@Error().@TrapOnDivideByZero(true);

// This should now raise a uCalc error
wl("Test 1 (Div by Zero): ", uc.EvalStr("1/0"))

// This should still return 'inf' by default, as we didn't enable overflow errors
wl("Test 2 (Overflow): ", uc.EvalStr("1e308 * 2"))

// For comparison, enable overflow errors as well
uc.@Error().@TrapOnOverflow(true);
wl("Test 3 (Overflow with error): ", uc.EvalStr("1e308 * 2"))
```

**Output:**
```
Test 1 (Div by Zero): Division by 0
Test 2 (Overflow): inf
Test 3 (Overflow with error): Floating point overflow
```

---

### Example ID: 403

**Description:** Toggling the error-raising behavior for division by zero.

**Code:**
```pseudocode
// Default behavior: returns infinity
wl("Default: ", uc.EvalStr("1/0"))

// Enable error raising
uc.@Error().@TrapOnDivideByZero(true);
wl("Error Enabled: ", uc.EvalStr("1/0"))

// Disable error raising
uc.@Error().@TrapOnDivideByZero(false);
wl("Error Disabled: ", uc.EvalStr("1/0"))
```

**Output:**
```
Default: inf
Error Enabled: Division by 0
Error Disabled: inf
```

---

### Example ID: 80

**Description:** RaiseErrorOnDivideByZero

**Code:**
```pseudocode
wl(uc.EvalStr("1/0"))
uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("1/0"))

wl(uc.EvalStr("Sqrt(-1)"))
uc.@Error().@TrapOnInvalid(true);
wl(uc.EvalStr("Sqrt(-1)"))

wl(uc.EvalStr("5*10^308"))
uc.@Error().@TrapOnOverflow(true);
wl(uc.EvalStr("5*10^308"))

wl(uc.EvalStr("10^-308/10000"))
uc.@Error().@TrapOnUnderflow(true);
wl(uc.EvalStr("10^-308/10000"))
```

**Output:**
```
inf
Division by 0
nan
Invalid operation
inf
Floating point overflow
0
Floating point underflow
```

---

### Example ID: 74

**Description:** Raising floating point errors with FloatingPointErrorsToTrap

**Code:**
```pseudocode
wl(uc.@Error().@FloatingPointErrorsToTrap())
wl(uc.EvalStr("1/0"))
wl(uc.EvalStr("0/0"))
wl(uc.EvalStr("5*10^308"))
wl(uc.EvalStr("10^-308/10000"))

wl("--- Raise Div-by-0 ---")
uc.@Error().@FloatingPointErrorsToTrap([c](int)[/c][vb]CInt([/vb]ErrorCode::FloatDivisionByZero[vb])[/vb]);
wl(uc.@Error().@FloatingPointErrorsToTrap())
wl(uc.EvalStr("1/0"))
wl(uc.EvalStr("0/0"))
wl(uc.EvalStr("5*10^308"))
wl(uc.EvalStr("10^-308/10000"))

wl("--- Raise overflow ---")
uc.@Error().@FloatingPointErrorsToTrap([c](int)[/c][vb]CInt([/vb]ErrorCode::FloatOverflow[vb])[/vb]);
wl(uc.@Error().@FloatingPointErrorsToTrap())
wl(uc.EvalStr("1/0"))
wl(uc.EvalStr("0/0"))
wl(uc.EvalStr("5*10^308"))
wl(uc.EvalStr("10^-308/10000"))

wl("--- Raise invalid & underflow ---")
uc.@Error().SetFloatingPointErrorsToTrap(ErrorCode::FloatInvalid, ErrorCode::FloatUnderflow);
wl(uc.@Error().@FloatingPointErrorsToTrap()) // ErrorCode::FloatInvalid + ErrorCode::FloatUnderflow
wl(uc.EvalStr("1/0"))
wl(uc.EvalStr("0/0"))
wl(uc.EvalStr("5*10^308"))
wl(uc.EvalStr("10^-308/10000"))
```

**Output:**
```
0
inf
nan
inf
0
--- Raise Div-by-0 ---
8
Division by 0
nan
inf
0
--- Raise overflow ---
4
Floating point overflow
nan
Floating point overflow
0
--- Raise invalid & underflow ---
18
inf
Invalid operation
inf
Floating point underflow
```

---

### Example ID: 258

**Description:** Registers a handler to log when division by zero occurs.

**Code:**
```pseudocode
[head]
[callback:u LogAndResume]
wl("Logged error: ", uc.@Error().@Message())
uc.@Error().@Response(ErrorHandlerResponse::Resume);
[/callback]

[body]
uc.@Error().@TrapOnDivideByZero(true);
uc.@Error().AddHandler(LogAndResume);

wl("Start")
var Result = uc.Eval("5/0");   // Division by zero
wl("End")
```

**Output:**
```
Start
Logged error: Division by 0
End
```

---

### Example ID: 55

**Description:** Error handler order

**Code:**
```pseudocode
[head]
[callback:u ErrorHandlerA]
wl("Handler A called")
[/callback]

[callback:u ErrorHandlerB]
wl("Handler B called")
[/callback]

[callback:u ErrorHandlerC]
wl("Handler C called")
[/callback]

[callback:u ErrorHandlerD]
wl("Handler D called")
[/callback]

[callback:u ErrorHandlerE]
wl("Handler E called")
[/callback]

[body]
uc.@Error().AddHandler(ErrorHandlerA);
uc.@Error().AddHandler(ErrorHandlerB);
uc.@Error().AddHandler(ErrorHandlerC);
uc.@Error().AddHandler(ErrorHandlerD, -1);
uc.@Error().AddHandler(ErrorHandlerE, 3);

wl(uc.EvalStr("10 / "))
```

**Output:**
```
Handler C called
Handler B called
Handler A called
Handler E called
Handler D called
Syntax error
```

---

### Example ID: 482

**Description:** A function that unconditionally raises a custom error.

**Code:**
```pseudocode
[head]
[callback:u MyHandler]
    // This handler just logs the error and aborts
    wl("Error Handler Caught: ", uc.@Error().@Message())
[/callback]
[callback MyFunc]
    // This function always fails with a custom message
    cb.@Error().Raise("Validation failed for input.");
[/callback]
[body]
uc.@Error().AddHandler(MyHandler);
uc.DefineFunction("Validate()", MyFunc);
uc.EvalStr("Validate()"); // This call will trigger the error
```

**Output:**
```
Error Handler Caught: Validation failed for input.
```

---

### Example ID: 1190

**Description:** A practical example of a proactive error handler that automatically defines undeclared variables on the fly, allowing the expression to successfully resume execution.

**Code:**
```pseudocode
[head]
// This handler automatically defines variables when they are first used.
[callback:u AutoDefineHandler]
  // Check if the error is specifically an undefined identifier
  if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
    wl("Handler: '", uc.@Error().@Symbol(), "' is undefined. Defining it now.")
    uc.DefineVariable(uc.@Error().@Symbol());
    
    // Tell the engine to resume the operation
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
  end if
[/callback]

[body]
uc.@Error().AddHandler(AutoDefineHandler);

// 'my_var' doesn't exist yet, but the handler will create it.
var result = uc.EvalStr("my_var = 100; my_var = my_var * 2");

wl("Final result: ", result)
```

**Output:**
```
Handler: 'my_var' is undefined. Defining it now.
Final result: 200
```

---

---

## Eval - ID: 46
/doc/reference/classes/ucalc/eval/

**Description:** Parses and evaluates a string expression in a single step, returning a numeric result.

**Syntax:** Eval(string)
**Parameters:**
expression - string - The string containing the mathematical, or logical expression to parse and evaluate.
**Return:** double - The double-precision floating-point result of the evaluated expression.
**Remarks:**

The `Eval` method provides a convenient one-step shortcut to parse and immediately evaluate an expression, returning its result. It is ideal for scenarios where an expression is evaluated only once and performance is not the primary concern.

### When to Use `Eval`

`Eval` is the simplest way to get a result from a string. However, it performs two operations internally: parsing and evaluation. If you need to evaluate the same expression multiple times (e.g., in a loop), it is significantly more efficient to use the two-step approach:

1.  Call [uCalc.Parse](/uCalc/Parse) once to create a compiled `Expression` object.
2.  Call [Expression.Evaluate](/Expression/Evaluate) repeatedly on that object.

This avoids the overhead of re-parsing the string on every iteration.

### ⚠️ Return Type Limitation

This function is specifically designed for expressions that yield a simple numeric result. It always returns a `double`.

*   If the expression's natural result is another numeric type (like `Int32` or `Boolean`), the value will be converted to a `double`.
*   If the expression yields a non-numeric or complex type (like a `String` or `Complex` number), the return value will be meaningless. No error is raised in this case.

For expressions that return non-numeric types or to get a string representation of any result, use the more versatile [uCalc.EvalStr](/uCalc/EvalStr) method instead.

### Supported Syntax

The expression string can contain any combination of numbers, variables, and calls to built-in or user-defined [Functions and Operators](/Functions-and-Operators).

### Comparative Analysis

*   **vs. C# `DataTable.Compute`**: A common workaround in .NET for evaluating strings is using the `Compute` method of a `DataTable`. While it works for simple arithmetic, it is far less powerful, significantly slower, and lacks the rich feature set of uCalc (custom functions, complex numbers, transformers, etc.).
*   **vs. Other Parsing Libraries (e.g., NCalc, Flee)**: Many libraries offer similar `Evaluate()` methods. uCalc's `Eval` differentiates itself by being part of a much larger, cohesive engine. The expression can leverage custom data types, operators, and transformation rules defined within the same uCalc instance, offering greater flexibility and power than single-purpose evaluation libraries.
*   **vs. `Parse` + `Evaluate`**: As mentioned, `Eval` is for convenience. The two-step process is for performance-critical applications.

**Examples:**

### Example ID: 334

**Description:** Quickly evaluates several basic mathematical and function-based expressions.

**Code:**
```pseudocode
// Eval provides a direct way to compute results from strings.
wl(uc.Eval("1+1"))
wl(uc.Eval("5*(3+9)^2"))
wl(uc.Eval("Sqrt(16) + Sin(0)"))
wl(uc.Eval("Length('This is a test')"))
```

**Output:**
```
2
720
4
14
```

---

### Example ID: 335

**Description:** Calculates simple interest by defining variables and then evaluating an expression string that uses them.

**Code:**
```pseudocode
// Define variables representing configuration or user inputs.
uc.DefineVariable("principal = 20000");
uc.DefineVariable("annual_rate = 0.0575");
uc.DefineVariable("years = 4");

// Evaluate an expression combining these variables.
var interest = uc.Eval("principal * annual_rate * years");
wl("Total Interest: ", interest)
```

**Output:**
```
Total Interest: 4600
```

---

### Example ID: 21

**Description:** Evaluating expressions

**Code:**
```pseudocode
// See EvalStr for more examples.

wl(uc.Eval("1+1"))
wl(uc.Eval("5*(3+9)^2"))
wl(uc.Eval("Length('This is a test')"))
```

**Output:**
```
2
720
14
```

---

### Example ID: 296

**Description:** A minimal example defining a function inline to calculate the area of a rectangle.

**Code:**
```pseudocode
uc.DefineVariable("x = 5");
uc.DefineFunction("Area(length, width) = length * width");
wl(uc.Eval("Area(4, x) + 7"))
```

**Output:**
```
27
```

---

### Example ID: 1296

**Description:** A quick start example showing defining a variable, a function, and evaluating an expression.

**Code:**
```pseudocode
uc.DefineVariable("x = 10");
uc.DefineFunction("DoubleThis(n) = n * 2");

wl(uc.Eval("DoubleThis(x) + 5"))
```

**Output:**
```
25
```

---

### Example ID: 297

**Description:** Demonstrates defining a function that is implemented by a native callback in the host application.

**Code:**
```pseudocode
[head]
[callback MyAreaCallback]
  var length = cb.Arg(1);
  var width = cb.Arg(2);
  cb.Return(length * width);
[/callback]

[body]
// The signature is defined, but the logic is provided by 'MyAreaCallback'.
uc.DefineFunction("Area(x, y)", MyAreaCallback);
wl(uc.Eval("Area(3, 4)"))
```

**Output:**
```
12
```

---

---

## EvalStr - ID: 47
/doc/reference/classes/ucalc/evalstr/

**Description:** Parses and evaluates an expression in a single step, returning the result of any data type as a string.

**Syntax:** EvalStr(string, bool)
**Parameters:**
expression - string - Expression to be evaluated
returnFormatted - bool [default = true] - If true, the output string is processed by any defined formatters. If false, the raw, unformatted string representation is returned.
**Return:** string - A string containing the formatted or raw result of the evaluation, or an error message if the expression is invalid.
**Remarks:**

The `EvalStr` method is a versatile, one-step function that parses and evaluates an expression, returning the result as a string. It is the most convenient way to get a display-ready result from user input, as it handles any data type and can automatically apply custom formatting.

This method is a high-level convenience wrapper around the two-step process of using [uCalc.Parse](/classes/ucalc/parse/) followed by [Expression.EvaluateStr](/classes/expression/evaluatestr/).

### 💡 Key Features

*   **Universal Type Support**: Unlike its counterpart [uCalc.Eval](/classes/ucalc/eval/), which is optimized for and returns a `double`, `EvalStr` works with any data type defined in uCalc, including `String`, `Complex`, `Boolean`, and user-defined types.
*   **Safe Error Handling**: If a syntax or evaluation error occurs (like a typo or division by zero), `EvalStr` does not throw an exception. Instead, it safely returns the error message as a string, making it ideal for processing raw user input without needing complex `try-catch` blocks.
*   **Automatic Formatting**: The result can be automatically passed through any defined output formatters, controlled by the `returnFormatted` parameter.

### `Eval` vs. `EvalStr`

| Feature | `Eval(string)` | `EvalStr(string)` |
| :--- | :--- | :--- |
| **Return Type** | `double` | `string` |
| **Supported Types** | Numeric types (or types convertible to `double`) | All data types |
| **Use Case** | Numeric calculations | General-purpose evaluation, user-facing output, non-numeric results |
| **Error Handling** | Returns `NaN` or `Infinity`; inspect with [pseudocode]`Error.@Code()` | Returns the error message as a string |

### 🎨 Output Formatting

The `returnFormatted` parameter determines whether custom format rules are applied. 

*   When `true` (default), the result is processed by formatters defined with [uCalc.Format](/classes/ucalc/format/). This is useful for consistently formatting values, such as adding currency symbols or scientific notation.
*   When `false`, the method returns the raw, default string representation of the result.

### Comparative Analysis

**vs. `eval()` in Scripting Languages (JavaScript, Python)**
While functionally similar, uCalc's `EvalStr` is vastly more secure. Scripting language `eval()` functions can often execute arbitrary code, creating significant security vulnerabilities (code injection). `EvalStr` operates within a sandboxed environment defined by your uCalc instance; it can only execute the functions, operators, and variables you have explicitly defined and cannot interact with the host system's file system, network, or other resources without being given explicit access.

**vs. Manual Parsing in C++/C#**
Implementing a robust expression evaluator from scratch is a complex task involving tokenization, abstract syntax tree (AST) construction, type checking, and evaluation logic. `EvalStr` abstracts all this complexity into a single, powerful function call, dramatically reducing development time and potential for bugs.

**Examples:**

### Example ID: 337

**Description:** Demonstrates basic, one-line evaluations for numeric, string, and boolean expressions.

**Code:**
```pseudocode
// Basic arithmetic
wl(uc.EvalStr("15 * (4 + 3)"))
// String manipulation
wl(uc.EvalStr("UCase('hello') + ', world!'"))
// Boolean logic
wl(uc.EvalStr("10 > 5 AndAlso 'a' < 'b'"))
```

**Output:**
```
105
HELLO, world!
true
```

---

### Example ID: 338

**Description:** Calculates a total price using predefined variables and demonstrates the effect of output formatting.

**Code:**
```pseudocode
// Define some context for the expression
uc.DefineVariable("price = 49.99");
uc.DefineVariable("quantity = 3");
uc.DefineConstant("TAX_RATE = 0.0825");

// Define a format for currency output
uc.Format("DataType: Double, Def: result = '$' + result");

// Expression to calculate total price, using variables
var expression = "price * quantity * (1 + TAX_RATE)";

// Evaluate with formatting enabled
wl("Formatted Total: ", uc.EvalStr(expression, true))

// Evaluate with formatting disabled
wl("Raw Total: ", uc.EvalStr(expression, false))
```

**Output:**
```
Formatted Total: $162.342525
Raw Total: 162.342525
```

---

### Example ID: 23

**Description:** Evaluating expressions returned as string

**Code:**
```pseudocode
uc.DefineVariable("x = 123");
uc.DefineVariable("y");

wl(uc.EvalStr("1 + 1"))
wl(uc.EvalStr("UCase('Hello ' + 'world!')"))
wl(uc.EvalStr("$'Interpolation: {2+3}'"))
wl(uc.EvalStr("#b101 + #hAE"))
wl(uc.EvalStr("Hex(1234)"))
wl(uc.EvalStr("(3+5*#i)^2"))
wl(uc.EvalStr("3 > 4"))
wl(uc.EvalStr("Max(5, 10, 3, -5)"))
wl(uc.EvalStr("x * 10"))
uc.EvalStr("x = 456");
wl(uc.EvalStr("x"))
wl(uc.EvalStr("2+4, 5+4, 10+20"))
wl(uc.EvalStr("y=100; ForLoop(x, 1, 10, 1, y = y + x); y"))
wl(uc.EvalStr("10 / "))
```

**Output:**
```
2
HELLO WORLD!
Interpolation: 5
179
4d2
-16+30i
false
10
1230
456
30
155
Syntax error
```

---

### Example ID: 22

**Description:** How to perform a summation in a loop efficiently using Execute() instead of Evaluate().

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x = 0");
var Total = uc.DefineVariable("Total");
var(string, Expression) = "x++; Total = Total + x^2 + 5";

var ParsedExpr = uc.Parse(Expression);

for(double x = 1 to 10)
   // Execute() runs the parsed expression without the overhead of returning a value.
   // This provides near-native performance for loops across C#, VB, and C++.
   ParsedExpr.Execute();

   // Evaluate string interpolation to output the final calculated total
   wl(uc.EvalStr("$'{x}   Sub total = {Total}'"))
end for

wl(uc.EvalStr("$'Total = {Total}'"))

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
1   Sub total = 6
2   Sub total = 15
3   Sub total = 29
4   Sub total = 50
5   Sub total = 80
6   Sub total = 121
7   Sub total = 175
8   Sub total = 244
9   Sub total = 330
10   Sub total = 435
Total = 435
```

---

---

## ExpressionTokens = [Tokens] - ID: 639
/doc/reference/classes/ucalc/expressiontokens-=-[tokens]/

**Description:** Retrieves the token definition collection used by the expression parser, allowing for inspection and customization.

**Remarks:**

The `ExpressionTokens()` property is your gateway to uCalc's lexical analysis engine. It returns the [Tokens](/ucalc/tokens) object that defines how input strings are broken down into fundamental units (tokens) before being parsed.

### 🏷️ What Are Tokens?

Before uCalc can evaluate an expression like `My_Var + 10`, it must first break it down into meaningful pieces called tokens. For that expression, the tokenizer would produce:

1.  `My_Var` - An `AlphaNumeric` token (an identifier).
2.  `+` - A `Reducible` token (an operator symbol).
3.  `10` - A `Literal` token (a number).

This method gives you direct access to the regular expressions (regex) that define these token types.

### 🛠️ Why Customize Tokens?

Modifying the default token set allows you to extend uCalc's syntax to support new language constructs. Common use cases include:

*   **New Number Formats**: Add support for C-style hexadecimal (`0x...`) or binary (`0b...`) literals.
*   **Custom Identifiers**: Change the rules for variable and function names, for example, to allow characters like `$` or `#`.
*   **Domain-Specific Literals**: Define tokens for concepts unique to your application, such as date formats (`dd-mm-yyyy`) or version strings (`v1.2.3`).
*   **New Comment Styles**: Implement single-line (`//...`) or multi-line (`/*...*/`) comments.

See the [Tokens](/ucalc/tokens) class for all available methods to `Add`, `Remove`, or `Modify` token definitions.

### Comparative Analysis: Why uCalc?

*   **vs. Manual String Parsing/Regex**: Manually parsing input with string functions and regular expressions is complex and error-prone. Standard regex struggles with nested structures (like parentheses) and context (distinguishing unary minus from subtraction). uCalc's tokenizer is structured, context-aware, and handles these challenges automatically.

*   **vs. Lexer Generators (e.g., ANTLR, Lex/Flex)**: Traditional compiler tools are extremely powerful but require an external toolchain, a separate definition language (like `.g4` files), and a code generation/build step. This process is static. uCalc's key advantage is that its token engine is **fully dynamic and programmatic**. You can add, remove, or modify token definitions at runtime, from within your code, without any external tools or recompilation. This provides unparalleled flexibility for creating adaptable and user-extendable DSLs.

**Examples:**

### Example ID: 340

**Description:** Quick Start: Inspects the regex pattern for a single, common token type (alphanumeric identifiers).

**Code:**
```pseudocode
var tokens = uc.@ExpressionTokens();
var alphanumericToken = tokens[TokenType::AlphaNumeric];

wl("The regex for alphanumeric tokens is:")
wl(alphanumericToken.@Regex())
```

**Output:**
```
The regex for alphanumeric tokens is:
[a-zA-Z_][a-zA-Z0-9_]*
```

---

### Example ID: 342

**Description:** Extends the parser to support C-style `0x` hex and `0b` binary notations using a token transformer.

**Code:**
```pseudocode
// Define a token for C-like 0x hex notation
uc.@ExpressionTokens().Add("0x[0-9A-Fa-f]+", TokenType::TokenTransform);
uc.@TokenTransformer().FromTo("{'0x'}{Num:'[0-9A-Fa-f]+'}", "BaseConvert('{Num}', 16)");
wl("0xFF is evaluated as: ", uc.EvalStr("0xFF"))

// Define a token for C++-style 0b binary notation
uc.@ExpressionTokens().Add("0b[01]+", TokenType::TokenTransform);

// Using {@Eval} is more efficient as the conversion happens once during the token transform pass.
uc.@TokenTransformer().FromTo("{'0b'}{Num:'[01]+'}", "{@Eval: BaseConvert(Num, 2)}");
wl("0b1011 is evaluated as: ", uc.EvalStr("0b1011"))

// Note: uCalc has built-in support for hex/binary using # notation (e.g., #hFF, #b1011)
wl("uCalc's built-in #hFF is: ", uc.EvalStr("#hFF"))
```

**Output:**
```
0xFF is evaluated as: 255
0b1011 is evaluated as: 11
uCalc's built-in #hFF is: 255
```

---

### Example ID: 70

**Description:** Displays the complete list of default token definitions, showing their type, internal name, and regex pattern.

**Code:**
```pseudocode
// Lists all tokens currently defined for the expression evaluator.

wl("Token Count: ", uc.@ExpressionTokens().@Count())
wl("")
wl("Index  Type  Name: regex")
wl("========================")
var Tokens = uc.@ExpressionTokens();
foreach (var token in Tokens)
   w(Tokens.IndexOf(token))
   wl("  ", token.@Description(), "  ", token.@Name(), ": ", token.@Regex())
end for

// Note that the expression evaluator token list has a few extra tokens,
// related to hex/bin/oct notation, string interpolation, and imaginary number
// notation, which are not found in the default Transformer token list.
```

**Output:**
```
Token Count: 30

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
27  literal  _token_imaginaryunit: #i
28  tokentransform  _token_binaryhexoctalnotation: #[bho][0-9A-F]+
29  tokentransform  _token_stringinterpolationquote: \$['"]
```

---

### Example ID: 170

**Description:** Token(TokenType)

**Code:**
```pseudocode
wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Name())
wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex())
wl("")

// Note: In C# or VB you can simply use [TokenType::Literal, n]
// instead of ByType(TokenType::Literal, n)
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 0).@Name())
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 1).@Name())
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 2).@Name())
```

**Output:**
```
_token_alphanumeric
[a-zA-Z_][a-zA-Z0-9_]*

_token_string_singlequoted
_token_string_doublequoted
_token_string_tripledoublequoted
```

---

### Example ID: 71

**Description:** Change characters accepted as alphanumeric in expressions using ExpressionTokens() & Token()

**Code:**
```pseudocode
// (See alternate version of this example using ItemOf instead of ExpressionTokens)

// In this section underscore, _, and numeric digits
// are accepted as part of alphanumeric tokens
uc.DefineVariable("My_Variable = 111");
wl(uc.@Error().@Message())
uc.DefineVariable("Variable123 = 222");
wl(uc.@Error().@Message())

wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex())
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
wl("---")

// Now we no longer want underscore, _, or numeric digits
// to be accepted in alphanumeric tokens; only A-Z
uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex("[a-zA-Z]+");

uc.DefineVariable("Other_Variable = 333");
wl(uc.@Error().@Message())
uc.DefineVariable("OtherVariable123 = 444");
wl(uc.@Error().@Message())

wl(uc.EvalStr("Other_Variable"))
wl(uc.EvalStr("OtherVariable123 "))
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
wl("---")

// We restore the alphanumeric regex to support _ and numbers again
// Note: My_Variable and Variable123 remained; they were simply inaccessible
uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex("[a-zA-Z_][a-zA-Z0-9_]*");
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
```

**Output:**
```
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222
```

---

---

## ExpressionTransformer = [Transformer] - ID: 48
/doc/reference/classes/ucalc/expressiontransformer-=-[transformer]/

**Description:** Returns the singleton transformer instance used to pre-process expressions before they are parsed.

**Remarks:**

Returns the singleton `Transformer` instance dedicated to pre-processing expressions before they are parsed by functions like [Eval](/reference/ucalc/mainclassgroup/eval), [EvalStr](/reference/ucalc/mainclassgroup/evalstr), and [Parse](/reference/ucalc/mainclassgroup/parse).

This powerful feature allows you to define structural, token-aware rewrite rules to create custom syntax, simplify complex expressions, or transpile constructs from other languages.

---

## ⚙️ How It Works

When you define a rule on the `ExpressionTransformer`, any expression string passed to the parser is first processed by these rules. This happens *before* the expression is evaluated.

For example, you can create a rule to automatically convert `x^y` into `pow(x,y)`, effectively adding a new operator to the language without using [DefineOperator](/reference/ucalc/mainclassgroup/defineoperator).

---

## 💡 Common Use Cases

*   **Creating syntactic sugar**: `Avg(1,2,3)` -> `(1+2+3)/3`
*   **Transpiling operators**: `a ? b : c` -> `iif(a, b, c)`
*   **Adding domain-specific keywords**: `CalculateYield(rate, time)` -> `rate * (1 + time)^2`
*   **Enforcing coding standards**: Rewriting deprecated function names to their modern equivalents.

---

## Comparative Analysis

### `ExpressionTransformer` vs. `Alias`

| Feature | `ExpressionTransformer` | `Alias` |
| :--- | :--- | :--- |
| **Mechanism** | Textual transformation (slower) | Internal symbol table pointer (faster) |
| **Flexibility** | Can change structure, add/remove arguments | Simple 1-to-1 name replacement only |
| **Use Case** | Use for changing syntax or structure. | Use for creating simple synonyms (`Log` -> `Ln`). |

Choose [Alias](/reference/ucalc/mainclassgroup/alias) for simple renaming; it's significantly more performant as it avoids the entire transformation step.

### `ExpressionTransformer` vs. `NewTransformer`

*   `ExpressionTransformer()`: Modifies the **built-in parsing pipeline**. Rules defined here affect **all** subsequent calls to `Eval`, `Parse`, etc., within that `uCalc` instance.
*   [NewTransformer()](/reference/ucalc/mainclassgroup/newtransformer): Creates a **standalone**, independent `Transformer` object. It does not affect the built-in parser and is used for general-purpose text transformation tasks.

### `ExpressionTransformer` vs. Standard Regex

A `Transformer` is superior to regular expressions for language constructs because it operates on **tokens**, not just characters. It inherently understands concepts like nested parentheses, quoted strings, and numbers, which are notoriously difficult to handle correctly with regex.

---

## ⚠️ Performance Considerations

A `Transformer` object is not created for a `uCalc` instance until `ExpressionTransformer()` is called for the first time. Once created, it introduces a small overhead to every parse operation, even if no rules are defined. For performance-critical applications where transformations are not needed, avoid calling this method.

For more targeted, token-level transformations (like defining hex `0xFF` notation or string interpolation), consider using [TokenTransformer](/reference/ucalc/mainclassgroup/tokentransformer), which is only triggered when a specific token type is matched.

---

The returned [Transformer](/reference/transformer/mainclassgroup/transformer) object should **not** be released manually. It is owned by the parent `uCalc` instance.

**Examples:**

### Example ID: 346

**Description:** Demonstrates using `RewindOnChange(true)` to perform recursive-style transformations, such as creating a variadic `AddUp` function.

**Code:**
```pseudocode
var t = uc.@ExpressionTransformer();

// Base case: a single argument
t.FromTo("AddUp({x})", "{x}");

// Recursive case: multiple arguments
// RewindOnChange(true) causes the transformer to re-scan the string after a replacement.
// This allows AddUp(1,2,3) -> (1 + AddUp(2,3)) -> (1 + (2 + AddUp(3))) -> (1 + (2 + 3))
t.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))").@RewindOnChange(true);

wl("Input: AddUp(1, 2, 3, 4)")
wl("Result: ", uc.Eval("AddUp(1, 2, 3, 4)"))
```

**Output:**
```
Input: AddUp(1, 2, 3, 4)
Result: 10
```

---

### Example ID: 347

**Description:** Internal Test: Verifies that multi-pass transformations work correctly when `RewindOnChange` is enabled for the entire rule set.

**Code:**
```pseudocode
var t = uc.@ExpressionTransformer();

// Enable RewindOnChange for all subsequently added rules
t.@DefaultRuleSet().@RewindOnChange(true);

// Define a chain of simple transformations
t.FromTo("A", "B");
t.FromTo("B", "C");
t.FromTo("C", "D");

// The transformer should apply all rules in sequence: A -> B -> C -> D
var result = t.Transform("A").@Text();
wl("Transform('A') -> ", result)
wl("Is correct: ", bool(result == "D"))
```

**Output:**
```
Transform('A') -> D
Is correct: True
```

---

### Example ID: 73

**Description:** Using ExpressionTransformer to transform expressions before they are parsed

**Code:**
```pseudocode
var ExprT = uc.@ExpressionTransformer();  // Transformer used for Eval() and Evaluate()

var p1 = ExprT.FromTo("AddUp({x})", "{x}"); // RewindOnChange False by default
var p2 = ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))").SetRewindOnChange(true);

wl("p1 RewindOnChange: ", bool(p1.@RewindOnChange()))
wl("p2 RewindOnChange: ", bool(p2.@RewindOnChange()))

wl("")

wl("Input: ", "AddUp(1,2,3,4)")
wl("Transform: ", ExprT.Transform("AddUp(1,2,3,4)"))
wl("Eval: ", uc.Eval("AddUp(1,2,3,4)"))
```

**Output:**
```
p1 RewindOnChange: False
p2 RewindOnChange: True

Input: AddUp(1,2,3,4)
Transform: (1 + (2 + (3 + 4)))
Eval: 10
```

---

### Example ID: 152

**Description:** RewindOnChange

**Code:**
```pseudocode
var ExprT = uc.@ExpressionTransformer();  // Transformer used for Eval() and Evaluate()

ExprT.@DefaultRuleSet().@RewindOnChange(true);

ExprT.FromTo("AddUp({x})", "{x}");
ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

ExprT.FromTo("ArgCount({x})", "1");
ExprT.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))");

ExprT.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})");

var Expression = "Average(1, 2, 3, 4)";
wl("Input: ", Expression)
wl("Transform: ", ExprT.Transform(Expression))
wl("Eval: ", uc.Eval(Expression))
```

**Output:**
```
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
```

---

---

## Format - ID: 50
/doc/reference/classes/ucalc/format/

---

## Format(OpCallback, string, DataType) - ID: 52
/doc/reference/classes/ucalc/format/format-opcallback,-string,-datatype/

**Description:** Registers a callback function to dynamically format the string output of evaluated expressions.

**Syntax:** Format(OpCallback, string, DataType)
**Parameters:**
callback - OpCallback - The user-defined callback function that receives the raw result and returns the formatted string.
targetDataTypeName - string [default = ""] - The name of the data type this format applies to. Omit or pass an empty string to apply the format to all data types.
targetDataType - DataType [default = Empty] - A `DataType` object to target. This provides an alternative to specifying the data type by name.
**Return:** Item - Returns an `Item` object representing the created format rule. This object can be used later to release the format.
**Remarks:**

The `Format()` method allows you to intercept the output of functions like [EvalStr](/uCalc/EvalStr) and [EvaluateStr](/Expression/EvaluateStr) and apply custom formatting transformations using a callback function. This creates a powerful, dynamic post-processing pipeline for all expression results.

**Note**: There are two versions of Format().  This one involves using a callback to a function in the host application for the formatting logic, while the other Format definition is done inline.

### 🎯 Targeting Specific Data Types

You can create formatters that apply globally or only to specific data types:

*   **Global Formatter**: If you omit the `targetDataTypeName` and `targetDataType` parameters, the callback will be applied to the string result of *all* data types.
*   **Type-Specific Formatter**: By providing a data type name (e.g., `"Double"`) or a `DataType` object, you can restrict the formatter to run only when the expression result matches that type. This is ideal for scenarios like formatting numbers as currency, dates into a specific layout, or booleans as "Yes/No".

### 📚 Layering and Execution Order (The Format Stack)

uCalc maintains a separate formatting pipeline for each data type (plus one for global formatters). When you add multiple formatters, they are pushed onto a stack. The execution order is **Last-In, First-Out (LIFO)**:

1.  The most recently added formatter is executed first.
2.  Its output is then passed as the input to the previously added formatter.
3.  This continues until all applicable formatters in the stack have been processed.

This layering allows for building up complex formatting from simple, reusable components.

### 🗑️ Releasing Formats

This method returns an [Item](/ucalc/item) object. To remove the formatter from the pipeline, call [uCalc.Item.Release](/ucalc/item/release) on this item. This is crucial for temporary formatting rules to avoid memory leaks and unintended side effects.

Also, [uCalc.EvalStr](/ucalc/evalstr) has a parameter that suppresses all formatting just for the given expression.

You can view all active formatters by using `uc.ListOfItems(ItemIs.Format);`.

### 🆚 Comparative Analysis

While languages like C# (string interpolation, `String.Format`) and Python (f-strings) provide excellent static formatting, uCalc's `Format()` method offers a different paradigm:

*   **Runtime Configuration**: uCalc formatters are defined and layered at runtime. This allows an application to change its output style dynamically, perhaps based on user preferences or localization settings, without recompiling code.
*   **Decoupled Logic**: The formatting logic is decoupled from the expression evaluation. You can define a complex calculation once and apply different formatting 'skins' to its output. This is highly effective for applications that need to present the same data in multiple ways (e.g., a report, a chart tooltip, a log file).
*   **Middleware Pipeline**: The format stack acts like a middleware pipeline for strings, a concept more common in web frameworks. This is a uniquely powerful feature for a math parser, enabling sophisticated transformations that go far beyond simple value-to-string conversion.

**Examples:**

### Example ID: 26

**Description:** Format using callback functions

**Code:**
```pseudocode
[head]
[callback OutputAnswerCB]
  cb.ReturnStr("Answer: " + cb.ArgStr(1));
[/callback]
[callback OutputSymbolCB]
  cb.ReturnStr("==> " + cb.ArgStr(1));
[/callback]
[callback OutputBoolCB]
  if (cb.ArgStr(1) == "false")
    cb.ReturnStr("No");
  else if (cb.ArgStr(1) == "true")
    cb.ReturnStr("Yes");
  end if
[/callback]
[body]

// This format inserts "Answer: " in front of every result
var OutputAnswer = uc.Format([VB]AddressOf[/VB] OutputAnswerCB);
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl("---")

// This one inserts ==> in front of the result
// The previously defined "Answer: " output is still prepended as well
var OutputSymbol = uc.Format([VB]AddressOf[/VB] OutputSymbolCB);
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl("---")

// Causes Boolean values to return Yes or No (instead of true or false)
var OutputBool = uc.Format([VB]AddressOf[/VB] OutputBoolCB, "Bool");
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl(uc.EvalStr("5 < 10"))
wl("---")

// The previously defined "==>" output is removed
OutputSymbol.Release();
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl(uc.EvalStr("5 < 10"))
```

**Output:**
```
Answer: 30
Answer: Hello world
Answer: false
---
Answer: ==> 30
Answer: ==> Hello world
Answer: ==> false
---
Answer: ==> 30
Answer: ==> Hello world
Answer: ==> No
Answer: ==> Yes
---
Answer: 30
Answer: Hello world
Answer: No
Answer: Yes
```

---

---

## Format(string, DataType) - ID: 53
/doc/reference/classes/ucalc/format/format-string,-datatype/

**Description:** Defines a declarative rule for transforming the string output of evaluation functions.

**Syntax:** Format(string, DataType)
**Parameters:**
definition - string - A string containing the formatting rule definition.
targetType - DataType [default = Empty] - The specific data type this format applies to. If omitted, the format applies to all data types.
**Return:** Item - Returns the `Item` object representing the newly created format rule. This item can be used to `.Release()` the format later.
**Remarks:**

The `Format()` method allows you to define powerful, declarative rules that automatically transform the string output of [EvalStr](/ucalc/evalstr) and [EvaluateStr](/expression/evaluatestr). This is ideal for ensuring consistent formatting for currency, scientific notation, or custom displays without cluttering your application logic with string manipulation code.

### 📜 Definition String Syntax

The `Definition` string specifies the transformation rule and can contain several optional components:

`[DataType: <TypeName>,] [InsertAt: <index>,] [Def: <variable> = <expression>]`

*   **`DataType`**: Scopes the rule to a specific type (e.g., `Double`, `String`, `Bool`). This can also be set via the method's second parameter.
*   **`InsertAt`**: Controls the order of application when multiple formats are active. See the 'Chaining Formats' section below.
*   **`Def`**: The core expression that defines the transformation. It uses a temporary variable (e.g., `Result`, `val`) to represent the original output string.

There are two primary styles for writing the format expression:

#### 1. C++ `std::format` Style (Recommended)
This modern approach uses a built-in `Format()` function within the expression, mirroring the syntax of C++ `std::format` or Python f-strings.

```pseudocode
// Format numbers to two decimal places.
uc.Format("Result = Format('{:.2f}', double(Result))");
```

**Note**: The placeholder variable (`Result`) is always a **string**. For numeric format specifiers, you must cast it back to a number using `double(Result)`, `int(Result)`, etc.

Use ListOfItems(ItemIs.Format) to see the list of active formats.

#### 2. String Concatenation Style
This legacy style builds the new string using the `+` operator.

```pseudocode
// Wrap the output in brackets.
uc.Format("Result = '[' + Result + ']'");
```

### 🔗 Chaining Formats

You can define multiple format rules, which are applied sequentially like a stack (Last-In, First-Out). The most recently defined format is applied first.

The `InsertAt` keyword gives you precise control over this order:
*   `InsertAt: 0`: Places the rule at the front of its type-specific chain (it will be applied **last**).
*   `InsertAt: -1` or omitting it: Places the rule at the end of the chain (it will be applied **first**).
*   `InsertAt: n`: Inserts the rule at the nth position in the chain.

### 🧹 Cleanup

To remove all defined formats, call [FormatRemove](/ucalc/formatremove). To remove a single format rule, call `.Release()` on the [Item](/ucalc/item) object returned by this method.

### ⚖️ Comparative Analysis

Unlike traditional formatting (`printf`, C# `string.Format`), which requires you to wrap every output call, uCalc's `Format` method is declarative. You define the rules once, and they are applied automatically by `EvalStr` everywhere in your application for a given `uCalc` instance. This leads to cleaner, more maintainable code by separating calculation logic from presentation logic.

**Examples:**

### Example ID: 351

**Description:** A basic example that prepends text to all numeric output.

**Code:**
```pseudocode
// Define a format that only applies to Double data types.
var doubleType = uc.DataTypeOf("Double");
var fmt = uc.Format("Result = 'Value: ' + Result", doubleType);

wl(uc.EvalStr("10 * 2.5"))
wl(uc.EvalStr("'Hello'")) // String output is unaffected.

// Clean up the format rule
fmt.Release();
wl(uc.EvalStr("10 * 2.5")) // No longer formatted
```

**Output:**
```
Value: 25
Hello
25
```

---

### Example ID: 352

**Description:** Practical: Using the C++ style `Format()` function for currency and text alignment.

**Code:**
```pseudocode
// Rule 1: Format Doubles as currency with two decimal places.
var doubleType = uc.DataTypeOf(BuiltInType::Float_Double);
uc.Format("Result = '$' + Format('{:.2f}', double(Result))", doubleType);

// Rule 2: Center-align strings in a 15-character field padded with '-'.
var strType = uc.DataTypeOf(BuiltInType::String);
uc.Format("Result = Format('{:-^15}', Result)", strType);

wl("Price: ", uc.EvalStr("199.999"))
wl("Discount: ", uc.EvalStr("7.5"))
wl("Label: ", uc.EvalStr("'Summary'"))
```

**Output:**
```
Price: $200.00
Discount: $7.50
Label: ----Summary----
```

---

### Example ID: 353

**Description:** Internal Test: Verifies the layering and precedence of multiple format rules using `InsertAt`.

**Code:**
```pseudocode
var strType = uc.DataTypeOf("String");

// Rule A (will be applied second)
uc.Format("val = '[' + val + ']'");

// Rule B (will be applied first)
uc.Format("val = 'inner:(' + val + ')'");

wl("Default layering: ", uc.EvalStr("'text'"))

// Rule C: Insert this rule at position 0, making it apply LAST.
uc.Format("InsertAt: 0, Def: val = 'outer: {' + val + '}'");

wl("With InsertAt: ", uc.EvalStr("'text'"))
```

**Output:**
```
Default layering: [inner:(text)]
With InsertAt: outer: {[inner:(text)]}
```

---

### Example ID: 27

**Description:** Output formatting without using a callback

**Code:**
```pseudocode
// The output is surrounded by < and >, and prepended with Answer:
uc.Format("Result = 'Answer: <' + Result + '>'");

wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))

uc.FormatRemove();
```

**Output:**
```
Answer: <30>
Answer: <Hello world>
Answer: <false>
```

---

### Example ID: 28

**Description:** Different output formats for different data types

**Code:**
```pseudocode
// String results will be surrounded by << and >>, while Boolean will be surrounded by [[ and ]]
uc.Format("DataType: String, Def: val = '<<' + val + '>>' ");
uc.Format("Bool, val = '[[' + val + ']]'"); // Shortcut notation without "DataType" or "Def"

wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl(uc.EvalStr("5 < 10"))

uc.FormatRemove();
wl("---")
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl(uc.EvalStr("5 < 10"))
```

**Output:**
```
30
<<Hello world>>
[[false]]
[[true]]
---
30
Hello world
false
true
```

---

### Example ID: 29

**Description:** Inserts formatting in specified sequence

**Code:**
```pseudocode
uc.Format("Result = 'Answer: ' + Result");
uc.Format("DataType: String, Def: val = '<<' + val + '>>' ");
uc.Format("DataType: Bool, Def: val = '[[' + val + ']]'");

// Note the difference between where "Bool: " and "String: " are displayed in the result
uc.Format("InsertAt: 0, DataType: Bool, Def: val = 'Bool: ' + val");  // Inserts at 0th position of Bool
uc.Format("InsertAt: 1, DataType: String, Def: val = 'String: ' + val"); // Inserts at 1st position of String
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl("---")

// This fomratting will be the last one to take effect
uc.Format("InsertAt: 0, Def: val = 'Outer: ' + val");
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl("---")

// This formatting will be the first one to take effect
uc.Format("val = 'Inner: ' + val"); // Optionally InsertAt: -1 could have been used
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl("---")

uc.FormatRemove();

wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
```

**Output:**
```
Answer: 30
Answer: String: <<Hello world>>
Bool: Answer: [[false]]
---
Outer: Answer: 30
Outer: Answer: String: <<Hello world>>
Outer: Bool: Answer: [[false]]
---
Outer: Answer: Inner: 30
Outer: Answer: String: <<Inner: Hello world>>
Outer: Bool: Answer: [[Inner: false]]
---
30
Hello world
false
```

---

---

## FormatRemove - ID: 54
/doc/reference/classes/ucalc/formatremove/

**Description:** Removes one or all custom output formatting rules previously defined with the Format method.

**Syntax:** FormatRemove(DataType)
**Parameters:**
targetType - DataType [default = Empty] - Optional. The data type whose formatting rules should be removed. If omitted, all formatting rules for all types are removed.
**Return:** void - This method does not return a value.
**Remarks:**

`FormatRemove` clears one or more custom output formatting rules that were previously defined using [uCalc.Format](/ucalc/format). This restores the default string representation for evaluated results.

You can use this method in two ways:

*   **Remove All Formatting**: Call `FormatRemove()` with no arguments to clear every formatting rule for all data types within the current `uCalc` instance.
*   **Remove Type-Specific Formatting**: Pass a [DataType](/ucalc/datatype) object (e.g., `uc.DataTypeOf("String")`) to remove only the formatting rules associated with that specific type, leaving others intact.

This is useful for dynamically changing the output style of your application or for cleaning up temporary formatting rules.

### Temporary Suppression vs. Permanent Removal

It's important to distinguish between removing a format and temporarily suppressing it.

*   `uc.FormatRemove()`: **Permanently deletes** the formatting rule(s). They must be redefined with [uCalc.Format](/ucalc/format) to be used again.
*   `uc.EvalStr(expression, false)`: **Temporarily bypasses** all formatting for a single evaluation. The rules remain defined and will apply to subsequent `EvalStr` calls that don't explicitly disable them.

---

### 🏛️ Comparative Analysis

Most programming languages handle formatting at the point of conversion to a string, often using format specifiers.

*   **C-style `printf` / `sprintf`**: `printf("Value: %.2f", my_var);`
*   **C# String Formatting**: `myVar.ToString("F2");` or `$"Value: {myVar:F2}"`
*   **Python f-strings**: `f"Value: {my_var:.2f}"`

These approaches are **imperative** and **localized**; the formatting logic is applied wherever the string is generated.

uCalc's [uCalc.Format](/ucalc/format) and `FormatRemove` system is **declarative** and **centralized**. You define formatting rules once per `uCalc` instance, and they are automatically applied to all relevant [EvalStr](ucalc/evalstr) or [EvaluateStr](expression/evaluatetstr) results. This is more akin to middleware or Aspect-Oriented Programming (AOP), where cross-cutting concerns (like output formatting) are managed separately from the core evaluation logic. `FormatRemove` provides the dynamic ability to tear down this "middleware" at runtime, offering a level of control not typically found in standard library formatters.

**Examples:**

### Example ID: 28

**Description:** Different output formats for different data types

**Code:**
```pseudocode
// String results will be surrounded by << and >>, while Boolean will be surrounded by [[ and ]]
uc.Format("DataType: String, Def: val = '<<' + val + '>>' ");
uc.Format("Bool, val = '[[' + val + ']]'"); // Shortcut notation without "DataType" or "Def"

wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl(uc.EvalStr("5 < 10"))

uc.FormatRemove();
wl("---")
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl(uc.EvalStr("5 < 10"))
```

**Output:**
```
30
<<Hello world>>
[[false]]
[[true]]
---
30
Hello world
false
true
```

---

### Example ID: 29

**Description:** Inserts formatting in specified sequence

**Code:**
```pseudocode
uc.Format("Result = 'Answer: ' + Result");
uc.Format("DataType: String, Def: val = '<<' + val + '>>' ");
uc.Format("DataType: Bool, Def: val = '[[' + val + ']]'");

// Note the difference between where "Bool: " and "String: " are displayed in the result
uc.Format("InsertAt: 0, DataType: Bool, Def: val = 'Bool: ' + val");  // Inserts at 0th position of Bool
uc.Format("InsertAt: 1, DataType: String, Def: val = 'String: ' + val"); // Inserts at 1st position of String
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl("---")

// This fomratting will be the last one to take effect
uc.Format("InsertAt: 0, Def: val = 'Outer: ' + val");
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl("---")

// This formatting will be the first one to take effect
uc.Format("val = 'Inner: ' + val"); // Optionally InsertAt: -1 could have been used
wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
wl("---")

uc.FormatRemove();

wl(uc.EvalStr("10+20"))
wl(uc.EvalStr("'Hello '+'world'"))
wl(uc.EvalStr("5 > 10"))
```

**Output:**
```
Answer: 30
Answer: String: <<Hello world>>
Bool: Answer: [[false]]
---
Outer: Answer: 30
Outer: Answer: String: <<Hello world>>
Outer: Bool: Answer: [[false]]
---
Outer: Answer: Inner: 30
Outer: Answer: String: <<Inner: Hello world>>
Outer: Bool: Answer: [[Inner: false]]
---
30
Hello world
false
```

---

---

## Handle - ID: 55
/doc/reference/classes/ucalc/handle/

**Description:** Returns the internal handle of the uCalc instance, a unique identifier used by the library for low-level operations.

**Syntax:** Handle()
**Return:** ADDR - The internal handle of the current uCalc instance. While typed as a `uCalc` object for convenience, it represents an opaque pointer whose numeric value is not guaranteed to be consistent across application runs.
**Remarks:**

This method retrieves the internal handle of a uCalc object. Handles are opaque, pointer-like identifiers used by the uCalc library to manage instances. This is primarily intended for advanced debugging and internal diagnostics.

### What is a Handle?
A handle is a unique, low-level identifier for a specific uCalc instance in memory. Its actual numeric value is unpredictable and can change every time the application runs. It should not be stored or used for serialization.

For a stable and predictable identifier, use [MemoryIndex](/uCalc-Documentation/Reference/uCalc/uCalc/MemoryIndex) instead.

--- 

### ⚖️ `Handle` vs. `MemoryIndex`

| Feature | Handle | MemoryIndex |
| :--- | :--- | :--- |
| **Stability** | **Volatile**. Changes between application runs. | **Stable**. Predictable and sequential. |
| **Uniqueness** | Guaranteed unique for the object's lifetime. | Can be **recycled** after an object is released. |
| **Purpose** | Low-level object identification for the C++ core. | High-level diagnostics and tracking object lifetime. |
| **Use Case** | Advanced debugging. | Identifying specific instances for logging or in diagnostic tools. |

--- 

### Comparative Analysis

In C# or C++, you might think of a handle as being similar to an `IntPtr` or a raw pointer (`void*`). It refers to a specific memory location managed by the uCalc engine. However, unlike raw pointers, the uCalc handle is managed within the uCalc ecosystem. The key takeaway for developers is to use `MemoryIndex` for any form of stable identification and to treat the `Handle` as a transient, internal-only value.

**Examples:**

---

## IsDefault = [bool] - ID: 57
/doc/reference/classes/ucalc/isdefault-=-[bool]/

**Description:** Gets or sets whether the current uCalc instance is the active default for the current thread.

**Remarks:**

# ⚙️ Managing the Default Instance

The `IsDefault` property gets or sets whether the current `uCalc` instance is the active **default instance** for the current thread. This default instance serves two main purposes:

1.  **An Ambient Context**: It acts as a convenient, globally accessible singleton. Components like [uCalc.Expression](/Reference/uCalcBase/Expression/Constructor) or [uCalc.String](/Reference/uCalcBase/String/Constructor), when created without an explicit `uCalc` instance, automatically use the default one for their context.
2.  **A Template for Clones**: When you create a new `uCalc` instance via its constructor, it is initialized as a clone of the current default instance, inheriting all its functions, variables, and settings.

---

## 📖 The Default Instance Stack

Instead of a single, rigid global object, uCalc manages a stack of default instances using a LIFO (Last-In, First-Out) model. This provides a flexible, layered context system.

The instance at the **top of the stack** is the *active* default, which is returned by [DefaultInstance](/Reference/uCalcBase/uCalc/DefaultInstance).


### 🔧 Getter and Setter Behavior

*   **Getter**: [pseudocode]`var isDefault = myInstance.@IsDefault()`
    Returns `true` if `myInstance` is currently at the top of the default stack; otherwise, `false`.

*   **Setter**: [pseudocode]`myInstance.@IsDefault(true)`
    Promotes `myInstance` to the top of the stack, making it the new active default.

*   **Setter**: [pseudocode]`myInstance.@IsDefault(false)`
    Removes `myInstance` from the stack, wherever it may be. If it was the active default, the previously active instance is automatically restored.

### ⏱️ Scoped Defaults

The recommended way to manage temporary contexts is to combine `@IsDefault` with a [pseudocode]`NewUsing(uCalc, uc)` block. When the scope is exited, the `uCalc` instance is automatically released and popped from the stack, cleanly restoring the previous default.

```pseudocode
// Main context is active here
NewUsing(uCalc, tempContext)
    tempContext.@IsDefault(true);
    // tempContext is now the active default within this block
End Using
// The original default context is automatically restored here
```

--- 

## ✨ Best Practices

*   Avoid modifying the initial, built-in default instance directly. Instead, create a new, fully configured `uCalc` instance and set that as your application's primary default.
*   Use scoped `using` blocks or call `@IsDefault(false)` to clean up temporary defaults and prevent unexpected behavior.
*   Use [DefaultCount()](/Reference/uCalcBase/uCalc/DefaultCount) to inspect the size of the stack and [DefaultClear()](/Reference/uCalcBase/uCalc/DefaultClear) to reset the stack to its initial state.

## 🆚 Why uCalc? (Comparative Analysis)

In standard C# or C++, managing a "global" context requires careful design patterns.

*   **Singleton Pattern**: A traditional singleton is rigid and hard to test. uCalc's stack-based approach is more dynamic, allowing for temporary context overrides within specific scopes.
*   **Dependency Injection (DI)**: While robust, DI adds boilerplate, especially for ubiquitous components like a parser. The default instance acts as a convenient "ambient context," simplifying code.
*   **Static Class**: This prevents having multiple, separate parser configurations running at the same time. uCalc's model allows for complete isolation between instances.

uCalc's default instance model offers a pragmatic middle ground, providing the convenience of a static/singleton approach while retaining the flexibility of having multiple, swappable configurations.

**Examples:**

### Example ID: 366

**Description:** A simple check to see which uCalc instance is the default.

**Code:**
```pseudocode
// The implicit 'uc' object is not the default upon creation.
wl("Is 'uc' the default instance? ", bool(uc.@IsDefault()))

// Create a new uCalc instance. It also won't be the default.
New(uCalc, myCalc);
wl("Is 'myCalc' the default instance? ", bool(myCalc.@IsDefault()));

// Let's get the actual default instance and check it.
var(uCalc, defaultInstance) = uCalc::@DefaultInstance();
wl("Is the instance from uCalc.DefaultInstance the default? ", bool(defaultInstance.@IsDefault()))
```

**Output:**
```
Is 'uc' the default instance? False
Is 'myCalc' the default instance? False
Is the instance from uCalc.DefaultInstance the default? True
```

---

### Example ID: 367

**Description:** Manage different parser configurations by switching the default instance.

**Code:**
```pseudocode
// Setup a "Scientific" configuration
New(uCalc, scientificCalc)
scientificCalc.DefineFunction("sqrt(x) = x^0.5");
scientificCalc.DefineVariable("pi = 3.14159");

// Setup a "Financial" configuration
New(uCalc, financialCalc)
financialCalc.DefineFunction("tax(amount, rate) = amount * (rate/100)");

// Set the scientific calculator as the default
scientificCalc.@IsDefault(true);
wl("Current default is scientific? ", bool(scientificCalc.@IsDefault()))

// Components that rely on the default instance now use the scientific setup.
var(uCalc::Expression, expr1) = "2 * pi";
wl("2 * pi = ", expr1.Evaluate())

// Now, switch the default to the financial calculator
financialCalc.@IsDefault(true);
wl("Current default is scientific? ", bool(scientificCalc.@IsDefault())) // Should be false now
wl("Current default is financial? ", bool(financialCalc.@IsDefault()))

// New components will use the financial setup.
var(uCalc::Expression, expr2) = "tax(50000, 20)";
wl("Tax on 50000 at 20% = ", expr2.Evaluate())
```

**Output:**
```
Current default is scientific? True
2 * pi = 6.28318
Current default is scientific? False
Current default is financial? True
Tax on 50000 at 20% = 10000
```

---

### Example ID: 368

**Description:** Internal Test: Verify the stack-like behavior of the default instance list.

**Code:**
```pseudocode
// Define a variable in the original default to distinguish it.
// Note: This variable won't exist in the implicit 'uc' instance.
uCalc::@DefaultInstance().DefineVariable("id='Original'");
wl("Initial default: ", uCalc::@DefaultInstance().EvalStr("id"));

New(uCalc, ucA);
ucA.DefineVariable("id='A'");
ucA.@IsDefault(true); // Default stack: [Original, A]
wl("Current default: ", uCalc::@DefaultInstance().EvalStr("id"));

New(uCalc, ucB);
ucB.DefineVariable("id='B'");
ucB.@IsDefault(true); // Default stack: [Original, A, B]
wl("Current default: ", uCalc::@DefaultInstance().EvalStr("id"));

New(uCalc, ucC);
ucC.DefineVariable("id='C'");
ucC.@IsDefault(true); // Default stack: [Original, A, B, C]
wl("Current default: ", uCalc::@DefaultInstance().EvalStr("id"));

wl("--- Unsetting instances ---");
// Unset B. The default should remain C.
ucB.@IsDefault(false);
wl("After unsetting B, current default: ", uCalc::@DefaultInstance().EvalStr("id"));

// Unset C. The default should revert to A.
ucC.@IsDefault(false);
wl("After unsetting C, current default: ", uCalc::@DefaultInstance().EvalStr("id"));

// Unset A. Reverts to the original default.
ucA.@IsDefault(false);
wl("After unsetting A, current default: ", uCalc::@DefaultInstance().EvalStr("id"));
```

**Output:**
```
Initial default: Original
Current default: A
Current default: B
Current default: C
--- Unsetting instances ---
After unsetting B, current default: C
After unsetting C, current default: A
After unsetting A, current default: Original
```

---

### Example ID: 75

**Description:** Checking if a uCalc object is the default with IsDefault

**Code:**
```pseudocode
var Status = uc.DefineVariable("Status As Bool");
wl(bool(Status.ValueBool()))

New(uCalc, MyuCalc)

Status.ValueBool(MyuCalc.@IsDefault());
wl(uc.EvalStr("$'MyuCalc is the current default? {Status}'"))

MyuCalc.@IsDefault(true);
Status.ValueBool(MyuCalc.@IsDefault());

wl(uc.EvalStr("$'MyuCalc is the current default? {Status}'"))
```

**Output:**
```
False
MyuCalc is the current default? false
MyuCalc is the current default? true
```

---

### Example ID: 76

**Description:** Setting uCalc default with uCalc.IsDefault()

**Code:**
```pseudocode
New(uCalc, uCalcA)
New(uCalc, uCalcB)
New(uCalc, uCalcC)

uCalcA.DefineVariable("MyVar = 'I was cloned from uCalcA'");
uCalcB.DefineVariable("MyVar = 'I was cloned from uCalcB'");
uCalcC.DefineVariable("MyVar = 'I was cloned from uCalcC'");

uCalcA.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("MyVar"))

uCalcB.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("MyVar"))

uCalcC.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("MyVar"))

wl("---")

// Now unsetting uCalc objects as default
uCalcC.@IsDefault(false);
wl(uCalc::@DefaultInstance().EvalStr("MyVar"))

uCalcB.@IsDefault(false);
wl(uCalc::@DefaultInstance().EvalStr("MyVar"))

uCalcA.@IsDefault(false);
wl(uCalc::@DefaultInstance().EvalStr("MyVar"))


```

**Output:**
```
I was cloned from uCalcA
I was cloned from uCalcB
I was cloned from uCalcC
---
I was cloned from uCalcB
I was cloned from uCalcA
Undefined identifier
```

---

### Example ID: 60

**Description:** Using the default uCalc.GetDefaultInstance() instance

**Code:**
```pseudocode
uCalc::@DefaultInstance().DefineVariable("instance = 'original default'");

New(uCalc, ucB)
New(uCalc, ucC)
New(uCalc, ucD)

ucB.Eval("instance = 'B derived from -> ' + instance");
ucC.Eval("instance = 'C derived from -> ' + instance");
ucD.Eval("instance = 'D derived from -> ' + instance");

ucC.@IsDefault(true);

New(uCalc, ucE)
ucE.Eval("instance = 'E derived from -> ' + instance");

wl(uCalc::@DefaultInstance().EvalStr("'Default: ' + instance"))

wl(uc.EvalStr("instance")) // Note: this is not, nor was the default
wl(ucB.EvalStr("instance"))
wl(ucC.EvalStr("instance"))
wl(ucD.EvalStr("instance"))
wl(ucE.EvalStr("instance"))

// Note: Unlike this example, it is generally best to always
// create a new instance first and then set it as default
```

**Output:**
```
Default: C derived from -> original default
Undefined identifier
B derived from -> original default
C derived from -> original default
D derived from -> original default
E derived from -> C derived from -> original default
```

---

### Example ID: 61

**Description:** Setting default uCalc instance with uCalc.IsDefault(); also clearing all uCalc instances from default list

**Code:**
```pseudocode
uCalc::@DefaultInstance().DefineVariable("val = 'original default'");
wl(uCalc::@DefaultInstance().EvalStr("val"))

uc.DefineVariable("val = 'uc'");
uc.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("val"))

New(uCalc, ucB)
ucB.DefineVariable("val = 'ucB'");
ucB.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("val"))

New(uCalc, ucC)
ucC.DefineVariable("val = 'ucC'");
ucC.@IsDefault(true);
wl(uCalc::@DefaultInstance().EvalStr("val"))

uCalc::DefaultClear();

// The original unnamed default instance is reset so user variable val no longer exists
wl(uCalc::@DefaultInstance().EvalStr("val"))

// The other instances are removed from Default list but remain active
wl(uc.EvalStr("val"))
wl(ucB.EvalStr("val"))
wl(ucC.EvalStr("val"))
```

**Output:**
```
original default
uc
ucB
ucC
Undefined identifier
uc
ucB
ucC
```

---

### Example ID: 79

**Description:** Defining uCalc Strings and  Expressions in the default uCalc object space

**Code:**
```pseudocode
new(uCalc, ucB)

uc.DefineVariable("x = 111");
ucB.DefineVariable("x = 222");

wl("--- using 'uc' as default ---")
uc.@IsDefault(true);

var(uCalc::String, MyString) = "The variable value is: x";
wl(MyString.Replace("x", "{@Eval: x}"))

var(uCalc::Expression, MyExpression) = "x * 1000";
wl(MyExpression.Evaluate())

New(uCalc::Transformer, MyTransformer)
MyTransformer.@Text("Value is: x");
MyTransformer.FromTo("x", "{@Eval: x}");
wl(MyTransformer.Transform())


wl("--- using 'ucB' as default ---")
ucB.@IsDefault(true);

var(uCalc::String, MyStringB) = "The variable value is: x";
wl(MyStringB.Replace("x", "{@Eval: x}"))

var(uCalc::Expression, MyExpressionB) = "x * 1000";
wl(MyExpressionB.Evaluate())

New(uCalc::Transformer, MyTransformerB)
MyTransformerB.Str("Value is: x");
MyTransformerB.FromTo("x", "{@Eval: x}");
wl(MyTransformerB.Transform())

```

**Output:**
```
--- using 'uc' as default ---
The variable value is: 111
111000
Value is: 111
--- using 'ucB' as default ---
The variable value is: 222
222000
Value is: 222
```

---

### Example ID: 271

**Description:** Manage separate parser contexts for different application modules.

**Code:**
```pseudocode
// --- Main Application Context ---
// Starting with the 'uc' object as the initial default.
uCalc::@DefaultInstance().DefineConstant("PI = 3.14159");
wl("Initial Count: ", uCalc::@DefaultCount())

// --- A Plugin needs a temporary, isolated context ---
NewUsing(uCalc, moduleCalc)
moduleCalc.@IsDefault(true); // Push the new instance onto the stack.
wl("Count after module pushes new default: ", uCalc::@DefaultCount())

// The module's context is now active.
// uCalc::DefaultInstance() would now return 'moduleCalc'.
End Using

// When 'moduleCalc' goes out of scope, it's destroyed and automatically
// removed from the stack, restoring the previous default.

wl("Count after module instance is disposed: ", uCalc::@DefaultCount())

// Verify the original default instance is active again.
var result = uCalc::@DefaultInstance().EvalStr("PI");
wl("Original context restored. PI = ", result)
```

**Output:**
```
Initial Count: 1
Count after module pushes new default: 2
Count after module instance is disposed: 1
Original context restored. PI = 3.14159
```

---

### Example ID: 161

**Description:** "using" (C#) and Owned (C++) for auto-releasing uCalc object

**Code:**
```pseudocode

// In C# and VB you should use "using".
// In C++ you can flag a uCalc object for
// auto-release with Owned(), or by setting
// the last parameter of the constructor to true.

uc.@IsDefault(true); // Set uc as the default uCalc object
uCalc::@DefaultInstance().DefineVariable("Value = 'Original uc object'");
wl(uCalc::@DefaultInstance().EvalStr("Value")) // Outputs: Original uc object

[NotCpp]// Use "using" so that the object is auto-released when it it goes out of scope[/NotCpp]
   NewUsing(uCalc, uCalcTemp) [cpp]// Make uCalcTemp owned so it reverts back to uc when uCalcTemp goes out of scope[/cpp]
   uCalcTemp.@IsDefault(true); // Set uCalcTemp as the default uCalc object
   uCalc::@DefaultInstance().DefineVariable("Value = 'uCalcTemp object'");
   wl(uCalc::@DefaultInstance().EvalStr("Value")) // uCalcTemp object
End Using
// uCalcTemp goes out of scope here, and the default uCalc object reverts back to uc

wl(uCalc::@DefaultInstance().EvalStr("Value")) // Original uc object

[c]{!Eval: Chr(123)}[/c][vb]If True Then[/vb]
   [cs]/*using*/[/cs] New(uCalc, uCalcSticky) // remains the default even after going out of scope
   uCalcSticky.@IsDefault(true); // Set uCalcSticky as the default uCalc object
   uCalc::@DefaultInstance().DefineVariable("Value = 'uCalcSticky object'");
   wl(uCalc::@DefaultInstance().EvalStr("Value")) // Outputs: uCalcSticky object
[c]{!Eval: Chr(125)}[/c][vb]End If[/vb]    // The uCalcSticky object itself goes out of scope here, but internally it remains the default uCalc object

wl(uCalc::@DefaultInstance().EvalStr("Value"))
```

**Output:**
```
Original uc object
uCalcTemp object
Original uc object
uCalcSticky object
uCalcSticky object
```

---

---

## ItemOf - ID: 59
/doc/reference/classes/ucalc/itemof/

---

## ItemOf(int64, int, string, bool) - ID: 60
/doc/reference/classes/ucalc/itemof/itemof-int64,-int,-string,-bool/

**Description:** Retrieves an item by iterating through a filtered list of all symbols defined within the uCalc instance.

**Syntax:** ItemOf(int64, int, string, bool)
**Parameters:**
properties - int64 - A bitmask of properties used to filter the items, created with Properties(). Use 0 to include all items.
index - int - The zero-based index of the item to retrieve from the filtered list.
dataTypeName - string [default = ""] - An optional string to filter items by their data type name (e.g., 'String', 'Int32').
includeOverloads - bool [default = false] - If true, includes all overloads of a symbol in the list. If false (default), only the primary definition for a given name is included.
**Return:** Item - The Item object at the specified index in the filtered list. Returns an empty item (where `IsEmpty()` is true) if the index is out of bounds or no items match the filter.
**Remarks:**

The `ItemOf` method provides a powerful way to query and iterate through all symbols (functions, variables, operators, etc.) defined within a uCalc instance. By specifying filter criteria, you can create a virtual list of matching items and retrieve a specific one by its index.

This is one of two overloads for `ItemOf`. This version iterates through a list of items based on their properties, while the [other overload](/Reference/uCalc/uCalc/ItemOf/ItemOf(string_view,int64_t,size_t)) finds a specific item by name.

### 🔍 Filtering by Property

The `properties` parameter accepts a bitmask that specifies which types of items to include. This mask is typically generated using one of two approaches:

*   **Single Property**: Pass a single member of the [ItemIs](/Reference/Enums/ItemIs) enum (e.g., `ItemIs::Function` to find only functions).
*   **Multiple Properties**: Use the static [Properties()](/Reference/uCalc/uCalc/Properties) method to combine multiple `ItemIs` flags. You can specify whether to match **any** (`ItemIs::SelectAny`, default) or **all** (`ItemIs::SelectAll`) of the provided properties.

Use `0` to create a list of all items without any property filtering.

### 🔢 Iteration and Indexing

The `index` parameter is a zero-based index into the filtered list. To iterate through all matching items, start at index `0` and increment until `ItemOf` returns an empty item (which you can check with `item.IsEmpty()` or `item.IsProperty(ItemIs::NotFound)`).

### ⛓️ Handling Overloads

It's possible for multiple items (like overloaded functions or operators) to share the same name. The `includeOverloads` parameter controls how these are handled:

*   `false` (default): Only the first or primary item for a given name is included in the list.
*   `true`: All overloads are included as separate entries in the list.

### Comparative Analysis: Why uCalc?

In languages like C# or Java, runtime introspection is typically handled by a **Reflection API**. While extremely powerful, reflection can be complex to use and often carries a performance penalty.

*   **vs. Reflection:** uCalc's `ItemOf` provides a more focused and efficient alternative. It is designed specifically for inspecting the uCalc engine's internal state. Instead of navigating complex `Type` and `MemberInfo` objects, you get a direct, streamlined `Item` object that contains all the relevant metadata (name, data type, precedence, etc.) for that symbol.

This makes `ItemOf` the ideal tool for building dynamic applications on top of uCalc, such as:
*   **Debuggers and Inspectors**: Programmatically list all defined variables and their current values.
*   **Dynamic UI**: Populate an autocomplete or IntelliSense list with available functions and their parameters.
*   **Documentation Generators**: Automatically generate documentation for a library of custom uCalc functions.

**Examples:**

### Example ID: 77

**Description:** ItemOf based on properties

**Code:**
```pseudocode
New(uCalc::Item, Item)
var x = 0;

// Lists the first few funcions defined in uCalc
// For the full list, loop until Item.IsEmpty() or while Item.NotEmpty()
for (x = 0 To 15)
   Item = uc.ItemOf(ItemIs::Function, x);
   wl(Item.@Name())
end for
wl("---")

// List only Prefix and Postfix (operators)
x = 0;
do
   Item = uc.ItemOf(uCalc::Properties(ItemIs::Prefix, ItemIs::Postfix), x);
   x = x + 1;
   wl(Item.@Name())
loop while (Item.NotEmpty())
```

**Output:**
```
abs
acos
acosh
addptr
addressof
anytype
append
append_copy
arg
argcount
asc
asin
asinh
atan
atan2
atanh
---
!
+
-
not
~
```

---

---

## ItemOf(string, int64, int) - ID: 61
/doc/reference/classes/ucalc/itemof/itemof-string,-int64,-int/

**Description:** Retrieves the uCalc.Item object for a symbol by its name, optionally filtered by properties to disambiguate overloads.

**Syntax:** ItemOf(string, int64, int)
**Parameters:**
itemName - string - Name of the uCalc.Item object to retrieve.
properties - int64 [default = 0] - An optional bitmask of ItemIs properties to filter the results, useful for disambiguating items that share the same name.
nthOverload - int [default = 0] - The zero-based index of the overload to select if multiple items match the name and properties.
**Return:** Item - The Item object matching the criteria. If no match is found, returns an empty Item that can be checked with `IsProperty(ItemIs::NotFound)` or `NotEmpty()`.
**Remarks:**

## 🔍 Retrieving Symbols by Name

The `ItemOf` method is the primary tool for retrieving a handle to any defined symbol (a variable, function, operator, etc.) by its name. This allows for runtime introspection and dynamic interaction with the uCalc engine's state.

If the requested item does not exist, the method returns an "empty" `Item` object. You can check for this condition using [pseudocode]`item.IsProperty(ItemIs::NotFound)` or, more conveniently, [pseudocode]`item.NotEmpty()`. The `Name()` of an empty item is an empty string.

---
## 🎯 Disambiguation with Properties

In uCalc, multiple symbols can share the same name. This is common with **overloaded functions** or with operators that have different forms (e.g., the unary prefix `-` vs. the binary infix `-`).

To resolve this ambiguity, you can provide an optional `properties` argument. This argument is a bitmask created by combining members of the [`ItemIs`](/Reference/Enums/ItemIs) enumeration.

*   **Single Property**: Pass a single `ItemIs` member to filter by that property. For example, `ItemIs::Prefix` will select the unary version of an operator.
*   **Multiple Properties**: To combine multiple properties, use the static [`Properties()`](/Reference/uCalc/uCalc/Properties) helper method.

```pseudocode
// Get the INFIX version of the '-' operator
var infix_minus = uc.ItemOf("-", ItemIs::Infix);

// Get the PREFIX version of the '-' operator
var prefix_minus = uc.ItemOf("-", ItemIs::Prefix);
```

---
## 📚 Handling Overloads

If multiple items match the given name and properties (e.g., several functions named `MyFunc` with different parameter counts), `ItemOf` returns the first one found. You can access subsequent overloads using two methods:

1.  **`nthOverload` Parameter**: Specify the zero-based index of the overload you want.
2.  **`NextOverload()` Method**: Call [pseudocode]`.NextOverload()` on a returned `Item` object to get the next item in the chain.

---
## 💡 Comparative Analysis: `ItemOf` vs. Reflection

`ItemOf` is conceptually similar to reflection mechanisms in other languages, such as C#'s `Type.GetMethod()` or Java's `Class.getMethod()`.

**Traditional Reflection (C# Example):**
```csharp
MethodInfo method = myType.GetMethod("MyMethod", new Type[] { typeof(int) });
if (method != null)
{
    // Found it
}
```

While powerful, reflection APIs are often complex, verbose, and can be slow.

**The uCalc Advantage with `ItemOf`:**
*   **Simplicity**: `ItemOf` uses a simple string name and optional property flags, making it more concise and readable.
*   **Integrated Properties**: Filtering by properties like `ItemIs::Function` or `ItemIs::Operator` is a natural, built-in part of the uCalc object model, not a separate, complex query system.
*   **Performance**: As an integrated feature, `ItemOf` is optimized for the uCalc engine's internal data structures and is generally faster than general-purpose reflection.
*   **Dynamic Nature**: Because uCalc symbols are defined at runtime, `ItemOf` is the essential tool for interacting with a constantly evolving symbol table, a scenario where compile-time reflection is not applicable.

This makes `ItemOf` a more ergonomic and efficient tool for the specific task of runtime symbol introspection within the uCalc ecosystem.

**Examples:**

### Example ID: 374

**Description:** A simple lookup to retrieve a defined variable by its name and display its value.

**Code:**
```pseudocode
uc.DefineVariable("MyVar = 123");

// Retrieve the item by name
var item = uc.ItemOf("MyVar");

// Check if the item was found and print its value
if (item.NotEmpty())
    wl("Value of MyVar is: ", item.Value())
end if
```

**Output:**
```
Value of MyVar is: 123
```

---

### Example ID: 375

**Description:** Use the 'properties' parameter to disambiguate between the infix (binary) and prefix (unary) versions of the minus '-' operator.

**Code:**
```pseudocode
// Get the infix (subtraction) operator and check its operand count
var infixOp = uc.ItemOf("-", [c]ItemIs::Infix[/c][vb]uCalc.Properties(ItemIs::Infix)[/vb]);
w("Infix '-' operator has ", infixOp.@Count())
wl(" operand(s).")

// Get the prefix (negation) operator
var prefixOp = uc.ItemOf("-", [c]ItemIs::Prefix[/c][vb]uCalc.Properties(ItemIs::Prefix)[/vb]);
w("Prefix '-' operator has ", prefixOp.@Count())
wl(" operand(s).")
```

**Output:**
```
Infix '-' operator has 2 operand(s).
Prefix '-' operator has 1 operand(s).
```

---

### Example ID: 51

**Description:** Returning data type names for the different definitions of the "+" operator

**Code:**
```pseudocode
var PlusOperator = uc.ItemOf("+");

while (PlusOperator.NotEmpty())
   wl("Def: " + PlusOperator.@Text() + "  Type: " + PlusOperator.@DataType().@Name())
   PlusOperator = PlusOperator.NextOverload();
end while
```

**Output:**
```
Def: Operator: 70 +{x}  Type: double
Def: Operator: 50 {x} + {y}  Type: double
Def: Operator: 50 {x As Int} + {y As Int} As Int  Type: int
Def: Operator: 50 {x As String} + {y As String} As String  Type: string
Def: Operator: 50 {x As Complex} + {y As Complex} As Complex  Type: complex
Def: Operator: 50 {ByHandle x As AnyType Ptr} + {y As Int} As SameTypeAs:0 Ptr  Type: sametypeas:ptr
Def: Operator: 50 {ByHandle x As AnyType} + {ByHandle y As String} As String  Type: string
Def: Operator: 50 {ByHandle x As String} + {ByHandle y As AnyType} As String  Type: string
```

---

### Example ID: 72

**Description:** Changing accepted tokens with ItemOf().Regex or ExpressionTokens().Token

**Code:**
```pseudocode
// (See alternate version of this example using ExpressionTokens instead of ItemOf)

// In this section underscore, _, and numeric digits
// are accepted as part of alphanumeric tokens
uc.DefineVariable("My_Variable = 111");
wl(uc.@Error().@Message())
uc.DefineVariable("Variable123 = 222");
wl(uc.@Error().@Message())

wl(uc.ItemOf("_Token_Alphanumeric").@Regex())
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
wl("---")

// Now we no longer want underscore, _, or numeric digits
// to be accepted in alphanumeric tokens; only A-Z
uc.ItemOf("_Token_Alphanumeric").@Regex("[a-zA-Z]+");

uc.DefineVariable("Other_Variable = 333");
wl(uc.@Error().@Message())
uc.DefineVariable("OtherVariable123 = 444");
wl(uc.@Error().@Message())

wl(uc.EvalStr("Other_Variable"))
wl(uc.EvalStr("OtherVariable123 "))
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
wl("---")

//
// We restore the alphanumeric regex to support _ and numbers again
// Note: My_Variable and Variable123 remained; they were simply inaccessible
// Also: We can't use the commented line below because it has the underscore, _,
// character that we had removed.
// uc.ItemOf("_token_alphanumeric").Regex("[a-zA-Z_][a-zA-Z0-9_]*");
uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex("[a-zA-Z_][a-zA-Z0-9_]*");
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
```

**Output:**
```
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222
```

---

### Example ID: 45

**Description:** ItemOf selection between infix version of - (minus) operator and unary prefix version with Properties

**Code:**
```pseudocode

// Returns number of operands for the given operators
wl(uc.ItemOf("-", uCalc::Properties(ItemIs::Infix)).@Count())
wl(uc.ItemOf("-", uCalc::Properties(ItemIs::Prefix)).@Count())

[C]// You can pass one property directly in C++ and C#, but not VB
wl(uc.ItemOf("-", ItemIs::Infix).@Count())
wl(uc.ItemOf("-", ItemIs::Prefix).@Count())[/C]
[VB]
// You can pass one property directly in C++ and C#, but not VB
wl(2) // C++ and C# only: uc.ItemOf("-", ItemIs::Infix).@Count();
wl(1) // C++ and C# only: uc.ItemOf("-", ItemIs::Prefix).@Count();[/VB]
```

**Output:**
```
2
1
2
1
```

---

### Example ID: 17

**Description:** DefineVariable examples

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var MyInt = uc.DefineVariable("MyInt As Int");
var MyStr = uc.DefineVariable("MyStr As String");
uc.DefineVariable("OtherStr = 'string type inferred'");
uc.DefineVariable("MyInt16 = Int16(100/3)"); // type inferred
uc.DefineVariable("MyBool = True"); // type inferred
uc.DefineVariable("MyComplex = 3 + 4*#i"); // type inferred

MyVar.Value(123);
MyInt.ValueInt32(456);
MyStr.ValueStr("This is a test");

wl("MyVar = " + uc.EvalStr("MyVar"))
wl("MyInt = " + uc.EvalStr("MyInt"))
wl("MyStr = " + uc.EvalStr("MyStr"))
wl("OtherStr = " + uc.EvalStr("OtherStr"))
wl("MyInt16 = " + uc.EvalStr("MyInt16"))
wl("MyBool = " + uc.EvalStr("MyBool"))
wl("MyComplex = " + uc.EvalStr("MyComplex"))
wl("---")
wl(MyVar.Value())
wl(MyInt.ValueInt32())
wl(MyStr.ValueStr())
wl("---")
wl(uc.ItemOf("MyVar").@DataType().@Name())
wl(uc.ItemOf("MyInt").@DataType().@Name())
wl(uc.ItemOf("MyStr").@DataType().@Name())
wl(uc.ItemOf("OtherStr").@DataType().@Name())
wl(uc.ItemOf("MyInt16").@DataType().@Name())
wl(uc.ItemOf("MyBool").@DataType().@Name())
wl("---")

var Expression = "x^2 * 10";
var VarX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse(Expression);

w("Expression = ")
wl(Expression)
for (int x = 1 to 10)
   VarX.Value(x); // In C++ you can skip this by passing &x to DefineVariable
   wl("x = " + VarX.ValueStr() + "  Result = " + ParsedExpr.EvaluateStr())
end for

ParsedExpr.Release();
VarX.Release();
```

**Output:**
```
MyVar = 123
MyInt = 456
MyStr = This is a test
OtherStr = string type inferred
MyInt16 = 33
MyBool = true
MyComplex = 3+4i
---
123
456
This is a test
---
double
int
string
string
int16
bool
---
Expression = x^2 * 10
x = 1  Result = 10
x = 2  Result = 40
x = 3  Result = 90
x = 4  Result = 160
x = 5  Result = 250
x = 6  Result = 360
x = 7  Result = 490
x = 8  Result = 640
x = 9  Result = 810
x = 10  Result = 1000
```

---

---

## Items = [ItemsAccessor] - ID: 854
/doc/reference/classes/ucalc/items-=-[itemsaccessor]/

**Description:** Provides access to the collection of all defined symbols (items) for runtime introspection and dynamic analysis.

**Remarks:**

# 🧐 Introspection: The Items Property

The `Items` property is uCalc's primary gateway for runtime introspection. It provides access to the complete collection of all symbols—known as [Items](/Reference/uCalcBase/Item/Constructor)—that have been defined within a `uCalc` instance.

An "[Item](/Reference/uCalcBase/Item/Constructor)" is the fundamental, universal object for any symbol in uCalc, including:
*   Variables created with [DefineVariable()](/Reference/uCalcBase/uCalc/DefineVariable)
*   Functions created with [DefineFunction()](/Reference/uCalcBase/uCalc/DefineFunction)
*   Operators created with [DefineOperator()](/Reference/uCalcBase/uCalc/DefineOperator)
*   Data Types, Aliases, and more.

This property returns an `ItemsAccessor` object, which is a powerful, iterable, and queryable collection, essential for debugging, creating dynamic user interfaces, or building tools that analyze the state of the uCalc engine.

---
## ⚙️ Accessing and Filtering Items

The `ItemsAccessor` supports direct iteration and indexed filtering, providing a flexible way to query the engine's symbol table.

### 1. Iterating All Items
You can use a `foreach` loop to iterate over every symbol defined in the instance.

```pseudocode
// Loop through every defined item and print its name
foreach(var item in uc.@Items())
   wl(item.@Name());
end foreach
```

### 2. Filtering by Property or Name
The collection can be filtered using an indexer `[]` with a property from the [ItemIs](/Reference/Enums/ItemIs) enum or a string name. The result of a filter is another iterable collection.

```pseudocode
// Get a list containing only defined functions
var functionList = uc.@Items()[ItemIs::Function];
foreach(var func in functionList)
    wl(func.@Name());
end foreach

// Get all overloads of the '+' operator
var plusOverloads = uc.@Items()["+"];
foreach(var op in plusOverloads)
    wl(op.@Text());
end foreach
```

### 3. Advanced Filtering with `Properties()`
For more complex queries, you can combine multiple `ItemIs` flags using the static [Properties()](/Reference/uCalcBase/uCalc/Properties) method. This allows you to find items that match **all** (`ItemIs::SelectAll`) or **any** (`ItemIs::SelectAny`) of a set of properties.

```pseudocode
// Find all items that are BOTH an Operator AND Infix
var infixOperators = uc.@Items()[
    uCalc.Properties(ItemIs::SelectAll, ItemIs::Operator, ItemIs::Infix)
];
```
---
## 💡 Why uCalc? (Comparative Analysis)

`Items` provides functionality similar to reflection or introspection in other programming environments, but it is tailored specifically for the uCalc engine.

*   **vs. .NET/Java Reflection**: Reflection is a powerful, general-purpose system for inspecting assemblies and types at runtime. However, it can be complex and verbose. The `@Items` property provides a much simpler, higher-level API focused exclusively on the symbols within the uCalc engine, making it easier and more efficient for its intended purpose.

*   **vs. Python's `dir()` or `globals()`**: In dynamic languages, introspection is a core feature. `@Items` is conceptually similar to these tools but provides a more structured, property-based filtering mechanism out of the box, whereas in Python you might need to combine `dir()` with `isinstance()` checks in a loop.

**Examples:**

### Example ID: 384

**Description:** Lists the names of all user-defined and built-in functions.

**Code:**
```pseudocode
// Note: Some items in this list (like bool, or int*) appear more than once or out of chronological
// order because they are aliases (like bool, which is also an alias for boolean)
wl("Defined Functions:")
foreach(var item in uc.GetItems(ItemIs::Function))
   wl(" - ", item.@Name())
end foreach
```

**Output:**
```
Defined Functions:
 - abs
 - acos
 - acosh
 - addptr
 - addressof
 - anytype
 - append
 - append_copy
 - arg
 - argcount
 - asc
 - asin
 - asinh
 - atan
 - atan2
 - atanh
 - back
 - baseconvert
 - bin
 - bool
 - bool
 - int8u
 - c_str
 - cbrt
 - ceil
 - chr
 - clear
 - compare
 - complex
 - conj
 - contains
 - copysign
 - cos
 - cosh
 - define
 - doloop
 - double
 - endswith
 - erase
 - erase_copy
 - erf
 - erfc
 - error
 - eval
 - evalstr
 - evaluate
 - evaluateint
 - evaluatestr
 - exp
 - exp2
 - expm1
 - exprptr
 - fabs
 - fdim
 - file
 - filesize
 - fill
 - find_first_not_of
 - find_first_of
 - find_last_not_of
 - find_last_of
 - single
 - floor
 - fmax
 - fmin
 - fmod
 - forloop
 - format
 - fpclassify
 - frac
 - frexp
 - fromto
 - goto
 - hex
 - hypot
 - iif
 - ilogb
 - imag
 - indexof
 - inf
 - insert
 - insert_copy
 - int
 - int16
 - int16u
 - int
 - int32u
 - int64
 - int64u
 - int8
 - int8u
 - int
 - isfinite
 - isinf
 - isnan
 - isnormal
 - lastindexof
 - lcase
 - ldexp
 - length
 - lgamma
 - llrint
 - llround
 - log
 - log10
 - log1p
 - log2
 - logb
 - lrint
 - lround
 - ltrim
 - max
 - min
 - modf
 - nan
 - nearbyint
 - nextafter
 - nexttoward
 - norm
 - oct
 - omnitype
 - padleft
 - padright
 - parse
 - pointer
 - polar
 - pop
 - pow
 - precedence
 - proj
 - push
 - rand
 - randfromsameseed
 - randomnumber
 - randomseed
 - real
 - remainder
 - remquo
 - repeat
 - replace
 - replace_copy
 - reset
 - rint
 - round
 - rtrim
 - sametypeas
 - scalbln
 - scalbn
 - setvar
 - sgn
 - signbit
 - sin
 - single
 - sinh
 - size_t
 - sizeof
 - sort
 - sqr
 - sqrt
 - startswith
 - str
 - string
 - substr
 - subtractptr
 - swap
 - tan
 - tanh
 - tgamma
 - trim
 - trunc
 - ucalcinstance
 - ucase
 - valueat
 - valueattype
 - void
```

---

### Example ID: 107

**Description:** uCalc.Items

**Code:**
```pseudocode
// Note: Some items in this list (like bool, or int*) appear more than once or out of chronological
// order because they are aliases (like bool, which is also an alias for boolean)
foreach(var item in uc.@Items())
   wl(item.@Name())
end foreach
```

**Output:**
```
!
%
&
&&
*
+
,
-
/
<
<<
<=
<>
=
==
>
>=
>>
\
^
_enduserformattedoutput
_newline
_token_alphanumeric
_token_argseparator
_token_binaryhexoctalnotation
_token_catchall
_token_catchall_utf8_other
_token_curlybrace
_token_curlybrace_close
_token_floatnumber
_token_imaginaryunit
_token_line
_token_memberaccess
_token_newline
_token_parenthesis
_token_parenthesis_close
_token_punctuation
_token_quotechar
_token_quotechar_double
_token_quotechar_single
_token_quotechar_tripledouble
_token_reducible
_token_reducible2
_token_semicolon
_token_squarebracket
_token_squarebracket_close
_token_string_doublequoted
_token_string_singlequoted
_token_string_tripledoublequoted
_token_stringinterpolationquote
_token_variableargs
_token_whitespace
_ucalc_lib_is32
_ucalc_lib_is64
_ucalc_lib_release_timestamp
_ucalc_lib_version
abs
acos
acosh
addptr
addressof
and
andalso
anytype
append
append_copy
arg
argcount
asc
asin
asinh
atan
atan2
atanh
back
baseconvert
bin
bitand
bitor
bool
bool
int8u
c_str
cbrt
ceil
chr
clear
compare
complex
conj
contains
copysign
cos
cosh
define
doloop
double
endswith
erase
erase_copy
erf
erfc
error
eval
evalstr
evaluate
evaluateint
evaluatestr
exp
exp2
expm1
exprptr
fabs
false
fdim
file
filesize
fill
find_first_not_of
find_first_of
find_last_not_of
find_last_of
single
floor
fmax
fmin
fmod
forloop
format
fpclassify
frac
frexp
fromto
goto
hex
hypot
iif
ilogb
imag
indexof
inf
insert
insert_copy
int
int16
int16u
int
int32u
int64
int64u
int8
int8u
int
isfinite
isinf
isnan
isnormal
lastindexof
lastrandomnumber
lcase
ldexp
length
lgamma
llrint
llround
log
log10
log1p
log2
logb
lrint
lround
ltrim
max
min
mod
modf
nan
nearbyint
nextafter
nexttoward
norm
not
oct
omnitype
or
orelse
padleft
padright
parse
pointer
polar
pop
pow
precedence
proj
push
rand
randfromsameseed
randomnumber
randomseed
real
remainder
remquo
repeat
replace
replace_copy
reset
rint
round
rtrim
sametypeas
scalbln
scalbn
setvar
sgn
signbit
sin
single
sinh
size_t
sizeof
sort
sqr
sqrt
startswith
str
string
substr
subtractptr
swap
tan
tanh
tgamma
trim
true
trunc
ucalcinstance
ucase
valueat
valueattype
void
xor
|
||
~
```

---

### Example ID: 108

**Description:** ListOfItem with name / property

**Code:**
```pseudocode
wl("Items with the Prefix property")
wl("------------------------------")
foreach(var item in uc.GetItems(ItemIs::Prefix))
   wl(item.@Name())
end foreach

wl("")
wl("Different versions of the + operator")
wl("------------------------------------")
foreach(var item in uc.GetItems("+"))
   wl(item.@Text())
end foreach
```

**Output:**
```
Items with the Prefix property
------------------------------
!
+
-
not
~

Different versions of the + operator
------------------------------------
Operator: 70 +{x}
Operator: 50 {x} + {y}
Operator: 50 {x As Int} + {y As Int} As Int
Operator: 50 {x As String} + {y As String} As String
Operator: 50 {x As Complex} + {y As Complex} As Complex
Operator: 50 {ByHandle x As AnyType Ptr} + {y As Int} As SameTypeAs:0 Ptr
Operator: 50 {ByHandle x As AnyType} + {ByHandle y As String} As String
Operator: 50 {ByHandle x As String} + {ByHandle y As AnyType} As String
```

---

---

## MemoryIndex = [int] - ID: 602
/doc/reference/classes/ucalc/memoryindex-=-[int]/

**Description:** Returns a stable, session-unique integer that identifies a uCalc object, primarily for diagnostics and tracking object lifetimes.

**Remarks:**

The `MemoryIndex` method returns a predictable, sequential integer that uniquely identifies a uCalc object for the duration of an application session. It is an essential tool for debugging, logging, and understanding object lifetimes.

Unlike a `Handle`, which is a volatile, low-level memory address, the `MemoryIndex` is a stable, high-level identifier. It is assigned sequentially when an object is created.

### `MemoryIndex` vs. `Handle`

Understanding the difference between `MemoryIndex` and a `Handle` is crucial for effective diagnostics.

| Feature | `MemoryIndex` | `Handle` |
| :--- | :--- | :--- |
| **Stability** | **Stable & Predictable**. Incremental and consistent within a session. | **Volatile**. A raw memory address that changes between application runs. |
| **Uniqueness** | Unique for an object's lifetime. Can be **recycled** after release. | Guaranteed unique for the object's lifetime. Not recycled. |
| **Purpose** | High-level diagnostics, logging, and tracking object lifetimes. | Low-level object identification for the C++ core. |

### ♻️ Index Recycling

A key behavior of `MemoryIndex` is that indices are recycled. When an object is released (either via `Release()` or by going out of scope if owned), its `MemoryIndex` is returned to an internal pool. The next object of the *same type* that is created will reuse that index. This behavior is a powerful diagnostic feature, as it allows you to verify that objects are being released as expected.

### 🎯 Practical Applications

*   **Logging**: Tag log messages with an instance's `MemoryIndex` to trace operations back to a specific `uCalc` engine, especially in multi-threaded or multi-instance scenarios.
*   **Debugging**: Confirm that objects are being deallocated correctly by observing that their `MemoryIndex` values are reused later.
*   **Resource Management**: Track which indices are currently active to monitor the number of concurrent objects in memory.

### 💡 Comparative Analysis

*   **vs. C# `GetHashCode()`**: While `GetHashCode()` provides an integer identifier, its primary purpose is for hashing in collections, and it is not guaranteed to be unique. `MemoryIndex` is guaranteed to be unique among all active objects of its type.
*   **vs. C++ Pointers**: A raw pointer address is unique but is volatile between sessions, making it unsuitable for repeatable diagnostic tests. `MemoryIndex` provides a predictable sequence (`1`, `2`, `3`, ...), making logs and test results easier to analyze.

For the low-level, volatile identifier, see the [Handle](/uCalc-Documentation/Reference/uCalc/uCalc/Handle) method.

**Examples:**

---

## MemoryObjectAddress - ID: 601
/doc/reference/classes/ucalc/memoryobjectaddress/

**Description:** Retrieves the internal handle of a uCalc object using its class type and memory index.
[Static = true]
**Syntax:** MemoryObjectAddress(MemoryTable, int)
**Parameters:**
objectType - MemoryTable - The type of object to look up, specified using a member of the [MemoryTable](/reference/enums/memorytable) enum.
index - int - The unique memory index of the object, typically obtained from an object's `MemoryIndex()` method. Index 0 is reserved for empty objects.
**Return:** int - The internal handle of the object at the specified index. Returns 0 if no object is found.
**Remarks:**

The `MemoryObjectAddress` method is a low-level diagnostic tool used to retrieve an object's internal **handle** by using its stable **memory index**. It is primarily intended for advanced debugging and internal diagnostics.

Given an object's memory index (obtained from a method like [Item.MemoryIndex()](/reference/item/memoryindex)), this function returns the corresponding object [Handle](/reference/ucalc/handle), which is an opaque identifier used internally by the uCalc library.

### ⚖️ Handle vs. Memory Index

It is critical to understand the difference between these two identifiers:

| Feature | Handle | Memory Index |
| :--- | :--- | :--- |
| **Stability** | **Volatile**. A handle's value is unpredictable and can change between application runs. | **Stable**. Memory indices are predictable and generally sequential. |
| **Uniqueness** | Guaranteed unique for an object's lifetime. | Can be **recycled** after an object is released. |
| **Purpose** | Low-level object identification for the C++ core. | High-level diagnostics and tracking object lifetime. |

This function bridges the gap between the two, allowing you to find a volatile handle using a stable index.

> **Note**: This is a static function and is not called on a `uCalc` instance.

**Examples:**

---

## NamespaceSymbol - ID: 63
/doc/reference/classes/ucalc/namespacesymbol/

**Description:** Returns nth symbol belonging to the given namespace

**Syntax:** NamespaceSymbol(int)
**Parameters:**
nth - int - Nth symbol
**Return:** Item - Nth symbol item object
**Remarks:**

This function returns the object for the nth symbol found in the given namespace

---

## NamespaceSymbolCount - ID: 64
/doc/reference/classes/ucalc/namespacesymbolcount/

**Description:** Returns the number of symbols found in a given namespace

**Syntax:** NamespaceSymbolCount()
**Return:** int - Number of symbols
**Remarks:**

This function returns the number of symbols found in a given namespace.

---

## NewString - ID: 65
/doc/reference/classes/ucalc/newstring/

**Description:** Returns a new uCalc String object

**Syntax:** NewString(string)
**Parameters:**
InitialString - string [default = ""] - String initial value
**Return:** String - New uCalc string object
**Remarks:**

Mostly for internal use.

Creates a new string instance in the space of the uCalc instance it is being called from.  This method is called from the uCalc.String constructor.  You may want to use that instead.

The following two C# lines are equivalent:

var MyString = new uCalc.String();
var MyString = uCalc.GetDefaultInstance().NewString();

and so are:

var MyString = new uCalc.String("Hello world");
var MyString = uCalc.GetDefaultInstance().NewString("Hello world");

as well as:

var MyString = new uCalc.String("Hello world", uc);
var MyString = uc.NewString("Hello world"); // Where uc is a defined uCalc instance


---

## NewTransformer - ID: 66
/doc/reference/classes/ucalc/newtransformer/

**Description:** Returns a new transformer object

**Syntax:** NewTransformer(Tokens)
**Parameters:**
TokensToInherit - Tokens [default = Empty] - Existing token list to inherit from
**Return:** Transformer - Transformer object
**Remarks:**

**Description**: Creates a new `Transformer` object used for high-level pattern matching and structural text replacement.

The `NewTransformer` method is the entry point for uCalc's powerful **Transformation Engine**. Unlike standard Regex which operates on raw characters, a `Transformer` operates on **tokens**. This makes it aware of language structures like strings, numbers, and nested parentheses.

### Why use a Transformer?

| Feature | Standard Regex | uCalc Transformer |
| :--- | :--- | :--- |
| **Nested Brackets** | Extremely difficult / requires recursion | Handled automatically via `Bracket` tokens |
| **Readability** | "Soup" of backslashes and symbols | Natural, template-based syntax |
| **Determinism** | Can suffer from catastrophic backtracking | Linear, token-based matching |
| **Awareness** | Treats everything as text | Distinguishes between `123` (Number) and `"123"` (String) |

Use this method when you need to:
* Transpile one programming language to another.
* Clean up or format user-entered mathematical expressions.
* Extract specific data structures from mixed-content logs.


**Examples:**

### Example ID: 392

**Description:** A simple replacement demonstrating how to swap specific word patterns.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("Hello {name}", "Greetings, {name}!");
wl(t.Transform("Hello World"))
```

**Output:**
```
Greetings, World!
```

---

### Example ID: 111

**Description:** Returns Start and End positions of Transformer matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>");
//         ^             ^                       ^              ^
//     012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50
// Carrets (^) point to Start and End locations of the matches

wl(t.@Text())
wl("")

t.Pattern("<{tag}>{etc}</{tag}>");
t.Find();
var Matches = t.@Matches();

wl(Matches[0].@Text())
wl("Start pos: ", Matches[0].@StartPosition())
wl("End pos: ", Matches[0].@EndPosition())
wl("Length: ", Matches[0].@Length())
wl("")

wl(Matches[1].@Text())
wl("Start pos: ", Matches[1].@StartPosition())
wl("End pos: ", Matches[1].@EndPosition())
wl("Length: ", Matches[1].@Length())
```

**Output:**
```
<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>

<h1>First</h1>
Start pos: 4
End pos: 18
Length: 14

<h2>Second</h2>
Start pos: 42
End pos: 57
Length: 15
```

---

### Example ID: 114

**Description:** Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>");
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text())
   wl("Start pos: ", match.@StartPosition())
   wl("End pos: ", match.@EndPosition())
   wl("Length: ", match.@Length())
   wl("")
end foreach
```

**Output:**
```
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
```

---

---

## Owned - ID: 740
/doc/reference/classes/ucalc/owned/

**Description:** Manages automatic resource release for an object, enabling RAII-style lifetime management primarily for C++.

**Syntax:** Owned()
**Return:** uCalcBase - Returns the current instance to allow for method chaining.
**Remarks:**

## 🛡️ Managing Object Lifetime: The `Owned` Method

In uCalc, every object (like a `uCalc` instance, `Expression`, or `Transformer`) consumes resources. Proper resource management is crucial to prevent memory leaks. By default, you must manually call [Release()](/Reference/uCalcBase/uCalc/Release) on an object when it's no longer needed.

The `Owned()` method provides a way to opt into **automatic resource management**, aligning with the native idioms of different programming languages.

---

## **C++: Embracing RAII**

`Owned()` is designed specifically for C++ developers to leverage the **RAII (Resource Acquisition Is Initialization)** pattern. When you declare an object as "owned", its destructor will automatically call `Release()`, ensuring resources are freed when the object goes out of scope.

```pseudocode
// An object created on the stack is a candidate for RAII.
uCalc myCalc;
myCalc.Owned(); // Now, myCalc will be released automatically at the end of the scope.
```

This is essential when dealing with objects returned by methods like [Clone()](/Reference/uCalcBase/uCalc/Clone), which are created on the heap. By wrapping the returned handle in a stack-allocated object and calling `Owned()`, you transfer ownership to the stack, guaranteeing cleanup.

```pseudocode
[cpp]
{
    // Clone() returns a heap object; we wrap it in a stack object
    // to manage its lifetime.
    uCalc ownedClone(uc.Clone());
    ownedClone.Owned(); 
    
} // ownedClone's destructor is called here, which automatically releases the object.
[/cpp]
```

---

## **C# and VB.NET: The `using` Keyword**

In .NET languages, `Owned()` is **not needed**. The idiomatic way to ensure automatic resource cleanup is to use the `using` statement (C#) or `Using` block (VB.NET). All major uCalc objects implement `IDisposable`, which integrates directly with this language feature.

```pseudocode
[cs]
// The 'using' statement ensures myCalc.Release() is called automatically.
using (var myCalc = new uCalc())
{
    // ... use myCalc here ...
} // myCalc is released here.
[/cs]
```

---

## **Comparative Analysis: Why `Owned()`?**

### vs. Standard Smart Pointers (`std::unique_ptr`)

A C++ developer might ask, "Why not just return a `std::unique_ptr<uCalc>`?" uCalc uses an internal, cross-platform reference counting and object management system. The `Owned()` method acts as a bridge, allowing the C++-specific RAII pattern to interface cleanly with uCalc's internal lifetime management without exposing implementation details or forcing a dependency on a specific smart pointer type.

### vs. Manual `Release()` Calls

Forgetting to call [Release()](/Reference/uCalcBase/uCalc/Release) is a common source of memory leaks. Using `Owned()` in C++ (or `using` in C#) makes resource management declarative and less error-prone. The cleanup is guaranteed by the language's scoping rules, leading to safer and more robust code.

**Examples:**

### Example ID: 161

**Description:** "using" (C#) and Owned (C++) for auto-releasing uCalc object

**Code:**
```pseudocode

// In C# and VB you should use "using".
// In C++ you can flag a uCalc object for
// auto-release with Owned(), or by setting
// the last parameter of the constructor to true.

uc.@IsDefault(true); // Set uc as the default uCalc object
uCalc::@DefaultInstance().DefineVariable("Value = 'Original uc object'");
wl(uCalc::@DefaultInstance().EvalStr("Value")) // Outputs: Original uc object

[NotCpp]// Use "using" so that the object is auto-released when it it goes out of scope[/NotCpp]
   NewUsing(uCalc, uCalcTemp) [cpp]// Make uCalcTemp owned so it reverts back to uc when uCalcTemp goes out of scope[/cpp]
   uCalcTemp.@IsDefault(true); // Set uCalcTemp as the default uCalc object
   uCalc::@DefaultInstance().DefineVariable("Value = 'uCalcTemp object'");
   wl(uCalc::@DefaultInstance().EvalStr("Value")) // uCalcTemp object
End Using
// uCalcTemp goes out of scope here, and the default uCalc object reverts back to uc

wl(uCalc::@DefaultInstance().EvalStr("Value")) // Original uc object

[c]{!Eval: Chr(123)}[/c][vb]If True Then[/vb]
   [cs]/*using*/[/cs] New(uCalc, uCalcSticky) // remains the default even after going out of scope
   uCalcSticky.@IsDefault(true); // Set uCalcSticky as the default uCalc object
   uCalc::@DefaultInstance().DefineVariable("Value = 'uCalcSticky object'");
   wl(uCalc::@DefaultInstance().EvalStr("Value")) // Outputs: uCalcSticky object
[c]{!Eval: Chr(125)}[/c][vb]End If[/vb]    // The uCalcSticky object itself goes out of scope here, but internally it remains the default uCalc object

wl(uCalc::@DefaultInstance().EvalStr("Value"))
```

**Output:**
```
Original uc object
uCalcTemp object
Original uc object
uCalcSticky object
uCalcSticky object
```

---

---

## Parse - ID: 69
/doc/reference/classes/ucalc/parse/

**Description:** Compiles a string expression into an intermediate, reusable object for high-performance evaluation.

**Syntax:** Parse(string, DataType)
**Parameters:**
expression - string - The string containing the mathematical or logical expression to compile.
returnType - DataType [default = Empty] - Optional. The explicit return data type for the expression. If omitted, the type is inferred from the expression's content.
**Return:** Expression - An `Expression` object representing the compiled, ready-to-evaluate form of the input string.
**Remarks:**

The `Parse` method is the first step in uCalc's high-performance, two-stage evaluation model. It takes a string expression and compiles it into a reusable `Expression` object. This object can then be evaluated repeatedly using methods like [Evaluate](/reference/expression/evaluate) or [EvaluateStr](/reference/expression/evaluatestr).

### 🚀 The Performance Advantage: Parse Once, Evaluate Many

The most significant advantage of this two-step process is performance. Parsing an expression—analyzing its syntax and building an execution plan—is computationally more expensive than evaluating it. If you need to calculate the same formula multiple times (e.g., in a loop with changing variable values), using `Parse` is far more efficient than calling [Eval](/reference/ucalc/eval) or [EvalStr](/reference/ucalc/evalstr) repeatedly.

*   **Inefficient (Repeated Parsing)**: `for (i = 1 to 1000) result = uc.Eval("x*2+y");`
*   **Efficient (Parse Once)**: `var p = uc.Parse("x*2+y"); for (i = 1 to 1000) result = p.Evaluate();`

### ⚙️ Syntax and Features

The expression string passed to `Parse` can leverage the full power of the uCalc engine:
*   It can contain built-in or user-defined [Functions and Operators](/reference/functions_and_operators).
*   It is automatically pre-processed by rules defined in the [ExpressionTransformer](/reference/ucalc/expressiontransformer), allowing you to create custom syntax.
*   The return type of the expression can be explicitly set or automatically inferred. If no type can be deduced, the instance's [DefaultDataType](/reference/ucalc/defaultdatatype) (typically `Double`) is used.

### 🧠 Memory Management

An `Expression` object created by `Parse` holds resources and must be released when no longer needed to prevent memory leaks. You can manage its lifecycle in two ways:

1.  **Explicit Release**: Manually call the [Expression.Release()](/reference/expression/release) method.
2.  **Scoped Release (Recommended)**: Use language-specific constructs for automatic resource management.
    *   **C#**: Create the object within a `using` statement.
    *   **C++**: Create the `Expression` object on the stack (RAII).

```pseudocode
// Recommended C# approach for automatic cleanup
NewUsing(uCalc::Expression, myExpr(uc.Parse("1+5")))
// ... use myExpr ...
End Using // myExpr is automatically released here
```

### ⚖️ Comparative Analysis

*   **vs. `Eval()` in Scripting Languages (Python, JS)**: While `eval()` combines parsing and evaluation into one step, uCalc's `Parse` exposes the intermediate compiled object. This gives developers granular control, enabling performance optimizations and introspection (e.g., checking an expression's return type before evaluating it).

*   **vs. C# Expression Trees**: Building expression trees in C# from strings is complex. `Parse` provides a simple, direct way to achieve a similar result at runtime from dynamic user input.

*   **vs. `uCalc.Eval()` and `uCalc.EvalStr()`**: These methods are convenient for single-use evaluations. Use `Parse` when you anticipate evaluating the same expression structure more than once.

**Examples:**

### Example ID: 396

**Description:** A simple demonstration of parsing an expression and then evaluating it.

**Code:**
```pseudocode
wl("Parsing the expression '100 / 4'...")
NewUsing(uCalc::Expression, parsedExpr("100 / 4"))
//var parsedExpr = uc.Parse("100 / 4");

wl("Evaluating the result...")
wl("Result: ", parsedExpr.Evaluate())
End Using
```

**Output:**
```
Parsing the expression '100 / 4'...
Evaluating the result...
Result: 25
```

---

### Example ID: 31

**Description:** Illustrates the core relationship between the uCalc engine, an Item (variable), and a compiled Expression.

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");
var Expression = "x^2 * 10"; // Replace this with your expression

wl("--- Efficient: Parse() once, then Evaluate() in a loop ---")
var ParsedExpr = uc.Parse(Expression);
for(double x = 1 to 10)
   VariableX.Value(x);
   wl(ParsedExpr.Evaluate())
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
--- Efficient: Parse() once, then Evaluate() in a loop ---
10
40
90
160
250
360
490
640
810
1000
```

---

### Example ID: 32

**Description:** Displaying Integer (Int32) results with Evaluate32

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");

var ParsedExpr = uc.Parse("x / 2", "Integer"); // Causes output of "x / 2" to convert to an integer

// NOTE: EvaluateInt32 should only be used when Parse() explicitly specifies Integer
// (Or Int, or Int32) as the second argument, or if the expression evaluates to an integer
// (such as evaluating a variable that was explicitly defined as integer;
// other arithmetic operators typically evaluate to Double floating point).

for (double x = 1 to 10)
   VariableX.Value(x);
   wl("x = " + VariableX.ValueStr() + "  Result = " + to_string(ParsedExpr.EvaluateInt32()))
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  Result = 0
x = 2  Result = 1
x = 3  Result = 1
x = 4  Result = 2
x = 5  Result = 2
x = 6  Result = 3
x = 7  Result = 3
x = 8  Result = 4
x = 9  Result = 4
x = 10  Result = 5
```

---

### Example ID: 1460

**Description:** Using the parse-evaluate pattern for high-performance calculations in a loop with a changing variable w/ stopwatch.

**Code:**
```pseudocode
var variableX = uc.DefineVariable("x");
var userExpression = "x * 2 + 5";
var Total = 0.0;
var UpperBound = 1000000; // One million

// Parse the expression just once before the loop begins.
var parsedExpr = uc.Parse(userExpression);

[NotCpp]var stopwatch = System.Diagnostics.Stopwatch.StartNew();[/NotCpp]
for(double x = 1 to UpperBound)
   variableX.Value(x);
   Total = Total + parsedExpr.Evaluate();
end for
[NotCpp]stopwatch.Stop();
//Uncomment the following line to reveal the actual speed:
//Console.WriteLine($"Elapsed Milliseconds: {stopwatch.ElapsedMilliseconds} ms");
[/NotCpp]
w("Sum(1, ", UpperBound, ", ", userExpression, ") = ", [cpp](long long)[/cpp]Total)
```

**Output:**
```
Sum(1, 1000000, x * 2 + 5) = 1000006000000
```

---

---

## Properties - ID: 72
/doc/reference/classes/ucalc/properties/

**Description:** Creates a bitmask for querying items by their properties, such as function, operator, or variable.
[Static = true]
**Syntax:** Properties(ItemIs, ItemIs, ItemIs, ItemIs)
**Parameters:**
property1 - ItemIs - The first property to include in the filter.
property2 - ItemIs [default = ItemIs::SelectAny] - A second, optional property to combine.
property3 - ItemIs [default = ItemIs::SelectAny] - A third, optional property to combine.
property4 - ItemIs [default = ItemIs::SelectAny] - A fourth, optional property to combine.
**Return:** int64 - A 64-bit integer bitmask representing the combined properties, for use with the [ItemOf](/reference/ucalc/itemof) method.
**Remarks:**

## ⚙️ Core Concept: Building a Query Filter

This static helper function is the primary tool for building complex, multi-property queries with the [ItemOf](/reference/ucalc/itemof) method. It takes one or more property flags from the [ItemIs](/reference/enums/itemis) enum and combines them into a single 64-bit integer bitmask that `ItemOf` can use to filter and retrieve items.

It allows you to find items that match a specific set of criteria, such as "find all items that are either a prefix or a postfix operator."

## 🧠 Selector Logic: `SelectAny` vs. `SelectAll`

By default, `Properties` creates a filter that matches items with **any** of the specified properties (a logical OR). You can change this behavior by including a selector flag as the first argument.

*   **`ItemIs::SelectAny`** (Default)
    The returned item must match at least one of the provided properties. This is the default behavior and does not need to be specified explicitly if it's the desired logic.

*   **`ItemIs::SelectAll`**
    The returned item must match **all** of the provided properties (a logical AND). This is used for creating highly specific filters.

## 🔧 Technical Details & Language Quirks

*   **Bitmask Conversion**: Internally, members of the `ItemIs` enum are sequential integers (0, 1, 2, ...). The `ItemOf` method, however, expects a bitmask where properties correspond to powers of two (1, 2, 4, ...). This function handles that conversion automatically.

*   **VB.NET Requirement**: In C# and C++, you can pass a single `ItemIs` member directly to `ItemOf` thanks to method overloading. However, because VB.NET does not distinguish enums from integers in the same way, you **must** use this `Properties` function even when filtering by a single property.

## ⚖️ Comparative Analysis

*   **vs. LINQ (C#)**: In LINQ, you would build a similar query using lambda expressions and logical operators, which is often more readable for native .NET development:
    ```csharp
    var operators = items.Where(i => i.IsPrefix || i.IsPostfix);
    ```
    uCalc's `Properties` method uses a classic bitmasking approach common in C-style APIs. Its main advantage is being completely language-agnostic, providing the exact same query mechanism for C#, C++, and VB.NET developers.

*   **vs. SQL**: The `SelectAny` and `SelectAll` logic is analogous to using `OR` and `AND` in a SQL `WHERE` clause to filter results from a database table.

**Examples:**

### Example ID: 77

**Description:** ItemOf based on properties

**Code:**
```pseudocode
New(uCalc::Item, Item)
var x = 0;

// Lists the first few funcions defined in uCalc
// For the full list, loop until Item.IsEmpty() or while Item.NotEmpty()
for (x = 0 To 15)
   Item = uc.ItemOf(ItemIs::Function, x);
   wl(Item.@Name())
end for
wl("---")

// List only Prefix and Postfix (operators)
x = 0;
do
   Item = uc.ItemOf(uCalc::Properties(ItemIs::Prefix, ItemIs::Postfix), x);
   x = x + 1;
   wl(Item.@Name())
loop while (Item.NotEmpty())
```

**Output:**
```
abs
acos
acosh
addptr
addressof
anytype
append
append_copy
arg
argcount
asc
asin
asinh
atan
atan2
atanh
---
!
+
-
not
~
```

---

### Example ID: 45

**Description:** ItemOf selection between infix version of - (minus) operator and unary prefix version with Properties

**Code:**
```pseudocode

// Returns number of operands for the given operators
wl(uc.ItemOf("-", uCalc::Properties(ItemIs::Infix)).@Count())
wl(uc.ItemOf("-", uCalc::Properties(ItemIs::Prefix)).@Count())

[C]// You can pass one property directly in C++ and C#, but not VB
wl(uc.ItemOf("-", ItemIs::Infix).@Count())
wl(uc.ItemOf("-", ItemIs::Prefix).@Count())[/C]
[VB]
// You can pass one property directly in C++ and C#, but not VB
wl(2) // C++ and C# only: uc.ItemOf("-", ItemIs::Infix).@Count();
wl(1) // C++ and C# only: uc.ItemOf("-", ItemIs::Prefix).@Count();[/VB]
```

**Output:**
```
2
1
2
1
```

---

---

## Release - ID: 78
/doc/reference/classes/ucalc/release/

**Description:** Explicitly releases a uCalc instance and frees all of its associated memory and resources.

**Syntax:** Release()
**Return:** void - This method does not return a value.
**Remarks:**

### Core Concept: Freeing Engine Resources

The `Release()` method explicitly destroys a `uCalc` instance and deallocates all of its associated resources, including variables, functions, operators, transformers, and parsed expressions. It is the primary mechanism for manual memory management within the uCalc ecosystem.

### Why Explicit Release is Necessary (Comparative Analysis)

uCalc's memory model is different from standard garbage-collected or native memory management, making `Release()` essential.

*   **vs. C# Garbage Collection (GC)**: In C#, when a `uCalc` object variable goes out of scope, the C# Garbage Collector only reclaims the memory for the **handle** (the C# wrapper object). The underlying C++ engine instance, which holds the bulk of the data, remains in memory. `Release()` is the signal to destroy that underlying engine instance. Without it, you will have a memory leak.

*   **vs. C++ `delete`**: uCalc uses its own internal memory manager for performance and object recycling. A `uCalc` handle is not a raw C++ pointer that can be managed with `delete`. Calling `Release()` ensures the object is returned to uCalc's internal pool correctly.

### Interaction with Automatic Release Mechanisms

While `Release()` provides manual control, the recommended approach is to use language-specific scoping mechanisms that call `Release()` for you automatically:

*   **C# / VB.NET**: Create the `uCalc` instance within a `using` block. The instance will be automatically released when the block is exited.
```pseudocode
NewUsing(uCalc, myCalc)
// ... use myCalc ...
End Using
// myCalc is automatically released here.
```

*   **C++**: For stack-allocated objects or by calling [Owned()](/Reference/uCalc/uCalc/Owned), the `uCalc` instance is released when its destructor is called at the end of its scope.

Use `Release()` explicitly when the lifetime of the `uCalc` object is not tied to a specific lexical scope.

### Best Practices

*   **Avoid Releasing the Default**: While possible, you should avoid calling `Release()` on the instance returned by [uCalc.GetDefaultInstance()](/Reference/uCalc/uCalc/Default). The engine expects a default instance to always be available.
*   **Memory Recycling**: Released instances are not completely destroyed but are returned to an internal pool. This means creating a new `uCalc` instance immediately after releasing one is a very fast operation, as the engine can recycle the previously used memory footprint.

**Examples:**

### Example ID: 33

**Description:** Doing an Eval in the same uCalc instance a variable belongs to

**Code:**
```pseudocode
New(uCalc, uc1)
New(uCalc, uc2)

var x1 = uc1.DefineVariable("x = 5");
var x2 = uc2.DefineVariable("x = 6");

wl(x1.@uCalc().Eval("x*10")) // Same as uc1.Eval("x*10")
wl(x2.@uCalc().Eval("x*10")) // Same as uc2.Eval("x*10")

uc1.Release();  // Since x1 is part of uc1, x1 is automatically released as well
uc2.Release();  // Since x2 is part of uc2, x2 is automatically released as well

// You should no longer use x1 or x2 because they were part of uc1 & uc2
// Don not try x1.uCalc().Eval("x*10"); or x2.uCalc().Eval("x*10");
```

**Output:**
```
50
60
```

---

### Example ID: 78

**Description:** Creating uCalc instances

**Code:**
```pseudocode
uc.DefineVariable("x = 123");

New(uCalc, uc1) // Creates a new instance
wl(uc1.EvalStr("x")) // uc1 does not have a variable named x
uc1.Release(); // Releases uc1 if it is no longer needed

var uc2 = uc.Clone(); // Creates new instance that is a clone of uc
wl(uc2.EvalStr("x")) // starts with the value of x obtained from uc
uc2.Eval("x = 456"); // Changes the value of x in uc1 but not uc
wl(uc2.EvalStr("x"))
wl(uc.EvalStr("x")) // The original x in uc remains unchanged
uc2.Release();

// Language specific - auto-releasing uCalc object
[vb]#If False[/vb]
{ // Instances pointed to by neither uCalc1 nor uCalc2 will be released when they go out of scope
   var uCalc1 = new uCalc();
   var uCalc2 = uc.Clone();
   // Call uCalc1.Release() and uCalc2.Release() explicitly if want to release them
}

{ // The instances that both uCalc1 and uCalc2 point to will be released when uCalc1 and uCalc2 go out of scope
   [cs]using var uCalc1 = new uCalc();
   using var uCalc2 = uc.Clone();[/cs]
   [cpp]uCalc uCalc1;
   uCalc uCalc2(uc.Clone());[/cpp]
   // No need for uCalc1.Release() or uCalc2.Release(), they will automatically be released
}
[vb]#End If[/vb]
```

**Output:**
```
Undefined identifier
123
456
123
```

---

---

## ResetAll - ID: 566
/doc/reference/classes/ucalc/resetall/

**Description:** Resets the entire uCalc library to its initial startup state, releasing all instances and clearing all definitions.
[Static = true]
**Syntax:** ResetAll()
**Return:** void - This method does not return a value.
**Remarks:**

The static `ResetAll()` method is a global, application-wide function that restores the uCalc library to its pristine, out-of-the-box state. It is a powerful tool for ensuring a clean environment, particularly in testing scenarios or applications with complex, dynamic configurations.

### ⚙️ What `ResetAll` Does

Calling this function performs the following actions:
1.  **Releases All Instances**: Every `uCalc` instance created during the application's lifetime is released, freeing all associated memory.
2.  **Clears the Default Stack**: It completely clears the default instance stack, which is managed by methods like [IsDefault](/reference/ucalc/ucalc/isdefault).
3.  **Resets the Root Default**: It restores the original, built-in [DefaultInstance](/reference/ucalc/ucalc/default) instance to its initial state, removing any user-defined functions, variables, or settings.

### 🎯 When to Use `ResetAll`

`ResetAll` is the most comprehensive cleanup tool and should be used when you need to guarantee a completely fresh start. Common use cases include:

*   **Unit Testing**: It is best practice to call `ResetAll()` in the `TearDown` or `afterEach` method of a test suite to ensure that each test runs in a perfectly isolated environment, free from any state created by previous tests.
*   **Application-Level Reset**: In applications that allow users to script or configure the engine, `ResetAll` can power a "Reset to Factory Defaults" feature.
*   **Recovering from Errors**: In an interactive or long-running session, it provides a reliable way to recover from a state where definitions may have become corrupted or are no longer needed.

### 🆚 `ResetAll` vs. Other Reset Methods

It is crucial to choose the correct cleanup method for your needs. `ResetAll` is the most powerful and destructive option.

| Method | Scope | Effect |
| :--- | :--- | :--- |
| `ResetAll()` | **Global (Library-wide)** | Destroys **all** `uCalc` instances and resets the entire library. |
| [DefaultClear()](/reference/ucalc/ucalc/defaultclear) | **Default Instance Stack** | Removes all custom default instances and resets only the original, root default instance. Other instances are unaffected. |
| `instance.Release()` | **Single Instance** | Releases one specific `uCalc` instance and its associated resources. |

⚠️ **Warning**: Because `ResetAll()` affects the entire application, use it with care. Calling it will invalidate all existing `uCalc` object handles, including any that may still be in scope.

**Examples:**

---

## TokenTransformer = [Transformer] - ID: 645
/doc/reference/classes/ucalc/tokentransformer-=-[transformer]/

**Description:** Retrieves the dedicated transformer for defining token-level transformations, enabling custom syntax like string interpolation or hex literals.

**Remarks:**

The `TokenTransformer()` method returns the dedicated [Transformer](/Reference/uCalc/uCalc/NewTransformer) object used for pre-processing specific tokens *during* the lexical analysis phase of an expression. This allows for powerful, targeted syntax transformations like string interpolation, custom numeric notations (hex/binary), or special escape sequences.

### ⚙️ How It Works: The Trigger Mechanism

Unlike the global [ExpressionTransformer](/Reference/uCalc/uCalc/ExpressionTransformer), which processes every expression string, the `TokenTransformer` is only activated when the parser encounters a token that has been specifically registered with the type `TokenType::TokenTransform`. This makes it exceptionally efficient.

The workflow is:
1.  **Define a Trigger**: Register a regex pattern with `ExpressionTokens().Add()` and assign it the type `TokenType::TokenTransform`. For example, a pattern for C-style hex numbers: `uc.ExpressionTokens().Add("0x[0-9A-F]+", TokenType::TokenTransform);`
2.  **Define the Rule**: Add a `FromTo` rule to the `TokenTransformer` that matches the token's structure and replaces it with a valid uCalc expression. `uc.TokenTransformer().FromTo("{'0x'}{val:'[0-9A-F]+'}", "BaseConvert(val, 16)");`
3.  **Evaluate**: When `Parse` or `EvalStr` encounters text matching the trigger (e.g., "0xFF"), the `TokenTransformer` runs, replaces it with "BaseConvert('FF', 16)", and the parser continues with the transformed result.

### `TokenTransformer` vs. `ExpressionTransformer`

Choosing the right tool is critical for performance and maintainability.

| Aspect | `TokenTransformer` (This Topic) | `ExpressionTransformer` | 
| :--- | :--- | :--- |
| **Scope** | **Surgical**: Only runs when a specific `TokenTransform` token is found. | **Global**: Runs on the entire expression string for every call to `Parse` or `Eval`. |
| **Performance** | 🚀 **High**. Zero overhead if the trigger tokens are not present. | 🐌 **Lower**. Introduces overhead on every parse, even if no rules match. |
| **Use Case** | Ideal for implementing new low-level syntax (literals, interpolation, escapes). | Ideal for high-level syntactic sugar or transpiling language constructs (e.g., `x^y` to `pow(x,y)`). |

**Rule of Thumb**: Use `TokenTransformer` for things that feel like new types of *literals* or *tokens*. Use `ExpressionTransformer` for things that feel like new *operators* or *function call syntax*.

### 💡 Comparative Analysis
*   **vs. Manual String Parsing/Regex**: A standard regex approach struggles with context (e.g., is `$` an interpolation marker or part of a variable name inside a string?). Because `TokenTransformer` is integrated with the lexer, it operates with full awareness of existing language structures.
*   **vs. Lexer Generators (ANTLR, Flex)**: Traditional compiler tools require an offline, static build step. uCalc's engine is fully **dynamic**. You can add or modify token transformation rules at runtime, allowing an application to extend its own syntax on the fly.

**Examples:**

### Example ID: 342

**Description:** Extends the parser to support C-style `0x` hex and `0b` binary notations using a token transformer.

**Code:**
```pseudocode
// Define a token for C-like 0x hex notation
uc.@ExpressionTokens().Add("0x[0-9A-Fa-f]+", TokenType::TokenTransform);
uc.@TokenTransformer().FromTo("{'0x'}{Num:'[0-9A-Fa-f]+'}", "BaseConvert('{Num}', 16)");
wl("0xFF is evaluated as: ", uc.EvalStr("0xFF"))

// Define a token for C++-style 0b binary notation
uc.@ExpressionTokens().Add("0b[01]+", TokenType::TokenTransform);

// Using {@Eval} is more efficient as the conversion happens once during the token transform pass.
uc.@TokenTransformer().FromTo("{'0b'}{Num:'[01]+'}", "{@Eval: BaseConvert(Num, 2)}");
wl("0b1011 is evaluated as: ", uc.EvalStr("0b1011"))

// Note: uCalc has built-in support for hex/binary using # notation (e.g., #hFF, #b1011)
wl("uCalc's built-in #hFF is: ", uc.EvalStr("#hFF"))
```

**Output:**
```
0xFF is evaluated as: 255
0b1011 is evaluated as: 11
uCalc's built-in #hFF is: 255
```

---

---

## TransformerForRulePatterns = [Transformer] - ID: 809
/doc/reference/classes/ucalc/transformerforrulepatterns-=-[transformer]/

**Description:** Retrieves a singleton transformer that pre-processes pattern definition strings before they are compiled into rules.

**Remarks:**

The `TransformerForRulePatterns()` method retrieves a special, singleton `Transformer` instance that pre-processes the *pattern* part of a rule before it is compiled. This "meta-transformer" allows you to create aliases, macros, or syntactic sugar for your pattern definitions, effectively enabling you to build a custom, higher-level pattern language.

### ⚙️ How It Works

When you define a rule using methods like [FromTo()](/Reference/uCalc/Transformer/FromTo) or [Pattern()](/Reference/uCalc/Transformer/Pattern), the pattern string goes through this pipeline:

1.  The raw pattern string is passed to the `TransformerForRulePatterns` instance.
2.  Any matching rules defined on this meta-transformer are applied.
3.  The resulting, transformed string is then compiled into the final pattern rule.

This process is transparent. By default, this transformer has no rules and does nothing. It is lazily instantiated only when this method is called for the first time, ensuring no performance overhead for users who don't need it.

### 🎯 Primary Use Cases

*   **Creating Shortcuts & Aliases**: Simplify complex or frequently used pattern segments. Instead of writing `{@StringSQ}` repeatedly, you can define a rule to transform a simple alias like `@sqs` into the full token name.
*   **Abstracting Complexity**: Hide complex regex or structural logic behind a simple, readable keyword. A custom pattern like `IPV4_ADDRESS` could be expanded into `{@Number}.{@Number}.{@Number}.{@Number}`.
*   **Building a Mini-DSL**: Design a simpler syntax for end-users, which the meta-transformer then transpiles into valid uCalc patterns behind the scenes.

### 🆚 Comparative Analysis

| Method | `TransformerForRulePatterns()` | `ExpressionTransformer()` | `NewTransformer()` |
| :--- | :--- | :--- | :--- |
| **Purpose** | Transforms **pattern definition strings** before they become rules. | Transforms **user expressions** before they are parsed (e.g., `EvalStr`). | A general-purpose tool for transforming **any user data string**. |
| **Scope** | Affects how `FromTo()` and `Pattern()` rules are created. | Affects the uCalc expression parser. | Standalone; does not affect any internal process. |

Using this meta-transformer is similar to using C/C++ preprocessor macros (`#define`) to create aliases for complex code, but with the full, token-aware power of a uCalc `Transformer`.

**Examples:**

### Example ID: 187

**Description:** RulePatternTransformer

**Code:**
```pseudocode
var t = uc.NewTransformer();

var Pattern = uc.@TransformerForRulePatterns();
var Replacement = uc.@TransformerForRuleReplacements();

Pattern.FromTo("@sq", "{@Eval: '{@Token(_Token_String_SingleQuoted)}'}");
Replacement.FromTo("~", "{@Eval: '{@Self}'}");

t.FromTo("@sq", "<single quote txt = ~>");
// Same as t.FromTo("{@Token(_Token_QuoteChar_Single)}", "<single quote txt = {@Self}>"); 

wl(t.Transform("Test: 'some text'."))




```

**Output:**
```
Test: <single quote txt = 'some text'>.
```

---

---

## TransformerForRuleReplacements = [Transformer] - ID: 810
/doc/reference/classes/ucalc/transformerforrulereplacements-=-[transformer]/

**Description:** Retrieves a meta-transformer that pre-processes the replacement strings of other transformer rules before they are defined.

**Remarks:**

The `TransformerForRuleReplacements()` method provides access to a special **meta-transformer**. This transformer does not process normal text; instead, it processes the **replacement strings** (the `To` part) of rules you define with `FromTo()`.

This allows you to create powerful shorthands, aliases, or macros for your replacement logic, promoting consistency and readability in complex transformation projects.

### ⚙️ How It Works

When you define a rule like `t.FromTo(pattern, replacement)`, the `replacement` string is first passed through the meta-transformer returned by this method. The *result* of that transformation is what gets compiled as the final replacement rule.

```pseudocode
// 1. Get the meta-transformer
var meta = uc.TransformerForRuleReplacements();

// 2. Define a meta-rule: "#b({c})" will become "<b>{c}</b>"
//    Note: {@Eval:'...'} is used to pass the replacement as a literal template.
meta.FromTo("#b({c})", "{@Eval:'<b>{c}</b>'}");

// 3. Create a standard transformer
New(uCalc::Transformer, t);

// 4. Use the shorthand in a normal rule definition.
//    The meta-transformer will expand "#b({word})" before this rule is compiled.
t.FromTo("{@Alpha:word}", "#b({word})");

// 5. The rule effectively becomes: t.FromTo("{@Alpha:word}", "<b>{word}</b>");
wl(t.Transform("make this bold"));
// Output: make this <b>bold</b>
```

### 💡 Core Use Cases

*   **Creating Aliases**: Define a short alias like `~` to represent a common but verbose placeholder like `{@Self}`.
*   **Building Macros**: Create complex, reusable replacement templates (e.g., for wrapping text in HTML/XML tags).
*   **Enforcing Consistency**: Ensure all replacement strings follow a standard format by pre-processing them.

### ⚠️ Critical Pitfall: Premature Variable Evaluation

When defining a meta-rule, its replacement string can contain variable placeholders intended for the *final* rule (e.g., `{c}` in the example above). To prevent the meta-transformer from trying to evaluate these placeholders itself, you must wrap the replacement template in `{@Eval:'...'}`. This treats the template as a literal string, ensuring the placeholders are preserved for the final rule.

*   **Incorrect**: `meta.FromTo("#b({c})", "<b>{c}</b>")` - The meta-transformer will look for a variable named `c`.
*   **Correct**: `meta.FromTo("#b({c})", "{@Eval:'<b>{c}</b>'}")` - The meta-transformer inserts the literal string `<b>{c}</b>`.

### Comparative Analysis

*   **vs. Manual Replacement**: You could manually type `<b>{word}</b>` every time, but using a meta-transformer abstracts this logic. If you later decide to use `<strong>` tags instead of `<b>`, you only need to change the single meta-rule, and all dependent rules update automatically.
*   **vs. Text Pre-processors (C/C++)**: This feature is analogous to a C pre-processor `#define` macro, but it's fully integrated into the uCalc engine, token-aware, and can be modified dynamically at runtime.

This meta-transformer is not created until `TransformerForRuleReplacements()` is called for the first time, ensuring no performance overhead if the feature is unused. It is the direct counterpart to [`TransformerForRulePatterns()`](/reference/ucalc/mainclassgroup/transformerforrulepatterns), which performs the same function for pattern strings.

**Examples:**

### Example ID: 187

**Description:** RulePatternTransformer

**Code:**
```pseudocode
var t = uc.NewTransformer();

var Pattern = uc.@TransformerForRulePatterns();
var Replacement = uc.@TransformerForRuleReplacements();

Pattern.FromTo("@sq", "{@Eval: '{@Token(_Token_String_SingleQuoted)}'}");
Replacement.FromTo("~", "{@Eval: '{@Self}'}");

t.FromTo("@sq", "<single quote txt = ~>");
// Same as t.FromTo("{@Token(_Token_QuoteChar_Single)}", "<single quote txt = {@Self}>"); 

wl(t.Transform("Test: 'some text'."))




```

**Output:**
```
Test: <single quote txt = 'some text'>.
```

---

---

## ValueAt - ID: 81
/doc/reference/classes/ucalc/valueat/

**Description:** Dereferences a pointer and returns a string representation of the value, allowing for on-the-fly type casting.

**Syntax:** ValueAt(POINTER, DataType, bool)
**Parameters:**
valuePtr - POINTER - The memory address (pointer) of the value to retrieve.
targetType - DataType [default = Empty] - The DataType object or its name, used to interpret the data at the specified memory address. This allows for type casting (e.g., viewing a signed integer as unsigned).
formattedOutput - bool [default = false] - If `true`, the output string is formatted according to the rules defined by the Format method. Defaults to `false`.
**Return:** string - A string representation of the value at the given memory address, interpreted as the specified `targetType`.
**Remarks:**

### 🎯 ValueAt: Dereference and Interpret Memory

The `ValueAt` method provides a powerful, low-level mechanism to dereference a pointer and retrieve the value stored at that memory address. Its primary function is to interpret raw memory as a specific data type and return its string representation. This is particularly useful for **type punning**, where you want to view the same block of memory as different data types.

### How It Works

In languages like C/C++, you might cast a pointer to a different type to change how you interpret the data it points to. For example, `*(unsigned int*)signed_int_ptr`. `ValueAt` brings this capability into the uCalc scripting environment in a managed way.

You provide:
1.  A memory address (`valuePtr`).
2.  A data type (`targetType`) to use for interpretation.
3.  An optional flag (`formattedOutput`) to apply custom formatting.

The engine then reads the data at `valuePtr`, interprets its bits according to the rules of `targetType`, and converts the result to a string.

### 💡 Common Use Cases

*   **Viewing Signed vs. Unsigned:** Read an `Int8` value from memory but display it as an `Int8u` to see its unsigned representation (e.g., -1 becomes 255).
*   **Inspecting Expression Results:** When an expression is parsed to return a specific type (e.g., an unsigned integer), `ValueAt` can be used to see what that result would be if it were a different type (e.g., a signed integer), without re-evaluating the expression.
*   **Interfacing with Pointers:** When working with variables defined as pointers, `ValueAt` is the standard way to get the value they point to.

### Formatting

If `formattedOutput` is set to `true`, the resulting string will be formatted using the global format string defined by the [Format](/uCalc-Documentation/Reference/uCalc/uCalc/Format) method.

**Examples:**

### Example ID: 430

**Description:** Retrieves a double-precision value from a pointer, with and without formatting.

**Code:**
```pseudocode
// Define a global format for the 'formattedOutput' parameter
uc.Format("Result = 'Answer: <' + Result + '>'");

// Create a variable and get its memory address
var myDouble = uc.DefineVariable("MyDouble = 123.456");
var ptr = myDouble.ValueAddr();

// 1. Retrieve the value by specifying the data type by name
wl("By Name: ", uc.ValueAt(ptr, "Double"))

// 2. Retrieve the value using the built-in enum
wl("By Enum: ", uc.ValueAt(ptr, BuiltInType::Float_Double))

// 3. Retrieve the value with formatting enabled
wl("Formatted: ", uc.ValueAt(ptr, BuiltInType::Float_Double, true))
```

**Output:**
```
By Name: 123.456
By Enum: 123.456
Formatted: Answer: <123.456>
```

---

### Example ID: 431

**Description:** Demonstrates type punning by interpreting an unsigned byte (`Int8u`) result as a signed byte (`Int8`) to observe how values wrap around.

**Code:**
```pseudocode
// Define a variable 'x' that will be used in our expression
var variableX = uc.DefineVariable("x As Int");

// Parse an expression that will result in an unsigned 8-bit integer (0-255)
var parsedExpr = uc.Parse("x + 125", "Int8u");

wl("x | Int8u (0 to 255) | Int8 (-128 to 127)")
wl("------------------------------------------")

for (int x = 1 to 5)
   variableX.ValueInt32(x);

   // Evaluate the expression to get a pointer to the result
   var resultPtr = parsedExpr.EvaluateVoid();

   // Get the raw unsigned result
   var unsignedResult = uc.ValueAt(resultPtr, "Int8u");

   // Use ValueAt to *re-interpret* the same memory as a signed byte
   var signedResult = uc.ValueAt(resultPtr, "Int8");

   wl(x, " | ", unsignedResult, " | ", signedResult)
end for

// Clean up the created items
parsedExpr.Release();
variableX.Release();
```

**Output:**
```
x | Int8u (0 to 255) | Int8 (-128 to 127)
------------------------------------------
1 | 126 | 126
2 | 127 | 127
3 | 128 | -128
4 | 129 | -127
5 | 130 | -126
```

---

### Example ID: 82

**Description:** Pointer value with ValueAt

**Code:**
```pseudocode
uc.Format("Result = 'Answer: <' + Result + '>'");

var Dbl = uc.DefineVariable("MyDouble = 123.456");

wl(uc.ValueAt(Dbl.ValueAddr(), "Double"))
wl(uc.ValueAt(Dbl.ValueAddr(), BuiltInType::Float_Double))
wl(uc.ValueAt(Dbl.ValueAddr(), BuiltInType::Float_Double, true))


```

**Output:**
```
123.456
123.456
Answer: <123.456>
```

---

---

## uCalc.ErrorInfo - ID: 846
/doc/reference/classes/ucalc.errorinfo/

**Description:** Class for handling errors

---

## Introduction - ID: 958
/doc/reference/classes/ucalc.errorinfo/introduction/

**Description:** Provides access to detailed information about parsing or evaluation errors and allows for the registration of custom error-handling callbacks.

**Remarks:**

# 💣 ErrorInfo: The Error Handling Engine

The `ErrorInfo` class is the central hub for uCalc's state-based error handling system. It provides detailed information about parsing and evaluation errors and allows you to register custom callbacks to intercept, inspect, and even recover from them.

This class is accessed via the [Error](/Reference/uCalcBase/uCalc/Error) property on a `uCalc` instance (e.g., [pseudocode]`uc.@Error()`).

---

## A Different Approach: State-Based Errors vs. Exceptions

In a parsing context, especially one dealing with user input, errors like typos or incomplete formulas are normal, not "exceptional." Traditional `try/catch` exception handling, which interrupts program flow and unwinds the call stack, is a heavyweight solution for such common occurrences. 

uCalc uses a more lightweight and flexible model:

1.  **Reactive State Checking**: After an operation like [EvalStr](/Reference/uCalcBase/uCalc/EvalStr) fails, it doesn't throw. Instead, it sets the error state on this `ErrorInfo` object. You can then check properties like [Code](/Reference/uCalcBase/ErrorInfo/Code) and [Message](/Reference/uCalcBase/ErrorInfo/Message) to see what went wrong.

2.  **Proactive Callback Handling**: For more advanced control, you can register a handler with [AddHandler](/Reference/uCalcBase/ErrorInfo/AddHandler). This callback is invoked the moment an error occurs, giving you the power to log the issue, provide custom feedback, or even fix the problem and `Resume` execution.

This callback-driven model is more performant and provides a unique level of control, transforming error handling from a simple failure mechanism into a dynamic recovery system.

--- 

## ⚙️ Error Information Properties

These properties provide detailed context about the last error that occurred.

| Member | Description |
| :--- | :--- |
| [`Code`](/Reference/uCalcBase/ErrorInfo/Code) | Retrieves the numeric code, as an `ErrorCode` enum member, for the most recently triggered error. |
| [`Message`](/Reference/uCalcBase/ErrorInfo/Message) | Retrieves the descriptive message for the last error that occurred. |
| [`Expression`](/Reference/uCalcBase/ErrorInfo/Expression) | Returns the full expression string that was being processed when a parsing error occurred. |
| [`Location`](/Reference/uCalcBase/ErrorInfo/Location) | Returns the zero-based character position where a parsing error was detected. |
| [`Symbol`](/Reference/uCalcBase/ErrorInfo/Symbol) | Returns the specific symbol or token that triggered a parsing-stage error. |


--- 

## 🔧 Error Handling Methods & Configuration

These members allow you to configure and control the error handling pipeline.

| Member | Description |
| :--- | :--- |
| [`AddHandler`](/Reference/uCalcBase/ErrorInfo/AddHandler) | Registers a callback function to intercept, log, or resolve errors during parsing and evaluation. |
| [`Response`](/Reference/uCalcBase/ErrorInfo/Response) | Determines the engine's behavior after an error handler callback finishes executing (e.g., `Abort`, `Resume`). |
| [`Raise`](/Reference/uCalcBase/ErrorInfo/Raise) | Triggers a predefined or custom error from within a callback function. |
| [`GetMessage`](/Reference/uCalcBase/ErrorInfo/GetMessage) | Retrieves the generic, built-in descriptive message for a specific error code. |
| [`FloatingPointErrorsToTrap`](/Reference/uCalcBase/ErrorInfo/FloatingPointErrorsToTrap) | Configures which IEEE 754 floating-point exceptions (e.g., division by zero) will raise a uCalc error. |
| [`TrapOnDivideByZero`](/Reference/uCalcBase/ErrorInfo/TrapOnDivideByZero) | A convenience property to enable or disable raising an error on division by zero. |
| [`TrapOnInvalid`](/Reference/uCalcBase/ErrorInfo/TrapOnInvalid) | A convenience property to control whether invalid floating-point operations (e.g., `sqrt(-1)`) raise an error. |
| [`TrapOnOverflow`](/Reference/uCalcBase/ErrorInfo/TrapOnOverflow) | A convenience property to configure the engine to raise an error upon floating-point overflow. |
| [`TrapOnUnderflow`](/Reference/uCalcBase/ErrorInfo/TrapOnUnderflow) | A convenience property to configure whether a floating-point underflow raises an error. |


**Examples:**

### Example ID: 1

**Description:** Adding an error handler callback

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Symbol: ", uc.@Error().@Symbol())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);
wl(uc.EvalStr("123+"))
wl("")

uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("5/0"))
```

**Output:**
```
An error has occurred!
Error #: 257
Error Message: Syntax error
Error Symbol: +
Error Location: 3
Error Expression: 123+
Syntax error

An error has occurred!
Error #: 8
Error Message: Division by 0
Error Symbol: 
Error Location: 0
Error Expression: 
Division by 0
```

---

---

## AddHandler - ID: 14
/doc/reference/classes/ucalc.errorinfo/addhandler/

**Description:** Registers a callback function to intercept, log, or resolve errors during parsing and evaluation.

**Syntax:** AddHandler(DELEGATE_UCALC, int)
**Parameters:**
callback - DELEGATE_UCALC - The address of the user-defined callback function.
priority - int [default = 0] - The insertion priority.
**Return:** Item - Item representing the error handler
**Remarks:**

`AddErrorHandler` lets you attach a custom function that can intercept and respond to errors (such as a syntax error, unknown symbol, or divide-by-zero) raised during parsing or evaluation. This allows for centralized error management, logging, or "soft" failure modes where the application can continue running despite invalid input.  Error handlers can:

- Display or log error information
- Modify the error response  
- Attempt recovery and resume execution  
- Abort evaluation early  
- Provide custom debugging or diagnostic output  

Handlers are invoked in a **stack‑like order** unless you specify a custom insertion position.

---

## **Handler Ordering**

By default, handlers are called:

1. **Most recently added handler first**  
2. Then older handlers in reverse order of registration  

You can override this by specifying the `priority` parameter:

- `0` (default): Insert at the **front** of the queue (called first)  
- `-1`: Insert at the **end** (called last)  
- Positive integer: Insert at that index  
- Out‑of‑range values are automatically clamped to valid bounds  

This allows you to build layered error‑handling strategies (e.g., a global logger at the end, a temporary handler at the front).

---

## **Resuming After an Error**

By default (`ErrorHandlerResponse::Abort`), an error stops the parsing or evaluation process.  As a result, [pseudocode]`Error.@Code()` will return a value other than `ErrorCode::None`, and `ErrorMessage()` will return a non-empty string.  `EvalStr()` or `EvaluateStr()` would also return an error message.

However, inside your callback, you can change the outcome using `uc.ErrorResponse(...)`.

If you set:

```
uCalc.ErrorResponse(ErrorHandlerResponse::Resume)
```

…then:

- The **current** handler runs  
- All **subsequent** handlers are skipped  
- uCalc resumes execution as if no error occurred  

⚠️ **Important:**  
You must correct the condition that caused the error before resuming.  
Otherwise, uCalc may repeatedly encounter the same error and enter an infinite loop.

---

## **Parsing‑Stage vs Evaluation‑Stage Error Information**

Some error‑inspection functions only produce meaningful results during the **parsing** stage:

- `uCalc.ErrorExpression()`  
- `uCalc.ErrorLocation()`  
- `uCalc.ErrorSymbol()`  

During **evaluation**, these functions still work safely but return:

- `ErrorLocation` → `0`  
- `ErrorExpression` → empty string  
- `ErrorSymbol` → empty string  

This distinction helps you determine whether the error occurred during parsing or evaluation.

---

## **Return Value**

`AddErrorHandler` returns an **Item** representing the handler.  
You can later remove the handler by calling `.Release()` on this returned object.

**Examples:**

### Example ID: 1

**Description:** Adding an error handler callback

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Symbol: ", uc.@Error().@Symbol())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);
wl(uc.EvalStr("123+"))
wl("")

uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("5/0"))
```

**Output:**
```
An error has occurred!
Error #: 257
Error Message: Syntax error
Error Symbol: +
Error Location: 3
Error Expression: 123+
Syntax error

An error has occurred!
Error #: 8
Error Message: Division by 0
Error Symbol: 
Error Location: 0
Error Expression: 
Division by 0
```

---

### Example ID: 258

**Description:** Registers a handler to log when division by zero occurs.

**Code:**
```pseudocode
[head]
[callback:u LogAndResume]
wl("Logged error: ", uc.@Error().@Message())
uc.@Error().@Response(ErrorHandlerResponse::Resume);
[/callback]

[body]
uc.@Error().@TrapOnDivideByZero(true);
uc.@Error().AddHandler(LogAndResume);

wl("Start")
var Result = uc.Eval("5/0");   // Division by zero
wl("End")
```

**Output:**
```
Start
Logged error: Division by 0
End
```

---

### Example ID: 54

**Description:** Error handler to auto-define variables

**Code:**
```pseudocode
[head]
// This error handler allows you to use variables that were not
// explicitly defined previously, by defining the unrecognized identifiers
// as variables instead of returning an error
[callback:u AutoVariableDef]
   if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
      uc.DefineVariable(uc.@Error().@Symbol());
      uc.@Error().@Response(ErrorHandlerResponse::Resume);
   end if
[/callback]

[body]
uc.@Error().AddHandler(AutoVariableDef);
wl(uc.Eval("AutoTest = 123"))
wl(uc.Eval("AutoTest * 1000"))
```

**Output:**
```
123
123000
```

---

### Example ID: 55

**Description:** Error handler order

**Code:**
```pseudocode
[head]
[callback:u ErrorHandlerA]
wl("Handler A called")
[/callback]

[callback:u ErrorHandlerB]
wl("Handler B called")
[/callback]

[callback:u ErrorHandlerC]
wl("Handler C called")
[/callback]

[callback:u ErrorHandlerD]
wl("Handler D called")
[/callback]

[callback:u ErrorHandlerE]
wl("Handler E called")
[/callback]

[body]
uc.@Error().AddHandler(ErrorHandlerA);
uc.@Error().AddHandler(ErrorHandlerB);
uc.@Error().AddHandler(ErrorHandlerC);
uc.@Error().AddHandler(ErrorHandlerD, -1);
uc.@Error().AddHandler(ErrorHandlerE, 3);

wl(uc.EvalStr("10 / "))
```

**Output:**
```
Handler C called
Handler B called
Handler A called
Handler E called
Handler D called
Syntax error
```

---

### Example ID: 1190

**Description:** A practical example of a proactive error handler that automatically defines undeclared variables on the fly, allowing the expression to successfully resume execution.

**Code:**
```pseudocode
[head]
// This handler automatically defines variables when they are first used.
[callback:u AutoDefineHandler]
  // Check if the error is specifically an undefined identifier
  if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
    wl("Handler: '", uc.@Error().@Symbol(), "' is undefined. Defining it now.")
    uc.DefineVariable(uc.@Error().@Symbol());
    
    // Tell the engine to resume the operation
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
  end if
[/callback]

[body]
uc.@Error().AddHandler(AutoDefineHandler);

// 'my_var' doesn't exist yet, but the handler will create it.
var result = uc.EvalStr("my_var = 100; my_var = my_var * 2");

wl("Final result: ", result)
```

**Output:**
```
Handler: 'my_var' is undefined. Defining it now.
Final result: 200
```

---

---

## Code = [ErrorCode] - ID: 43
/doc/reference/classes/ucalc.errorinfo/code-=-[errorcode]/

**Description:** Retrieves the numeric code, as an ErrorCode enum member, for the most recently triggered error.

**Remarks:**

The `Code` property is the primary mechanism for identifying the specific *type* of error that occurred during parsing or evaluation. It is almost always used from within a custom error handler callback registered via [`AddErrorHandler`](/uCalc/AddErrorHandler).

### How It Works

The method returns an integer that directly corresponds to a member of the [`ErrorCode`](/Enums/ErrorCode) enumeration. This allows you to write clear, conditional logic to handle different error scenarios programmatically.

For example, you can check if the error was due to a missing variable and attempt to resolve it:
```pseudocode
if (uc.Error.@Code() == ErrorCode::Undefined_Identifier)
  //... handle the missing variable
end if
```

### Error State Lifecycle

An error code is set when an error is raised (either internally by uCalc or manually by your code). This error state persists until one of the following actions occurs, at which point the error is cleared and [pseudocode]`Error.@Code()` will return `ErrorCode::None` (0):

*   A successful call to [`Parse`](/uCalc/Parse), [`Eval`](/uCalc/Eval), or [`EvalStr`](/uCalc/EvalStr).
*   A successful call to any `Define*` method, such as `DefineVariable` or `DefineFunction`.

This behavior ensures that error information from a failed operation does not incorrectly affect the status of a subsequent, successful operation.

### Comparative Analysis

*   **vs. C# Exceptions**: In C#, errors are typically handled by catching specific exception types (e.g., `catch (DivideByZeroException)`). This involves stack unwinding, which can have a performance cost. uCalc's model uses callbacks and error codes, which avoids this overhead. This is particularly advantageous when parsing user input, where syntax errors are common and expected, not exceptional.
*   **vs. C-Style Error Codes**: Traditional C APIs often return integer error codes that the caller must check after every function call. uCalc centralizes this logic into a single handler, making the main application code cleaner and less cluttered with repetitive error-checking blocks.

In summary, `Error.Code` provides a structured, efficient, and centralized way to manage and respond to errors within the uCalc engine.

**Examples:**

### Example ID: 1457

**Description:** Checking the error code for a simple syntax error

**Code:**
```pseudocode
var result = uc.Eval("MyVar * 10");
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
```

**Output:**
```
An error has occurred!
Error #: 258
Error Message: Undefined identifier
Error Location: 0
Error Expression: MyVar * 10
```

---

### Example ID: 325

**Description:** Checking the error code for a simple syntax error using a callback.

**Code:**
```pseudocode
[head]
[callback:u MyHandler]
  // Retrieve the error code as an integer for display
  var(int, code) = [C](int)[/C]uc.@Error().@Code();
  wl("Caught Error Code: ", code)
  
  // Compare the error code against the ErrorCode enum for logic
  if (uc.@Error().@Code() == ErrorCode::Syntax_Error)
     wl("This was a syntax error.")
  end if
[/callback]

[body]
// Register the error handler
uc.@Error().AddHandler(MyHandler);

// Intentionally cause a syntax error, which will trigger the handler
wl(uc.EvalStr("5 *"))
```

**Output:**
```
Caught Error Code: 257
This was a syntax error.
Syntax error
```

---

### Example ID: 326

**Description:** Creating an error handler that automatically defines variables on the fly by checking for an 'Undefined Identifier' error.

**Code:**
```pseudocode
[head]
[callback:u AutoDefineHandler]
  // Check if the error is specifically an undefined identifier
  if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
    // If so, define the missing variable and instruct uCalc to resume
    wl("Auto-defining variable: '", uc.@Error().@Symbol(), "'")
    uc.DefineVariable(uc.@Error().@Symbol());
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
  end if
[/callback]

[body]
uc.@Error().AddHandler(AutoDefineHandler);

// 'x' doesn't exist, but the handler will intercept the error and create it.
var Result = uc.EvalStr("x = 10; x * 5");
wl("Result: ", Result)
```

**Output:**
```
Auto-defining variable: 'x'
Result: 50
```

---

### Example ID: 327

**Description:** Internal Test: Verifies that the error code is correctly cleared after a successful operation.

**Code:**
```pseudocode
// Trigger an error and check the code
uc.EvalStr("1+"); 
wl("1. Error code after failure: ", [C](int)[/C]uc.@Error().@Code()[VB].ToString("D")[/VB])

// A successful evaluation should clear the error code
uc.EvalStr("1+1");
wl("2. Error code after success: ", [C](int)[/C]uc.@Error().@Code()[VB].ToString("D")[/VB])

// Trigger a different type of error
uc.@Error().@TrapOnDivideByZero(true);
uc.EvalStr("1/0");
wl("3. Error code after new failure: ", [C](int)[/C]uc.@Error().@Code()[VB].ToString("D")[/VB])

// A successful definition should also clear the error code
uc.DefineVariable("x=5"); 
wl("4. Error code after successful definition: ", [C](int)[/C]uc.@Error().@Code()[VB].ToString("D")[/VB])
```

**Output:**
```
1. Error code after failure: 257
2. Error code after success: 0
3. Error code after new failure: 8
4. Error code after successful definition: 0
```

---

### Example ID: 1

**Description:** Adding an error handler callback

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Symbol: ", uc.@Error().@Symbol())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);
wl(uc.EvalStr("123+"))
wl("")

uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("5/0"))
```

**Output:**
```
An error has occurred!
Error #: 257
Error Message: Syntax error
Error Symbol: +
Error Location: 3
Error Expression: 123+
Syntax error

An error has occurred!
Error #: 8
Error Message: Division by 0
Error Symbol: 
Error Location: 0
Error Expression: 
Division by 0
```

---

### Example ID: 323

**Description:** Retrieves the generic message for a specific error code and compares it to the last error message.

**Code:**
```pseudocode
// Retrieve the built-in message for a specific error code, without triggering an error.
wl("Generic 'Undefined Identifier' message: ", uc.@Error().GetMessage(ErrorCode::Undefined_Identifier))

// Now, trigger a specific error by using an undefined variable.
uc.EvalStr("MyUndefinedVar + 5");

// Check the message and number for the last error that occurred.
wl("Last error message: ", uc.@Error().@Message())
wl("Last error number: ", [c](int)[/c][vb]CType([/vb]uc.@Error().@Code()[vb], Integer)[/vb])
```

**Output:**
```
Generic 'Undefined Identifier' message: Undefined identifier
Last error message: Undefined identifier
Last error number: 258
```

---

### Example ID: 324

**Description:** Internal Test: Verifies that the error state is correctly cleared after a subsequent successful operation.

**Code:**
```pseudocode
// Internal Test: Verify error state is cleared
wl("--- Testing Error State Lifecycle ---")

// 1. Trigger a division-by-zero error.
uc.@Error().@TrapOnDivideByZero(true);
uc.EvalStr("1 / 0");
wl("Message after 1/0: '", uc.@Error().@Message(), "'")
wl("Error number is not None: ", bool(uc.@Error().@Code() != ErrorCode::None))

// 2. Perform a successful operation, which should clear the previous error state.
uc.EvalStr("1 + 1");

// 3. Verify the error message and number have been reset.
wl("Message after successful op: '", uc.@Error().@Message(), "'")
wl("Error number is now None: ", bool(uc.@Error().@Code() == ErrorCode::None))
```

**Output:**
```
--- Testing Error State Lifecycle ---
Message after 1/0: 'Division by 0'
Error number is not None: True
Message after successful op: 'No error'
Error number is now None: True
```

---

### Example ID: 329

**Description:** Practical: Creates a robust error handler that automatically defines variables on-the-fly when an 'Undefined Identifier' error occurs.

**Code:**
```pseudocode
[head]
// This error handler allows you to use variables that were not
// explicitly defined previously by defining unrecognized identifiers
// as variables instead of returning an error.
[callback:u AutoVariableDef]
   if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
      uc.DefineVariable(uc.@Error().@Symbol());
      uc.@Error().@Response(ErrorHandlerResponse::Resume);
   end if
[/callback]

[body]
uc.@Error().AddHandler(AutoVariableDef);
// The handler will automatically define 'AutoTest' on first use.
wl(uc.Eval("AutoTest = 123"))
wl(uc.Eval("AutoTest * 1000"))
```

**Output:**
```
123
123000
```

---

---

## Expression = [string] - ID: 39
/doc/reference/classes/ucalc.errorinfo/expression-=-[string]/

**Description:** Returns the full expression string that was being processed when a parsing error occurred.

**Remarks:**

This property is a key diagnostic tool used within an error handler callback to retrieve the source expression that triggered a **parsing-stage error**.

When uCalc processes an expression with a function like [EvalStr()](/uCalc/EvalStr), errors can occur at two distinct stages:

1.  **Parsing Stage**: This is when uCalc analyzes the structure and syntax of the input string. Errors include syntax mistakes, undefined identifiers, or mismatched brackets. During this stage, `ErrorExpression()` returns the complete, original expression string.

2.  **Evaluation Stage**: This occurs after a successful parse, when uCalc executes the parsed tree. Errors include division by zero, invalid function arguments, or floating-point overflows. During this stage, the original expression string is no longer in context, so `ErrorExpression()` returns an **empty string**.

This distinction is crucial for building robust error handlers. By checking if `ErrorExpression()` is empty, a handler can determine whether the failure was syntactic or computational.

### Usage in Error Handlers

This method is almost exclusively called from within a callback registered with [uCalc.AddErrorHandler()](/uCalc/AddErrorHandler). It works in conjunction with other diagnostic functions to provide a complete picture of the error:

*   [Error.Code](/uCalc/Error.Code): The numeric error code.
*   [Error.Message](/uCalc/ErrorMessage): The human-readable error description.
*   [Error.Symbol](/uCalc/ErrorSymbol): The specific token that caused the parse to fail.
*   [Error.Location](/uCalc/ErrorLocation): The character position of the error within the expression.

### # Comparative Analysis

In standard programming languages like C# or C++, a `try-catch` block provides an exception object with properties like `Message` and `StackTrace`. However, it typically does not give you the original line of source code or expression string that failed. `ErrorExpression()` provides this high-level context directly, allowing for more intelligent error reporting and even programmatic correction, which is a significant advantage of uCalc's error handling model.

**Examples:**

### Example ID: 318

**Description:** An internal test to confirm that ErrorExpression returns an empty string for an error triggered manually by a user function during evaluation.

**Code:**
```pseudocode
[head]
[callback MyFunc]
  // This error occurs during evaluation, not parsing.
  cb.@Error().Raise("Manual evaluation failure!");
[/callback]

[callback:u MyHandler]
  wl("Handler triggered for error: ", uc.@Error().@Message())
  wl("ErrorExpression() returned: '", uc.@Error().@Expression(), "'")
  wl("Is expression empty? ", bool(uc.@Error().@Expression() == ""))
[/callback]

[body]
uc.DefineFunction("MyFunc()", MyFunc);
uc.@Error().AddHandler(MyHandler);

// The expression 'MyFunc()' itself is valid syntactically.
wl(uc.EvalStr("MyFunc()"))
```

**Output:**
```
Handler triggered for error: Manual evaluation failure!
ErrorExpression() returned: ''
Is expression empty? True
Manual evaluation failure!
```

---

### Example ID: 1

**Description:** Adding an error handler callback

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Symbol: ", uc.@Error().@Symbol())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);
wl(uc.EvalStr("123+"))
wl("")

uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("5/0"))
```

**Output:**
```
An error has occurred!
Error #: 257
Error Message: Syntax error
Error Symbol: +
Error Location: 3
Error Expression: 123+
Syntax error

An error has occurred!
Error #: 8
Error Message: Division by 0
Error Symbol: 
Error Location: 0
Error Expression: 
Division by 0
```

---

---

## FloatingPointErrorsToTrap = [Int32] - ID: 49
/doc/reference/classes/ucalc.errorinfo/floatingpointerrorstotrap-=-[int32]/

**Description:** Configures which IEEE 754 floating-point exceptions will raise a uCalc error instead of returning `inf` or `nan`.

**Remarks:**

By default, uCalc follows the standard IEEE 754 behavior for floating-point exceptions: operations like `1/0` return `inf` and `0/0` return `nan` without interrupting execution. The `FloatingPointErrorsToRaise` method allows you to override this behavior, instructing the engine to treat these events as catchable uCalc errors.

This provides a centralized way to enforce stricter arithmetic rules and prevent silent propagation of non-finite values through complex calculations.

### ⚙️ How It Works


`uc.FloatingPointErrorsToRaise`, can retrieve the current integer bitmask of enabled flags.
Or you can pass a bitmask of flags to enable them. You can construct the bitmask using integer values or, more readably, by combining members of the [Error.Code](/enum/errorcode) enum that start with `Float`.

### ✅ Available Flags

The relevant flags are members of the [ErrorCode](/enum/errorcode) enumeration:

| Flag | Value | Triggers On | Default Behavior |
|---|---|---|---|
| `FloatDivisionByZero` | 8 | Division by zero (e.g., `1/0`). | Returns `inf`. |
| `FloatInvalid` | 16 | Invalid operations (e.g., `0/0`, `sqrt(-1)`). | Returns `nan`. |
| `FloatOverflow` | 4 | Result exceeds the maximum representable value. | Returns `inf`. |
| `FloatUnderflow` | 2 | Result is too small to be represented (close to zero). | Returns `0`. |
| `FloatInexact` | 1 | *Currently not implemented.* | | 

Helper methods like [RaiseOnDivideByZero](/ucalc/RaiseOnDivideByZero) provide a more direct way to toggle individual flags.

### ⚖️ Comparative Analysis

**uCalc's Approach vs. Native Language Exceptions (`try/catch`)**

Most programming languages handle floating-point exceptions through hardware-level signals that can be mapped to language-level exceptions (e.g., `ArithmeticException` in C#). While powerful, `try/catch` blocks can introduce significant performance overhead, making them unsuitable for use inside performance-critical loops.

uCalc's mechanism operates within its own error system. When a floating-point error is raised, it sets an internal error state that can be checked via [Error.Code](/ucalc/error.code) or handled by a callback defined with [AddHandler](/ucalc/addhandler). This approach avoids the high cost of native exception handling, allowing for robust error checking even in tight loops where performance is paramount.

**Examples:**

### Example ID: 348

**Description:** The getter and setter functionality for a single flag.

**Code:**
```pseudocode
// Get the initial state (default is 0, no errors raised)
wl("Initial flags: ", uc.@Error().@FloatingPointErrorsToTrap())

// Enable raising an error for division by zero
uc.@Error().@FloatingPointErrorsToTrap([c](int)[/c][vb]CInt([/vb]ErrorCode::FloatDivisionByZero[vb])[/vb]);

// Verify the new state
wl("Updated flags: ", uc.@Error().@FloatingPointErrorsToTrap())

// Test the behavior
wl("1/0 = ", uc.EvalStr("1/0"))

// Disable the flag by setting it back to 0
uc.@Error().@FloatingPointErrorsToTrap(0);
wl("Flags after reset: ", uc.@Error().@FloatingPointErrorsToTrap())
wl("1/0 after reset = ", uc.EvalStr("1/0"))
```

**Output:**
```
Initial flags: 0
Updated flags: 8
1/0 = Division by 0
Flags after reset: 0
1/0 after reset = inf
```

---

### Example ID: 349

**Description:** Demonstrates enabling multiple floating-point error types and observing the results.

**Code:**
```pseudocode
wl("--- Default Behavior (No Errors Raised) ---")
wl("1/0: ", uc.EvalStr("1/0"))
wl("0/0: ", uc.EvalStr("0/0"))
wl("Overflow (5*10^308): ", uc.EvalStr("5*10^308"))
wl("Underflow (10^-308/10000): ", uc.EvalStr("10^-308/10000"))

wl("")
wl("--- Enable Invalid Operation & Underflow ---")
// You can pass multiple enum members to enable them simultaneously
uc.@Error().SetFloatingPointErrorsToTrap(ErrorCode::FloatInvalid, ErrorCode::FloatUnderflow);
wl("Current flags: ", uc.@Error().@FloatingPointErrorsToTrap()) // Should be 16 (Invalid) + 2 (Underflow) = 18

wl("1/0: ", uc.EvalStr("1/0")) // Not enabled, returns inf
wl("0/0: ", uc.EvalStr("0/0")) // Enabled, raises error
wl("Overflow (5*10^308): ", uc.EvalStr("5*10^308")) // Not enabled, returns inf
wl("Underflow (10^-308/10000): ", uc.EvalStr("10^-308/10000")) // Enabled, raises error
```

**Output:**
```
--- Default Behavior (No Errors Raised) ---
1/0: inf
0/0: nan
Overflow (5*10^308): inf
Underflow (10^-308/10000): 0

--- Enable Invalid Operation & Underflow ---
Current flags: 18
1/0: inf
0/0: Invalid operation
Overflow (5*10^308): inf
Underflow (10^-308/10000): Floating point underflow
```

---

### Example ID: 350

**Description:** Internal Test: Verifies that setting and clearing all possible floating-point flags works correctly.

**Code:**
```pseudocode
// Combine all flags using integer values (or bitwise OR on enums)
var allFlags = [c]2 | 4 | 8 | 16[/c][vb]2 Or 4 Or 8 Or 16[/vb]; // Underflow, Overflow, DivByZero, Invalid
uc.@Error().@FloatingPointErrorsToTrap(allFlags);
wl("All flags set: ", uc.@Error().@FloatingPointErrorsToTrap())

// Test all conditions
wl("Underflow: ", uc.EvalStr("1e-320"))
wl("Overflow: ", uc.EvalStr("1e320"))
wl("DivByZero: ", uc.EvalStr("1/0"))
wl("Invalid: ", uc.EvalStr("0/0"))

// Clear all flags
uc.@Error().@FloatingPointErrorsToTrap(0);
wl("")
wl("All flags cleared: ", uc.@Error().@FloatingPointErrorsToTrap())

// Verify they are cleared
wl("Underflow: ", uc.EvalStr("1e-320"))
wl("Overflow: ", uc.EvalStr("1e320"))
wl("DivByZero: ", uc.EvalStr("1/0"))
wl("Invalid: ", uc.EvalStr("0/0"))
```

**Output:**
```
All flags set: 30
Underflow: Floating point underflow
Overflow: Floating point overflow
DivByZero: Division by 0
Invalid: Invalid operation

All flags cleared: 0
Underflow: 0
Overflow: inf
DivByZero: inf
Invalid: nan
```

---

### Example ID: 74

**Description:** Raising floating point errors with FloatingPointErrorsToTrap

**Code:**
```pseudocode
wl(uc.@Error().@FloatingPointErrorsToTrap())
wl(uc.EvalStr("1/0"))
wl(uc.EvalStr("0/0"))
wl(uc.EvalStr("5*10^308"))
wl(uc.EvalStr("10^-308/10000"))

wl("--- Raise Div-by-0 ---")
uc.@Error().@FloatingPointErrorsToTrap([c](int)[/c][vb]CInt([/vb]ErrorCode::FloatDivisionByZero[vb])[/vb]);
wl(uc.@Error().@FloatingPointErrorsToTrap())
wl(uc.EvalStr("1/0"))
wl(uc.EvalStr("0/0"))
wl(uc.EvalStr("5*10^308"))
wl(uc.EvalStr("10^-308/10000"))

wl("--- Raise overflow ---")
uc.@Error().@FloatingPointErrorsToTrap([c](int)[/c][vb]CInt([/vb]ErrorCode::FloatOverflow[vb])[/vb]);
wl(uc.@Error().@FloatingPointErrorsToTrap())
wl(uc.EvalStr("1/0"))
wl(uc.EvalStr("0/0"))
wl(uc.EvalStr("5*10^308"))
wl(uc.EvalStr("10^-308/10000"))

wl("--- Raise invalid & underflow ---")
uc.@Error().SetFloatingPointErrorsToTrap(ErrorCode::FloatInvalid, ErrorCode::FloatUnderflow);
wl(uc.@Error().@FloatingPointErrorsToTrap()) // ErrorCode::FloatInvalid + ErrorCode::FloatUnderflow
wl(uc.EvalStr("1/0"))
wl(uc.EvalStr("0/0"))
wl(uc.EvalStr("5*10^308"))
wl(uc.EvalStr("10^-308/10000"))
```

**Output:**
```
0
inf
nan
inf
0
--- Raise Div-by-0 ---
8
Division by 0
nan
inf
0
--- Raise overflow ---
4
Floating point overflow
nan
Floating point overflow
0
--- Raise invalid & underflow ---
18
inf
Invalid operation
inf
Floating point underflow
```

---

---

## GetMessage - ID: 848
/doc/reference/classes/ucalc.errorinfo/getmessage/

**Description:** Retrieves the descriptive message for a specific error code.

**Syntax:** GetMessage(ErrorCode)
**Parameters:**
errCode - ErrorCode - Enum member to retrieve a specific error message.
**Return:** string - The error message as a string. Returns "No error" if no error has occurred or if the specified `errorId` is `ErrorCode::None`.
**Remarks:**

When called with an enum member, like [pseudocode]`uc.ErrorMessage(ErrorCode::Syntax_Error)`, it returns the generic, built-in message for that specific error code, regardless of what the last error was. This is useful for building custom error displays or documentation.

**Examples:**

### Example ID: 802

**Description:** GetMessage

**Code:**
```pseudocode
wl(uc.@Error().GetMessage(ErrorCode::Syntax_Error))
wl(uc.@Error().GetMessage(ErrorCode::FloatOverflow))
```

**Output:**
```
Syntax error
Floating point overflow
```

---

---

## Location = [int] - ID: 41
/doc/reference/classes/ucalc.errorinfo/location-=-[int]/

**Description:** Returns the zero-based character position where a parsing error was detected.

**Remarks:**

The `Location` property is a crucial tool for diagnosing issues within an expression, designed to be called from inside an error handler callback registered with [`AddErrorHandler`](/ucalc/uCalc/AddErrorHandler).

### 🎯 Parsing vs. Evaluation Errors

The value returned by `ErrorLocation` depends on the type of error that occurred:

*   **Parsing-Stage Errors:** For syntax errors, unrecognized tokens, or mismatched brackets, `ErrorLocation` returns the **zero-based character index** in the original expression string where the parser first detected the problem. This allows you to pinpoint the exact location of the faulty syntax.

*   **Evaluation-Stage Errors:** For mathematical or logical errors that occur during calculation (e.g., division by zero), `ErrorLocation` will return **0**. This is because the error is not tied to a specific character in the input string but is a result of the computation itself. To get information about these types of errors, you should rely on [`Error.Code`](/ucalc/uCalc/Error.Code) and [`ErrorMessage`](/ucalc/uCalc/ErrorMessage).

The provided examples clearly illustrate this distinction.

### Related Error Handling Functions
`ErrorLocation` is part of a suite of functions available within an error handler:
*   [`Error.Code`](/ucalc/uCalc/Error.Code): Gets the numeric code for the error.
*   [`Error.Message`](/ucalc/uCalc/ErrorMessage): Gets the descriptive error message string.
*   [`Error.Symbol`](/ucalc/uCalc/ErrorSymbol): Identifies the specific token or symbol that caused a parsing error.
*   [`Error.Expression`](/ucalc/uCalc/ErrorExpression): Returns the full expression being processed.

### ⚖️ Comparative Analysis

In other parsing systems, obtaining error locations can be complex. For example:
*   **Manual Parsing:** A developer would need to meticulously track the current index or cursor position while iterating through the string.
*   **Parser Generators (e.g., ANTLR):** These tools often provide rich context objects with line and column numbers but require a deeper understanding of the generated parse tree and visitor patterns.

uCalc simplifies this by providing a direct, single-function call—`uc.ErrorLocation()`—that gives immediate access to the relevant character position without any manual tracking or complex object navigation. This strikes a balance between simplicity and utility, making it easy to build user-friendly feedback systems.

**Examples:**

### Example ID: 321

**Description:** Capturing both parsing-stage and evaluation-stage errors to see how ErrorLocation behaves differently.

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
wl("--- Error Captured ---")
wl("Message: ", uc.@Error().@Message())
wl("Symbol: '", uc.@Error().@Symbol(), "'")
wl("Location: ", uc.@Error().@Location())
wl("Expression: '", uc.@Error().@Expression(), "'")
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);

wl("Demonstrating a PARSING error:")
uc.EvalStr("123//456");

wl("")
wl("Demonstrating an EVALUATION error:")
uc.@Error().@TrapOnDivideByZero(true);
uc.EvalStr("5/0");
```

**Output:**
```
Demonstrating a PARSING error:
--- Error Captured ---
Message: Syntax error
Symbol: '/'
Location: 3
Expression: '123//456'

Demonstrating an EVALUATION error:
--- Error Captured ---
Message: Division by 0
Symbol: ''
Location: 0
Expression: ''
```

---

### Example ID: 1

**Description:** Adding an error handler callback

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Symbol: ", uc.@Error().@Symbol())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);
wl(uc.EvalStr("123+"))
wl("")

uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("5/0"))
```

**Output:**
```
An error has occurred!
Error #: 257
Error Message: Syntax error
Error Symbol: +
Error Location: 3
Error Expression: 123+
Syntax error

An error has occurred!
Error #: 8
Error Message: Division by 0
Error Symbol: 
Error Location: 0
Error Expression: 
Division by 0
```

---

---

## Message = [string] - ID: 42
/doc/reference/classes/ucalc.errorinfo/message-=-[string]/

**Description:** Retrieves the descriptive message for the last error that occurred.

**Remarks:**

The `Message` property is a key part of uCalc's state-based error handling model. It provides a simple way to inspect error details without relying on traditional exception handling, which can be advantageous in performance-critical loops.

It returns the message for the most recent error triggered by an operation like [pseudocode]`EvalStr()`, [pseudocode]`Parse()`, or [pseudocode]`Define()`. If the last operation was successful, it returns the message for `ErrorCode::None` ("No error").

--- 

### ⚙️ Error State Lifecycle

It is crucial to understand that uCalc's error state (including the error message, number, and location) is **transient**. The state is automatically cleared and reset by the next operation that is initiated. 

For example, if `EvalStr("1/0")` fails, `ErrorMessage()` will return "Division by 0". If the next call is `EvalStr("2+2")`, which succeeds, the error state is cleared, and `ErrorMessage()` will subsequently return "No error".

--- 

### 🆚 Comparative Analysis: State-Based Errors vs. Exceptions

Most modern languages use a `try/catch` mechanism for error handling. This pattern interrupts the normal flow of execution and unwinds the stack to find a handler.

**Traditional `try/catch` (e.g., C#, C++):**
```csharp
// C# Example
try
{
    result = PerformCalculation(input);
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message); // Message is tied to the exception object
}
```

**uCalc's State-Based Model:**
```pseudocode
// uCalc's approach
uc.EvalStr("some invalid input");
if (uc.Error.GetCode() != ErrorCode::None) 
{
    wl(uc.Error.GetMessage()); // Message is retrieved from the uCalc instance's state
}
```

uCalc's approach avoids the overhead associated with throwing and catching exceptions, making it suitable for scenarios where invalid user input is common and performance is a priority. The program flow is not interrupted, allowing the developer to check for an error state and react accordingly.

**Examples:**

### Example ID: 322

**Description:** Demonstrates getting the last error message after a failed operation.

**Code:**
```pseudocode
// Attempt to evaluate an expression with unbalanced parenthesis causing a syntax error.
uc.EvalStr("5 * (10 +");

// Check the error message from the last operation.
wl("Last error message: ", uc.@Error().@Message())
```

**Output:**
```
Last error message: Bracket delimiter error
```

---

### Example ID: 323

**Description:** Retrieves the generic message for a specific error code and compares it to the last error message.

**Code:**
```pseudocode
// Retrieve the built-in message for a specific error code, without triggering an error.
wl("Generic 'Undefined Identifier' message: ", uc.@Error().GetMessage(ErrorCode::Undefined_Identifier))

// Now, trigger a specific error by using an undefined variable.
uc.EvalStr("MyUndefinedVar + 5");

// Check the message and number for the last error that occurred.
wl("Last error message: ", uc.@Error().@Message())
wl("Last error number: ", [c](int)[/c][vb]CType([/vb]uc.@Error().@Code()[vb], Integer)[/vb])
```

**Output:**
```
Generic 'Undefined Identifier' message: Undefined identifier
Last error message: Undefined identifier
Last error number: 258
```

---

### Example ID: 324

**Description:** Internal Test: Verifies that the error state is correctly cleared after a subsequent successful operation.

**Code:**
```pseudocode
// Internal Test: Verify error state is cleared
wl("--- Testing Error State Lifecycle ---")

// 1. Trigger a division-by-zero error.
uc.@Error().@TrapOnDivideByZero(true);
uc.EvalStr("1 / 0");
wl("Message after 1/0: '", uc.@Error().@Message(), "'")
wl("Error number is not None: ", bool(uc.@Error().@Code() != ErrorCode::None))

// 2. Perform a successful operation, which should clear the previous error state.
uc.EvalStr("1 + 1");

// 3. Verify the error message and number have been reset.
wl("Message after successful op: '", uc.@Error().@Message(), "'")
wl("Error number is now None: ", bool(uc.@Error().@Code() == ErrorCode::None))
```

**Output:**
```
--- Testing Error State Lifecycle ---
Message after 1/0: 'Division by 0'
Error number is not None: True
Message after successful op: 'No error'
Error number is now None: True
```

---

### Example ID: 1

**Description:** Adding an error handler callback

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Symbol: ", uc.@Error().@Symbol())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);
wl(uc.EvalStr("123+"))
wl("")

uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("5/0"))
```

**Output:**
```
An error has occurred!
Error #: 257
Error Message: Syntax error
Error Symbol: +
Error Location: 3
Error Expression: 123+
Syntax error

An error has occurred!
Error #: 8
Error Message: Division by 0
Error Symbol: 
Error Location: 0
Error Expression: 
Division by 0
```

---

---

## Raise - ID: 879
/doc/reference/classes/ucalc.errorinfo/raise/

---

## Raise(string) - ID: 107
/doc/reference/classes/ucalc.errorinfo/raise/raise-string/

**Description:** Raises an error from within a callback function, allowing for a custom, dynamic error message.

**Syntax:** Raise(string)
**Parameters:**
errorMessage - string - The custom error message to be raised.
**Return:** ErrorHandlerResponse - Returns a value from the [ErrorHandlerResponse](/reference/enums/errorhandlerresponse) enum, indicating the action taken by the error handler (e.g., Abort, Resume, or ReRaise).
**Remarks:**

The `ErrorRaiseMessage` method allows a callback function to halt execution and signal an error using a custom, dynamically-generated message. This provides more context-specific feedback than [ErrorRaise](/reference/ucalc/callback/errorraise), which is limited to predefined error codes from the [ErrorCode](/reference/enums/errorcode) enumeration.

This method is the primary mechanism for custom validation logic within callbacks. When an error is raised, the uCalc engine's error handling pipeline is invoked. An error handler, registered with [AddErrorHandler](/reference/ucalc/mainclassgroup/adderrorhandler), can inspect the message and decide whether to [Abort](/reference/enums/errorhandlerresponse), [Resume](/reference/enums/errorhandlerresponse), or [ReRaise](/reference/enums/errorhandlerresponse) the error.

End-user expressions can achieve similar functionality by using the built-in [Error()](/reference/functions_and_operators/functions/specialized) function.

### Comparative Analysis: uCalc Errors vs. Native Exceptions

In languages like C# or C++, errors are typically signaled by throwing exceptions.

**C# Exception Example:**
```csharp
if (value > 100)
{
    throw new ArgumentOutOfRangeException("Value cannot exceed 100.");
}
```

This approach interrupts the program's flow and unwinds the call stack until a `catch` block is found.

uCalc's error system is different. It's a state-based mechanism that does not unwind the stack.

**uCalc Callback Example:**
```pseudocode
if (cb.Arg(1) > 100)
    cb.ErrorRaiseMessage("Value cannot exceed 100.");
end if
```

When `ErrorRaiseMessage` is called:
1.  The engine's error state is set (`Error.Code` and `ErrorMessage`).
2.  The error handler callback stack is invoked.
3.  The handler can choose to **recover** from the error and resume execution, a powerful feature not easily replicated with standard exceptions.

This model is more lightweight and offers greater control over the execution flow, which is ideal for environments where user-input errors are common and recoverable.

**Examples:**

### Example ID: 482

**Description:** A function that unconditionally raises a custom error.

**Code:**
```pseudocode
[head]
[callback:u MyHandler]
    // This handler just logs the error and aborts
    wl("Error Handler Caught: ", uc.@Error().@Message())
[/callback]
[callback MyFunc]
    // This function always fails with a custom message
    cb.@Error().Raise("Validation failed for input.");
[/callback]
[body]
uc.@Error().AddHandler(MyHandler);
uc.DefineFunction("Validate()", MyFunc);
uc.EvalStr("Validate()"); // This call will trigger the error
```

**Output:**
```
Error Handler Caught: Validation failed for input.
```

---

### Example ID: 483

**Description:** Raises an error with a dynamic message if a validation check fails within a callback.

**Code:**
```pseudocode
[head]
[callback ValidateValue]
    var val = cb.Arg(1);
    if (val > 100)
        // The error message includes the problematic value, making it dynamic.
        cb.@Error().Raise("Value exceeds maximum of 100. Got: " + [cpp]to_string((int)val)[/cpp][NotCpp]val.ToString()[/NotCpp]);
    else
        cb.Return(val);
    end if
[/callback]
[body]
uc.DefineFunction("CheckValue(val)", ValidateValue);
wl(uc.EvalStr("CheckValue(50)"))
wl(uc.EvalStr("CheckValue(123)"))
```

**Output:**
```
50
Value exceeds maximum of 100. Got: 123
```

---

### Example ID: 484

**Description:** Internal Test: Demonstrates error recovery by having an error handler resume execution after a custom error is raised.

**Code:**
```pseudocode
[head]
[callback:u RecoveryHandler]
    wl("Handler: Caught '", uc.@Error().@Message(), "'")
    // Attempt to recover by resuming execution.
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
    wl("Handler: Resuming execution...")
[/callback]
[callback RiskyOperation]
    var input = cb.ArgStr(1);
    if (input == "bad")
        cb.@Error().Raise("A recoverable error occurred.");
        // After the error handler resumes, this return value will be used.
 
    else
        cb.ReturnStr("Normal_OK");
    end if
[/callback]
[body]
uc.@Error().AddHandler(RecoveryHandler);
uc.DefineFunction("DoWork(s As String) As String", RiskyOperation);

wl("Result: " + uc.EvalStr("DoWork('good')"))
wl("---")
wl("Result: " + uc.EvalStr("DoWork('bad')"))
```

**Output:**
```
Result: Normal_OK
---
Handler: Caught 'A recoverable error occurred.'
Handler: Resuming execution...
Result: A recoverable error occurred.
```

---

### Example ID: 39

**Description:** Raises an error in a callback using a customized message with ErrorRaiseMessage

**Code:**
```pseudocode
[head]
[callback RaiseErrorMessageCallback]
if (cb.Arg(1) == 123)
   cb.@Error().Raise("I do not like this value!");
   cb.Return(cb.Arg(1));
end if
[/callback]
[body]

uc.DefineFunction("ErrRaiseMsgTest(Value)", RaiseErrorMessageCallback);
wl(uc.EvalStr("ErrRaiseMsgTest(111)"))
wl(uc.EvalStr("ErrRaiseMsgTest(123)"))
```

**Output:**
```
111
I do not like this value!
```

---

---

## Raise(ErrorCode) - ID: 106
/doc/reference/classes/ucalc.errorinfo/raise/raise-errorcode/

**Description:** Triggers a predefined uCalc error from within a custom callback function, returning the final response from the error handler chain.

**Syntax:** Raise(ErrorCode)
**Parameters:**
errCode - ErrorCode - The predefined error to trigger, selected from the `ErrorCode` enumeration.
**Return:** ErrorHandlerResponse - An `ErrorHandlerResponse` value indicating the action requested by any registered error handlers. The callback should typically return this value to the uCalc engine to ensure the error is handled correctly.
**Remarks:**

The `ErrorRaise` method provides a controlled way to trigger an error from within a callback function. Unlike a native `throw` statement, this method invokes uCalc's internal error handling system, allowing registered handlers to intercept, log, or even recover from the error before it halts execution.

### How It Works
1.  Your callback calls `ErrorRaise` with a specific `ErrorCode` code.
2.  The uCalc engine invokes the chain of error handlers registered via [AddErrorHandler](/reference/uCalc/AddErrorHandler).
3.  Handlers can respond with `Abort`, `Resume`, or `ReRaise`.
4.  `ErrorRaise` returns the final [ErrorHandlerResponse](/reference/Enums/ErrorHandlerResponse) determined by the handler chain.

### Handling the Return Value
The return value from `ErrorRaise` is crucial. It informs your callback what action the error handlers decided upon. Your callback can inspect this value and act accordingly. For example, if an error handler successfully resolves a problem and requests to `Resume`, your callback can continue its logic instead of aborting.

For custom error messages, use [ErrorRaiseMessage](/reference/uCalc/Callback/ErrorRaiseMessage) instead.

### ⚖️ Comparative Analysis

*   **vs. Native `throw` (C#/C++)**: A native `throw` immediately unwinds the call stack, interrupting the flow of execution. `ErrorRaise` does not. It is a controlled, synchronous call *into* the uCalc error system. It returns a value to your callback, giving it the opportunity to react to the outcome of the error handling process without unwinding the native stack.

*   **vs. C-Style Return Codes**: While it returns a code, `ErrorRaise` is far more powerful. Instead of just signaling that an error occurred, it actively triggers a sophisticated, layered handling system ([AddErrorHandler](/reference/uCalc/AddErrorHandler)) that can dynamically resolve issues.

**Examples:**

### Example ID: 479

**Description:** Triggering a standard syntax error if the input value is negative.

**Code:**
```pseudocode
[head]
[callback DoublePositive]
  // If input is negative, raise a syntax error.
  if (cb.Arg(1) < 0)
    cb.@Error().Raise(ErrorCode::Syntax_Error);
  end if
  cb.Return(cb.Arg(1) * 2);
[/callback]
[body]
uc.DefineFunction("DoublePositive(x)", DoublePositive);
wl(uc.EvalStr("DoublePositive(10)"))
wl(uc.EvalStr("DoublePositive(-5)"))
```

**Output:**
```
20
Syntax error
```

---

### Example ID: 37

**Description:** Raising an error in a callback with ErrorRaise

**Code:**
```pseudocode
[head]
[callback RaiseErrorCallback]
if (cb.Arg(1) == 123)
  cb.@Error().Raise(ErrorCode::Unrecognized_Command);
end if
cb.Return(cb.Arg(1));
[/callback]
[body]

uc.DefineFunction("ErrRaiseTest(Value)", RaiseErrorCallback);
wl(uc.EvalStr("ErrRaiseTest(111)"))
wl(uc.EvalStr("ErrRaiseTest(123)")) // The callback arbitrarily raises an error for 123
```

**Output:**
```
111
Unrecognized command
```

---

---

## Response = [ErrorHandlerResponse] - ID: 44
/doc/reference/classes/ucalc.errorinfo/response-=-[errorhandlerresponse]/

**Description:** Determines the engine's behavior after an error handler callback finishes executing.

**Remarks:**

The `Response` property is the primary control mechanism used inside an [AddErrorHandler](/classes/ucalc/adderrorhandler) callback to dictate the flow of execution after an error has been intercepted. It determines whether the engine should abort the operation, attempt to recover and continue, or delegate the error to another handler in the chain.

This method can only be called from within an error handler's callback function.

--- 

## ⚙️ Handler Responses

You must provide a value from the [ErrorHandlerResponse](/enums/errorhandlerresponse) enum:

*   `ErrorHandlerResponse::Abort` (Default)
    This is the standard behavior. It immediately halts the parsing or evaluation process. The original function call (e.g., `EvalStr`) will fail and return an error message. Use this when the error is unrecoverable.

*   `ErrorHandlerResponse::Resume`
    This powerful option instructs the uCalc engine to continue execution from where it left off, as if the error never occurred. This is ideal for creating robust, fault-tolerant applications that can recover from invalid input.

    ⚠️ **Important**: Before resuming, your handler **must** resolve the condition that caused the error. For example, if the error was `Undefined_Identifier`, you might define the variable. Failure to resolve the issue will likely cause an infinite loop as the engine repeatedly encounters the same error.

*   `ErrorHandlerResponse::ReRaise`
    This passes the current error to the next handler in the stack. It allows for creating layered or tiered error-handling strategies. For instance, an initial handler might simply log all errors and then `ReRaise` them, allowing a more specific, subsequent handler to decide whether to `Abort` or `Resume`.

---

### Comparative Analysis

*   **vs. Traditional `try-catch`**
    Standard exception handling in languages like C# and C++ is primarily about unwinding the stack and aborting a block of code. `try-catch` provides a way to fail gracefully. uCalc's model, particularly with `Resume`, offers a fundamentally different paradigm: **error recovery**. It allows an operation to be repaired and continued, which is essential for interactive applications, live editors, or long-running calculations where simply aborting is not desirable.

*   **vs. LISP Condition System**
    The combination of intercepting an error, choosing a recovery strategy (`Resume`), and delegating responsibility (`ReRaise`) is conceptually similar to the highly-regarded Common Lisp Condition System. This system separates the act of signaling an error from the logic that handles it, providing a level of flexibility rarely seen outside of Lisp-like languages. This makes uCalc's error handling exceptionally powerful for complex parsing and evaluation tasks.

**Examples:**

### Example ID: 329

**Description:** Practical: Creates a robust error handler that automatically defines variables on-the-fly when an 'Undefined Identifier' error occurs.

**Code:**
```pseudocode
[head]
// This error handler allows you to use variables that were not
// explicitly defined previously by defining unrecognized identifiers
// as variables instead of returning an error.
[callback:u AutoVariableDef]
   if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
      uc.DefineVariable(uc.@Error().@Symbol());
      uc.@Error().@Response(ErrorHandlerResponse::Resume);
   end if
[/callback]

[body]
uc.@Error().AddHandler(AutoVariableDef);
// The handler will automatically define 'AutoTest' on first use.
wl(uc.Eval("AutoTest = 123"))
wl(uc.Eval("AutoTest * 1000"))
```

**Output:**
```
123
123000
```

---

### Example ID: 54

**Description:** Error handler to auto-define variables

**Code:**
```pseudocode
[head]
// This error handler allows you to use variables that were not
// explicitly defined previously, by defining the unrecognized identifiers
// as variables instead of returning an error
[callback:u AutoVariableDef]
   if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
      uc.DefineVariable(uc.@Error().@Symbol());
      uc.@Error().@Response(ErrorHandlerResponse::Resume);
   end if
[/callback]

[body]
uc.@Error().AddHandler(AutoVariableDef);
wl(uc.Eval("AutoTest = 123"))
wl(uc.Eval("AutoTest * 1000"))
```

**Output:**
```
123
123000
```

---

### Example ID: 1190

**Description:** A practical example of a proactive error handler that automatically defines undeclared variables on the fly, allowing the expression to successfully resume execution.

**Code:**
```pseudocode
[head]
// This handler automatically defines variables when they are first used.
[callback:u AutoDefineHandler]
  // Check if the error is specifically an undefined identifier
  if (uc.@Error().@Code() == ErrorCode::Undefined_Identifier)
    wl("Handler: '", uc.@Error().@Symbol(), "' is undefined. Defining it now.")
    uc.DefineVariable(uc.@Error().@Symbol());
    
    // Tell the engine to resume the operation
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
  end if
[/callback]

[body]
uc.@Error().AddHandler(AutoDefineHandler);

// 'my_var' doesn't exist yet, but the handler will create it.
var result = uc.EvalStr("my_var = 100; my_var = my_var * 2");

wl("Final result: ", result)
```

**Output:**
```
Handler: 'my_var' is undefined. Defining it now.
Final result: 200
```

---

---

## Symbol = [string] - ID: 45
/doc/reference/classes/ucalc.errorinfo/symbol-=-[string]/

**Description:** Returns the specific symbol or token that triggered a parsing-stage error.

**Remarks:**

The `Symbol` property is a crucial tool for diagnosing and recovering from errors within a custom error handler. When an error occurs during the **parsing stage**, this function returns the specific text of the symbol (e.g., an undefined variable name, a misplaced operator) that caused the failure.

This function is most effective when used inside a callback registered with [uCalc.AddErrorHandler](/reference/ucalc/adderrorhandler).

### Parsing vs. Evaluation Errors

The behavior of `ErrorSymbol` depends on when the error occurs:

*   **📝 Parsing-Stage Errors**: For errors like `Undefined_Identifier` or `Syntax_Error`, `ErrorSymbol` returns the problematic token. This allows for powerful recovery logic. For example, if a user types an undefined variable, you can capture its name with `ErrorSymbol` and define it on the fly.
*   **⚙️ Evaluation-Stage Errors**: For errors that occur during calculation, such as `FloatDivisionByZero`, there is no single "symbol" at fault. In these cases, `ErrorSymbol` will return an **empty string**. You can check for an empty result to determine if the error was contextual or computational.

### Common `ErrorSymbol` Results

| Error Type (`ErrorCode`) | Example Expression | `ErrorSymbol()` Result |
| :--- | :--- | :--- |
| `Undefined_Identifier` | `x * 10` (where `x` is not defined) | `"x"` |
| `Syntax_Error` | `5 +++ 3` (if `+++` is not a valid operator) | `"+++"` |
| `FloatDivisionByZero` | `1 / 0` | `""` (empty string) |
| `Invalid_Argument_Count` | `Sin(1, 2)` | `"Sin"` |

### 💡 Comparative Analysis

Compared to traditional `try-catch` blocks in C# or C++, uCalc's error handling provides far more granular context. A standard exception might tell you "An object reference was not found," but `ErrorSymbol` tells you the *exact name* of the object that was missing.

This level of detail transforms error handling from a simple reporting mechanism into a powerful recovery system. The ability to get the problematic symbol allows you to build self-healing expressions that can, for example, auto-define variables or suggest corrections to the user, a feat that is difficult to achieve with generic exception handling alone.


**Examples:**

### Example ID: 1

**Description:** Adding an error handler callback

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Symbol: ", uc.@Error().@Symbol())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);
wl(uc.EvalStr("123+"))
wl("")

uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("5/0"))
```

**Output:**
```
An error has occurred!
Error #: 257
Error Message: Syntax error
Error Symbol: +
Error Location: 3
Error Expression: 123+
Syntax error

An error has occurred!
Error #: 8
Error Message: Division by 0
Error Symbol: 
Error Location: 0
Error Expression: 
Division by 0
```

---

---

## TrapOnDivideByZero = [bool] - ID: 73
/doc/reference/classes/ucalc.errorinfo/trapondividebyzero-=-[bool]/

**Description:** Enables or disables the raising of a formal uCalc error when a division by zero occurs, overriding the default IEEE 754 behavior.

**Remarks:**

By default, uCalc adheres to the IEEE 754 standard for floating-point arithmetic, where division by zero does not halt execution but instead returns `inf` (infinity). The `RaiseErrorOnDivideByZero` method allows you to override this behavior, instructing the engine to treat division by zero as a formal, catchable uCalc error.

This is crucial for applications requiring strict validation where non-finite values like `inf` or `nan` are considered invalid results.

### ⚙️ How It Works
- **`RaiseErrorOnDivideByZero(true)`**: Enables error raising.
- **`RaiseErrorOnDivideByZero(false)`**: Disables error raising, reverting to the default `inf` behavior.

This method is a convenient shortcut for manipulating the `FloatDivisionByZero` flag within the engine's error bitmask. For configuring multiple floating-point exceptions at once, see the more general [`FloatingPointErrorsToRaise`](/reference/ucalc/mainclassgroup/floatingpointerrorstoraise) method.

### ⚠️ Important Distinction: `Eval` vs. `EvalStr`
The effect of this setting depends on the evaluation function you use:
*   **[`EvalStr`](/reference/ucalc/mainclassgroup/evalstr) / [`EvaluateStr`](/reference/expression/evaluatestr)**: When an error is raised, these functions return the error message as a string (e.g., `"Division by 0"`).
*   **[`Eval`](/reference/ucalc/mainclassgroup/eval) / [`Evaluate`](/reference/expression/evaluate)**: These functions *always* return a `double`. Even with error raising enabled, a division by zero will still result in `inf`. To check for an error after calling these, you must inspect [`uc.Error.Code`](/reference/ucalc/mainclassgroup/errorcode).

### ⚖️ Comparative Analysis: uCalc Errors vs. Native Exceptions

In languages like C# or C++, arithmetic errors typically throw exceptions (e.g., `DivideByZeroException`), which involves a costly stack-unwinding process.

uCalc's error model is state-based and designed for performance. Instead of throwing an exception, it sets an internal error flag and can invoke a lightweight callback registered with [`AddErrorHandler`](/reference/ucalc/mainclassgroup/adderrorhandler). This approach is significantly faster and makes uCalc ideal for scenarios where errors are expected and common, such as parsing unvalidated user input in a loop, without the performance penalty of traditional `try/catch` blocks.

**Examples:**

### Example ID: 403

**Description:** Toggling the error-raising behavior for division by zero.

**Code:**
```pseudocode
// Default behavior: returns infinity
wl("Default: ", uc.EvalStr("1/0"))

// Enable error raising
uc.@Error().@TrapOnDivideByZero(true);
wl("Error Enabled: ", uc.EvalStr("1/0"))

// Disable error raising
uc.@Error().@TrapOnDivideByZero(false);
wl("Error Disabled: ", uc.EvalStr("1/0"))
```

**Output:**
```
Default: inf
Error Enabled: Division by 0
Error Disabled: inf
```

---

### Example ID: 405

**Description:** Internal Test: Verifies that only the division by zero flag is affected, while other floating-point exceptions like overflow remain unchanged by default.

**Code:**
```pseudocode
// Enable only the division by zero error
uc.@Error().@TrapOnDivideByZero(true);

// This should now raise a uCalc error
wl("Test 1 (Div by Zero): ", uc.EvalStr("1/0"))

// This should still return 'inf' by default, as we didn't enable overflow errors
wl("Test 2 (Overflow): ", uc.EvalStr("1e308 * 2"))

// For comparison, enable overflow errors as well
uc.@Error().@TrapOnOverflow(true);
wl("Test 3 (Overflow with error): ", uc.EvalStr("1e308 * 2"))
```

**Output:**
```
Test 1 (Div by Zero): Division by 0
Test 2 (Overflow): inf
Test 3 (Overflow with error): Floating point overflow
```

---

### Example ID: 1

**Description:** Adding an error handler callback

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
wl("An error has occurred!")
wl("Error #: ", [c](int)uc.@Error().@Code()[/c][vb]CInt(uc.@Error().@Code())[/vb])
wl("Error Message: ", uc.@Error().@Message())
wl("Error Symbol: ", uc.@Error().@Symbol())
wl("Error Location: ", uc.@Error().@Location())
wl("Error Expression: ", uc.@Error().@Expression())
[/callback]

[body]
uc.@Error().AddHandler(MyErrorHandler);
wl(uc.EvalStr("123+"))
wl("")

uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("5/0"))
```

**Output:**
```
An error has occurred!
Error #: 257
Error Message: Syntax error
Error Symbol: +
Error Location: 3
Error Expression: 123+
Syntax error

An error has occurred!
Error #: 8
Error Message: Division by 0
Error Symbol: 
Error Location: 0
Error Expression: 
Division by 0
```

---

### Example ID: 80

**Description:** RaiseErrorOnDivideByZero

**Code:**
```pseudocode
wl(uc.EvalStr("1/0"))
uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("1/0"))

wl(uc.EvalStr("Sqrt(-1)"))
uc.@Error().@TrapOnInvalid(true);
wl(uc.EvalStr("Sqrt(-1)"))

wl(uc.EvalStr("5*10^308"))
uc.@Error().@TrapOnOverflow(true);
wl(uc.EvalStr("5*10^308"))

wl(uc.EvalStr("10^-308/10000"))
uc.@Error().@TrapOnUnderflow(true);
wl(uc.EvalStr("10^-308/10000"))
```

**Output:**
```
inf
Division by 0
nan
Invalid operation
inf
Floating point overflow
0
Floating point underflow
```

---

---

## TrapOnInvalid = [bool] - ID: 75
/doc/reference/classes/ucalc.errorinfo/traponinvalid-=-[bool]/

**Description:** Controls whether invalid floating-point operations (e.g., sqrt(-1)) raise a formal error or return `nan`.

**Remarks:**

By default, uCalc follows the standard IEEE 754 behavior for invalid floating-point operations: operations like `sqrt(-1)` or `0/0` return `nan` (Not a Number) without interrupting execution. The `RaiseErrorOnInvalid` method allows you to override this behavior, instructing the engine to treat these events as catchable uCalc errors.

This provides a centralized way to enforce stricter arithmetic rules and prevent silent propagation of non-finite values through complex calculations.

### ⚙️ Behavior

*   **Disabled (Default)**: An expression like [pseudocode]`uc.EvalStr("sqrt(-1)")` returns the string `"nan"`.
*   **Enabled**: Calling [pseudocode]`uc.RaiseErrorOnInvalid(true)` changes the behavior. The same expression will now trigger a `FloatInvalid` error. The `EvalStr` call will return the error message (e.g., "Invalid operation"), and the error can be intercepted by a handler registered with [AddErrorHandler](/reference/ucalc/adderrorhandler).

This is a convenience method that acts as a shortcut for modifying the master bitmask controlled by [FloatingPointErrorsToRaise](/reference/ucalc/floatingpointerrorstoraise).

### ⚖️ Comparative Analysis

Most programming languages handle floating-point exceptions through hardware-level signals that can be mapped to language-level exceptions (e.g., `ArithmeticException` in C#). While powerful, `try/catch` blocks can introduce significant performance overhead.

uCalc's mechanism operates within its own error system. When a floating-point error is raised, it sets an internal error state that can be checked via [Error.Code](/reference/ucalc/errorcode) or handled by a callback. This approach avoids the high cost of native exception handling, allowing for robust error checking even in tight loops where performance is paramount.

**Examples:**

### Example ID: 406

**Description:** How to enable error raising for invalid operations.

**Code:**
```pseudocode
// By default, invalid operations return 'nan'
wl(uc.EvalStr("sqrt(-1)"))

// Enable error raising for this specific case
uc.@Error().@TrapOnInvalid(true);

// Now, the same operation returns a descriptive error message
wl(uc.EvalStr("sqrt(-1)"))
```

**Output:**
```
nan
Invalid operation
```

---

### Example ID: 407

**Description:** A practical example using an error handler to provide a custom, user-friendly message when an invalid operation occurs.

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
  // Check if the specific 'FloatInvalid' error was raised
  if (uc.@Error().@Code() == ErrorCode::FloatInvalid)
    wl("Error: The calculation resulted in an invalid number (e.g., square root of a negative).")
    // Stop further processing
    uc.@Error().@Response(ErrorHandlerResponse::Abort);
  end if
[/callback]

[body]
// Register the custom error handler
uc.@Error().AddHandler(MyErrorHandler);

// Tell uCalc to raise an error instead of returning 'nan'
uc.@Error().@TrapOnInvalid(true);

// This will now trigger our custom error handler's message
uc.EvalStr("sqrt(-4)");
```

**Output:**
```
Error: The calculation resulted in an invalid number (e.g., square root of a negative).
```

---

### Example ID: 408

**Description:** Internal test verifying the behavior of all `RaiseErrorOn...` flag methods.

**Code:**
```pseudocode
// --- Division by Zero ---
wl(uc.EvalStr("1/0"))
uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("1/0"))

// --- Invalid Operation ---
wl(uc.EvalStr("Sqrt(-1)"))
uc.@Error().@TrapOnInvalid(true);
wl(uc.EvalStr("Sqrt(-1)"))

// --- Overflow ---
wl(uc.EvalStr("5*10^308"))
uc.@Error().@TrapOnOverflow(true);
wl(uc.EvalStr("5*10^308"))

// --- Underflow ---
wl(uc.EvalStr("10^-308/10000"))
uc.@Error().@TrapOnUnderflow(true);
wl(uc.EvalStr("10^-308/10000"))
```

**Output:**
```
inf
Division by 0
nan
Invalid operation
inf
Floating point overflow
0
Floating point underflow
```

---

### Example ID: 80

**Description:** RaiseErrorOnDivideByZero

**Code:**
```pseudocode
wl(uc.EvalStr("1/0"))
uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("1/0"))

wl(uc.EvalStr("Sqrt(-1)"))
uc.@Error().@TrapOnInvalid(true);
wl(uc.EvalStr("Sqrt(-1)"))

wl(uc.EvalStr("5*10^308"))
uc.@Error().@TrapOnOverflow(true);
wl(uc.EvalStr("5*10^308"))

wl(uc.EvalStr("10^-308/10000"))
uc.@Error().@TrapOnUnderflow(true);
wl(uc.EvalStr("10^-308/10000"))
```

**Output:**
```
inf
Division by 0
nan
Invalid operation
inf
Floating point overflow
0
Floating point underflow
```

---

---

## TrapOnOverflow = [bool] - ID: 76
/doc/reference/classes/ucalc.errorinfo/traponoverflow-=-[bool]/

**Description:** Configures the engine to raise a catchable uCalc error upon floating-point overflow instead of silently returning infinity.

**Remarks:**

By default, uCalc follows the standard IEEE 754 behavior for floating-point exceptions: an operation that results in a value exceeding the maximum representable number for a `double` returns `inf` (infinity) without interrupting execution. The `RaiseErrorOnOverflow` method allows you to override this behavior, instructing the engine to treat this event as a catchable uCalc error.

This provides a centralized way to enforce stricter arithmetic rules and prevent the silent propagation of non-finite values through complex calculations.

This method is a convenience wrapper for setting a specific flag via the more general [FloatingPointErrorsToRaise](/reference/ucalc/ucalc/floatingpointerrorstoraise) method. The following two calls are equivalent:

```pseudocode
// Using the convenience method
uc.RaiseErrorOnOverflow(true);

// Using the general-purpose method
uc.FloatingPointErrorsToRaise(uCalc::ErrorCode::FloatOverflow);
```

### ⚖️ Comparative Analysis: uCalc Errors vs. Native Exceptions

Most programming languages handle floating-point exceptions through hardware-level signals that can be mapped to language-level exceptions (e.g., `ArithmeticException` in C#). While powerful, `try/catch` blocks can introduce significant performance overhead, making them unsuitable for use inside performance-critical loops where invalid user input might be common.

uCalc's mechanism operates within its own error system. When a floating-point error is raised, it sets an internal error state that can be checked via [Error.Code](/reference/ucalc/ucalc/errorcode) or handled by a callback defined with [AddErrorHandler](/reference/ucalc/ucalc/adderrorhandler). This approach avoids the high cost of native exception handling, allowing for robust error checking even in tight loops where performance is paramount.

**Examples:**

### Example ID: 409

**Description:** How to toggle overflow error reporting on and off.

**Code:**
```pseudocode
// 1. Default behavior: returns 'inf'
wl(uc.EvalStr("1e308 * 10"))

// 2. Enable error raising for overflow
uc.@Error().@TrapOnOverflow(true);
wl(uc.EvalStr("1e308 * 10"))

// 3. Disable it again to revert to default
uc.@Error().@TrapOnOverflow(false);
wl(uc.EvalStr("1e308 * 10"))
```

**Output:**
```
inf
Floating point overflow
inf
```

---

### Example ID: 410

**Description:** A practical example demonstrating all four related floating-point error configuration methods.

**Code:**
```pseudocode
wl("Divide by Zero (Default): ", uc.EvalStr("1/0"))
uc.@Error().@TrapOnDivideByZero(true);
wl("Divide by Zero (Error Enabled): ", uc.EvalStr("1/0"))

wl("")
wl("Invalid Operation (Default): ", uc.EvalStr("Sqrt(-1)"))
uc.@Error().@TrapOnInvalid(true);
wl("Invalid Operation (Error Enabled): ", uc.EvalStr("Sqrt(-1)"))

wl("")
wl("Overflow (Default): ", uc.EvalStr("5*10^308"))
uc.@Error().@TrapOnOverflow(true);
wl("Overflow (Error Enabled): ", uc.EvalStr("5*10^308"))

wl("")
wl("Underflow (Default): ", uc.EvalStr("10^-308/10000"))
uc.@Error().@TrapOnUnderflow(true);
wl("Underflow (Error Enabled): ", uc.EvalStr("10^-308/10000"))
```

**Output:**
```
Divide by Zero (Default): inf
Divide by Zero (Error Enabled): Division by 0

Invalid Operation (Default): nan
Invalid Operation (Error Enabled): Invalid operation

Overflow (Default): inf
Overflow (Error Enabled): Floating point overflow

Underflow (Default): 0
Underflow (Error Enabled): Floating point underflow
```

---

### Example ID: 411

**Description:** Internal Test: An overflow error is intercepted by a custom error handler.

**Code:**
```pseudocode
[head]
[callback:u MyErrorHandler]
    wl("--- Error Handler Caught ---")
    wl("  Code: ", [c](int)[/c][vb]CInt([/vb]uc.@Error().@Code()[vb])[/vb])
    wl("  Message: ", uc.@Error().@Message())
    // Abort is the default response, no need to set it.
[/callback]

[body]
// Register the custom error handler
uc.@Error().AddHandler(MyErrorHandler);

// Configure the engine to raise an error on overflow
uc.@Error().@TrapOnOverflow(true);

// This evaluation will now be intercepted by our handler
wl("Evaluating expression '1e999'...")
uc.EvalStr("1e999"); // This triggers the callback
wl("Evaluation finished.")
```

**Output:**
```
Evaluating expression '1e999'...
--- Error Handler Caught ---
  Code: 4
  Message: Floating point overflow
Evaluation finished.
```

---

### Example ID: 80

**Description:** RaiseErrorOnDivideByZero

**Code:**
```pseudocode
wl(uc.EvalStr("1/0"))
uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("1/0"))

wl(uc.EvalStr("Sqrt(-1)"))
uc.@Error().@TrapOnInvalid(true);
wl(uc.EvalStr("Sqrt(-1)"))

wl(uc.EvalStr("5*10^308"))
uc.@Error().@TrapOnOverflow(true);
wl(uc.EvalStr("5*10^308"))

wl(uc.EvalStr("10^-308/10000"))
uc.@Error().@TrapOnUnderflow(true);
wl(uc.EvalStr("10^-308/10000"))
```

**Output:**
```
inf
Division by 0
nan
Invalid operation
inf
Floating point overflow
0
Floating point underflow
```

---

### Example ID: 405

**Description:** Internal Test: Verifies that only the division by zero flag is affected, while other floating-point exceptions like overflow remain unchanged by default.

**Code:**
```pseudocode
// Enable only the division by zero error
uc.@Error().@TrapOnDivideByZero(true);

// This should now raise a uCalc error
wl("Test 1 (Div by Zero): ", uc.EvalStr("1/0"))

// This should still return 'inf' by default, as we didn't enable overflow errors
wl("Test 2 (Overflow): ", uc.EvalStr("1e308 * 2"))

// For comparison, enable overflow errors as well
uc.@Error().@TrapOnOverflow(true);
wl("Test 3 (Overflow with error): ", uc.EvalStr("1e308 * 2"))
```

**Output:**
```
Test 1 (Div by Zero): Division by 0
Test 2 (Overflow): inf
Test 3 (Overflow with error): Floating point overflow
```

---

---

## TrapOnUnderflow = [bool] - ID: 77
/doc/reference/classes/ucalc.errorinfo/traponunderflow-=-[bool]/

**Description:** Configures whether a floating-point underflow raises a catchable uCalc error instead of silently returning 0.

**Remarks:**

By default, uCalc follows the standard IEEE 754 behavior for floating-point underflow: an operation that results in a value too small to be represented returns `0` without interrupting execution. The `RaiseErrorOnUnderflow` method allows you to override this, instructing the engine to treat underflow as a catchable uCalc error.

This provides a way to enforce stricter arithmetic rules and detect calculations that lose precision, which can be critical in scientific or financial applications.

### Default Behavior vs. Error Raising

| Setting | Expression | `EvalStr` Result | `Eval` Result |
| :--- | :--- | :--- | :--- |
| `RaiseErrorOnUnderflow(false)` | `1e-320` | `"0"` | `0.0` |
| `RaiseErrorOnUnderflow(true)` | `1e-320` | `"Floating point underflow"` | `0.0` |

**Note**: The numeric-only [Eval()](/reference/ucalc/mainclassgroup/eval) method will still return `0` even when this flag is enabled. To capture the error, you must use a method that can return a string, like [EvalStr()](/reference/ucalc/mainclassgroup/evalstr), or use a custom error handler with [AddErrorHandler()](/reference/ucalc/mainclassgroup/adderrorhandler).

For bulk configuration of all floating-point error types, use the [FloatingPointErrorsToRaise()](/reference/ucalc/mainclassgroup/floatingpointerrorstoraise) method.

### 💡 Comparative Analysis: State-Based Errors vs. Native Exceptions

Most programming languages handle arithmetic issues through hardware-level signals that map to language exceptions (e.g., `ArithmeticException` in C#). While powerful, `try/catch` blocks can introduce significant performance overhead, making them unsuitable for performance-critical loops where errors might be common.

_uCalc's approach is different_. It operates within its own error system. When an error is raised, it sets an internal state that can be checked via [Error.Code](/reference/ucalc/mainclassgroup/errorcode) or handled by a callback. This model avoids the high cost of native exception handling, allowing for robust error checking even in tight loops without a performance penalty.

**Examples:**

### Example ID: 80

**Description:** RaiseErrorOnDivideByZero

**Code:**
```pseudocode
wl(uc.EvalStr("1/0"))
uc.@Error().@TrapOnDivideByZero(true);
wl(uc.EvalStr("1/0"))

wl(uc.EvalStr("Sqrt(-1)"))
uc.@Error().@TrapOnInvalid(true);
wl(uc.EvalStr("Sqrt(-1)"))

wl(uc.EvalStr("5*10^308"))
uc.@Error().@TrapOnOverflow(true);
wl(uc.EvalStr("5*10^308"))

wl(uc.EvalStr("10^-308/10000"))
uc.@Error().@TrapOnUnderflow(true);
wl(uc.EvalStr("10^-308/10000"))
```

**Output:**
```
inf
Division by 0
nan
Invalid operation
inf
Floating point overflow
0
Floating point underflow
```

---

---

## uCalc.Callback - ID: 92
/doc/reference/classes/ucalc.callback/

**Description:** Class for retrieving arguments passed to a callback, returning a value, and more

---

## Introduction - ID: 959
/doc/reference/classes/ucalc.callback/introduction/

**Description:** An object passed to native callbacks, providing the interface to get arguments, set return values, and interact with the uCalc engine.

**Remarks:**

# 🤝 The Callback Object: Bridging uCalc and Native Code

The `uCalc.Callback` class is the essential interface for communication between the uCalc engine and a native callback function in your host application (C#, C++, etc.). You do not create an instance of this class yourself; instead, a `Callback` object is automatically passed as the sole argument to any native function you register with [DefineFunction](/Reference/uCalcBase/uCalc/DefineFunction) or [DefineOperator](/Reference/uCalcBase/uCalc/DefineOperator).

In all documentation examples, this object is referred to by the conventional name `cb`.

Its primary roles are:
1.  **Getting Arguments**: Retrieving the values passed from the expression to your native code.
2.  **Setting Return Values**: Sending a result from your native code back to the expression.
3.  **Accessing Context**: Interacting with the parent uCalc instance, introspecting the calling function, and handling errors.

---

## 📂 Argument Retrieval Methods
These methods are used to get the values passed to your function from the uCalc expression.

| Member | Description |
| :--- | :--- |
| [`Arg`](/Reference/uCalcBase/Callback/Arg) | Retrieves a numeric argument as a double-precision float. |
| [`Arg1`](/Reference/uCalcBase/Callback/Arg1) | A high-performance shortcut for retrieving the first numeric argument. |
| [`Arg2`](/Reference/uCalcBase/Callback/Arg2) | A high-performance shortcut for retrieving the second numeric argument. |
| [`ArgAddr`](/Reference/uCalcBase/Callback/ArgAddr) | Retrieves a direct memory pointer to an argument's value, for low-level operations. |
| [`ArgBool`](/Reference/uCalcBase/Callback/ArgBool) | Retrieves a boolean argument, with automatic type conversion. |
| [`ArgCount`](/Reference/uCalcBase/Callback/ArgCount) | Gets the total number of arguments passed to the callback, essential for variadic functions. |
| [`ArgDbl`](/Reference/uCalcBase/Callback/ArgDbl) | Retrieves a double-precision argument, functionally identical to `Arg`. |
| [`ArgExpr`](/Reference/uCalcBase/Callback/ArgExpr) | Retrieves an argument as an unevaluated `Expression` object for lazy evaluation (`ByExpr`). |
| [`ArgInt16`](/Reference/uCalcBase/Callback/ArgInt16) | Retrieves a 16-bit integer argument. |
| [`ArgInt32`](/Reference/uCalcBase/Callback/ArgInt32) | Retrieves a 32-bit integer argument. |
| [`ArgInt64`](/Reference/uCalcBase/Callback/ArgInt64) | Retrieves a 64-bit integer argument. |
| [`ArgItem`](/Reference/uCalcBase/Callback/ArgItem) | Retrieves the full metadata `Item` object for an argument, for introspection (`ByHandle`). |
| [`ArgPtr`](/Reference/uCalcBase/Callback/ArgPtr) | Retrieves the value of an argument that is a pointer. |
| [`ArgStr`](/Reference/uCalcBase/Callback/ArgStr) | Retrieves an argument as a string, with automatic type conversion. |

## 📤 Return Value Methods
These methods are used to send a result from your callback back to the uCalc engine.

| Member | Description |
| :--- | :--- |
| [`Return`](/Reference/uCalcBase/Callback/Return) | Sets the double-precision return value for the callback. |
| [`ReturnBool`](/Reference/uCalcBase/Callback/ReturnBool) | Sets the boolean return value. |
| [`ReturnDbl`](/Reference/uCalcBase/Callback/ReturnDbl) | Sets the double-precision return value, functionally identical to `Return`. |
| [`ReturnInt16`](/Reference/uCalcBase/Callback/ReturnInt16) | Sets the 16-bit integer return value. |
| [`ReturnInt32`](/Reference/uCalcBase/Callback/ReturnInt32) | Sets the 32-bit integer return value. |
| [`ReturnInt64`](/Reference/uCalcBase/Callback/ReturnInt64) | Sets the 64-bit integer return value. |
| [`ReturnPtr`](/Reference/uCalcBase/Callback/ReturnPtr) | Sets a pointer as the return value. |
| [`ReturnStr`](/Reference/uCalcBase/Callback/ReturnStr) | Sets the string return value. |

## ⚙️ Context & Introspection
These properties provide access to the surrounding execution environment.

| Member | Description |
| :--- | :--- |
| [`uCalc`](/Reference/uCalcBase/Callback/uCalc) | Retrieves the parent `uCalc` instance that is executing the callback. |
| [`Item`](/Reference/uCalcBase/Callback/Item) | Retrieves the `Item` object for the function or operator that triggered the callback. |

## 💣 Error Handling
These members allow you to manage errors from within a callback.

| Member | Description |
| :--- | :--- |
| [`Error`](/Reference/uCalcBase/Callback/Error) | Provides access to the `ErrorInfo` object to raise errors or inspect error state. |
| [`Raise`](/Reference/uCalcBase/ErrorInfo/Raise) | Triggers a uCalc error with a predefined code or a custom message. |

## 🔍 Low-Level & Diagnostics

| Member | Description |
| :--- | :--- |
| [`Handle`](/Reference/uCalcBase/Callback/Handle) | Retrieves the internal, low-level identifier for the callback context object. |

**Examples:**

### Example ID: 11

**Description:** How to define a custom function using a native callback.

**Code:**
```pseudocode
[head]
[callback MyArea]
// Retrieve the 1st and 2nd arguments passed to the function
var Length = cb.Arg(1); 
var Width = cb.Arg(2);

// Calculate the area and return the result to the uCalc engine.
// This logic pattern translates seamlessly across languages.
cb.Return(Length * Width); // Same as cb.ReturnDbl
[/callback]
[body]
uc.DefineFunction("Area(x, y)", MyArea);
wl(uc.Eval("Area(3, 4)"))
```

**Output:**
```
12
```

---

### Example ID: 12

**Description:** Defining a callback function with a variable number of arguments

**Code:**
```pseudocode
[head]
[callback MyAverage]
var(double, Total) = 0;
for(int x = 1 to cb.ArgCount())
   Total = Total + cb.Arg(x);
end for
cb.Return(Total / cb.ArgCount());
[/callback]
[body]
uc.DefineFunction("Average(x ...)", MyAverage);
wl(uc.Eval("Average(10, 3, 7, 4)"))
```

**Output:**
```
6
```

---

---

## (Constructor) - ID: 649
/doc/reference/classes/ucalc.callback/-constructor/

**Description:** uCalc.Callback constructor

**Remarks:**

Callbacks object are not meant to be explicitly constructed.  Instead it is passed as an argument for a callback function.

**Examples:**

### Example ID: 11

**Description:** How to define a custom function using a native callback.

**Code:**
```pseudocode
[head]
[callback MyArea]
// Retrieve the 1st and 2nd arguments passed to the function
var Length = cb.Arg(1); 
var Width = cb.Arg(2);

// Calculate the area and return the result to the uCalc engine.
// This logic pattern translates seamlessly across languages.
cb.Return(Length * Width); // Same as cb.ReturnDbl
[/callback]
[body]
uc.DefineFunction("Area(x, y)", MyArea);
wl(uc.Eval("Area(3, 4)"))
```

**Output:**
```
12
```

---

### Example ID: 12

**Description:** Defining a callback function with a variable number of arguments

**Code:**
```pseudocode
[head]
[callback MyAverage]
var(double, Total) = 0;
for(int x = 1 to cb.ArgCount())
   Total = Total + cb.Arg(x);
end for
cb.Return(Total / cb.ArgCount());
[/callback]
[body]
uc.DefineFunction("Average(x ...)", MyAverage);
wl(uc.Eval("Average(10, 3, 7, 4)"))
```

**Output:**
```
6
```

---

### Example ID: 14

**Description:** Passing arg ByExpr (delayed lazy eval) and ByHandle

**Code:**
```pseudocode
[head]
[callback MySum]
   var Total = 0.0;
   var Expr = cb.ArgExpr(1);
   var Start = cb.Arg(2);
   var Finish = cb.Arg(3);
   var Variable = cb.ArgItem(4);

   for(double x = Start to Finish)
      Variable.Value(x);
      Total += Expr.Evaluate();
   end for
   cb.Return(Total);
[/callback]
[body]
uc.DefineVariable("x");
uc.DefineFunction("Sum(ByExpr Expr, Start, Finish, ByHandle Var)", MySum);
wl(uc.Eval("Sum(x ^ 2, 1, 10, x)"))

```

**Output:**
```
385
```

---

---

## Arg - ID: 93
/doc/reference/classes/ucalc.callback/arg/

**Description:** Retrieves a numeric argument passed to a callback function, returned as a double-precision float.

**Syntax:** Arg(int)
**Parameters:**
index - int - The 1-based index of the argument to retrieve. The first argument is at index 1.
**Return:** double - The value of the specified argument, converted to a double-precision floating-point number.
**Remarks:**

The `Arg` method retrieves a numeric argument that was passed to a callback function, returning it as a `double`.

When a function or operator is defined using a callback with [DefineFunction](/Reference/uCalcBase/uCalc/DefineFunction) or [DefineOperator](/Reference/uCalcBase/uCalc/DefineOperator), this method is the primary way to access the values of its arguments from within your host application's code.

### ⚠️ 1-Based Indexing

Unlike most C-family languages that use 0-based indexing for arrays and lists, uCalc callback arguments are **1-based**. The first argument is at index `1`, the second is at index `2`, and so on. This is a crucial distinction to avoid off-by-one errors.

*   For a binary operator, the left operand is at index `1` and the right operand is at index `2`.
*   For a unary operator, the single operand is at index `1`.

For convenience, you can also use the parameterless [Arg1()](/Reference/uCalcBase/Callback/Arg1) and [Arg2()](/Reference/uCalcBase/Callback/Arg2) methods, which are slightly more efficient.

### 🎯 Type-Specific Alternatives

`Arg()` is the default getter for `double` values and is functionally identical to [ArgDbl()](/Reference/uCalcBase/Callback/ArgDbl). If your callback expects arguments of other types, you should use the corresponding type-specific methods for clarity and to avoid unnecessary conversions:

*   `ArgInt32()` for 32-bit integers.
*   `ArgStr()` for strings.
*   `ArgBool()` for booleans.
*   ... and so on for other supported types.

### 💡 Comparative Analysis

In native C++ or C#, retrieving arguments from a callback often involves variadic templates, `va_list`, or parameter arrays (`params object[]`), which can add complexity. uCalc's `Callback` object provides a simple, unified interface (`cb.Arg(1)`, `cb.ArgStr(2)`, etc.) that abstracts away these differences, providing a consistent API across all supported languages. This model simplifies the process of retrieving arguments, especially for functions with a variable number of arguments.

**Examples:**

### Example ID: 11

**Description:** How to define a custom function using a native callback.

**Code:**
```pseudocode
[head]
[callback MyArea]
// Retrieve the 1st and 2nd arguments passed to the function
var Length = cb.Arg(1); 
var Width = cb.Arg(2);

// Calculate the area and return the result to the uCalc engine.
// This logic pattern translates seamlessly across languages.
cb.Return(Length * Width); // Same as cb.ReturnDbl
[/callback]
[body]
uc.DefineFunction("Area(x, y)", MyArea);
wl(uc.Eval("Area(3, 4)"))
```

**Output:**
```
12
```

---

### Example ID: 12

**Description:** Defining a callback function with a variable number of arguments

**Code:**
```pseudocode
[head]
[callback MyAverage]
var(double, Total) = 0;
for(int x = 1 to cb.ArgCount())
   Total = Total + cb.Arg(x);
end for
cb.Return(Total / cb.ArgCount());
[/callback]
[body]
uc.DefineFunction("Average(x ...)", MyAverage);
wl(uc.Eval("Average(10, 3, 7, 4)"))
```

**Output:**
```
6
```

---

### Example ID: 297

**Description:** Demonstrates defining a function that is implemented by a native callback in the host application.

**Code:**
```pseudocode
[head]
[callback MyAreaCallback]
  var length = cb.Arg(1);
  var width = cb.Arg(2);
  cb.Return(length * width);
[/callback]

[body]
// The signature is defined, but the logic is provided by 'MyAreaCallback'.
uc.DefineFunction("Area(x, y)", MyAreaCallback);
wl(uc.Eval("Area(3, 4)"))
```

**Output:**
```
12
```

---

### Example ID: 14

**Description:** Passing arg ByExpr (delayed lazy eval) and ByHandle

**Code:**
```pseudocode
[head]
[callback MySum]
   var Total = 0.0;
   var Expr = cb.ArgExpr(1);
   var Start = cb.Arg(2);
   var Finish = cb.Arg(3);
   var Variable = cb.ArgItem(4);

   for(double x = Start to Finish)
      Variable.Value(x);
      Total += Expr.Evaluate();
   end for
   cb.Return(Total);
[/callback]
[body]
uc.DefineVariable("x");
uc.DefineFunction("Sum(ByExpr Expr, Start, Finish, ByHandle Var)", MySum);
wl(uc.Eval("Sum(x ^ 2, 1, 10, x)"))

```

**Output:**
```
385
```

---

---

## Arg1 - ID: 94
/doc/reference/classes/ucalc.callback/arg1/

**Description:** Returns the first argument passed to a callback function as a double-precision number.

**Syntax:** Arg1()
**Return:** double - The double-precision floating-point value of the first argument.
**Remarks:**

The `Arg1` method is a high-performance shortcut for retrieving the first (or only) argument passed to a [Callback](/reference/ucalc/callback/) function. It is functionally identical to calling `Arg(1)` but is slightly more efficient as it avoids the overhead of an indexed lookup.

This method is exclusively used within the body of a callback function that has been registered with [DefineFunction](/reference/ucalc/definefunction/) or [DefineOperator](/reference/ucalc/defineoperator/). It simplifies the implementation of unary functions and operators where only one input is expected.

### 💡 Why uCalc? (Comparative Analysis)

In most languages, accessing function arguments involves indexing into an array or list.

*   **C# / VB.NET**: Similar to accessing `args[0]` in a `params object[] args` array, but `Arg1` is type-specific and avoids the casting and indexing steps.
*   **C++**: Conceptually similar to accessing the first element in a variadic template pack or a `va_list`.

uCalc provides `Arg1` (and its counterpart [Arg2](/reference/ucalc/callback/arg2/)) as a convenience that leads to cleaner and more readable callback code, especially for simple mathematical operations. It reinforces the contract that a particular callback expects a specific number of arguments.

For arguments of other data types or for accessing arguments by a dynamic index, use the general-purpose [Arg](/reference/ucalc/callback/arg/) method or its type-specific variants like `ArgStr` or `ArgInt32`.

**Examples:**

---

## Arg2 - ID: 95
/doc/reference/classes/ucalc.callback/arg2/

**Description:** Retrieves the second argument passed to a callback function as a double-precision number.

**Syntax:** Arg2()
**Return:** double - The second argument as a double-precision floating-point number. Returns 0 if fewer than two arguments were passed.
**Remarks:**

The `Arg2()` method is a high-performance shortcut for retrieving the second argument passed to a callback function. It is functionally identical to calling [Arg(2)](/reference/ucalcbase/callback/arg) but avoids the overhead of passing an index, making it slightly more efficient.

This method is primarily a convenience for callbacks linked to binary operators or functions that take exactly two numeric arguments. It complements [Arg1()](/reference/ucalcbase/callback/arg1), which retrieves the first argument.

### Data Type
`Arg2()` specifically retrieves the argument as a `double`. If you need to access arguments of other types, use the corresponding type-safe methods:
*   [ArgStr()](/reference/ucalcbase/callback/argstr)
*   [ArgInt32()](/reference/ucalcbase/callback/argint32)
*   [ArgBool()](/reference/ucalcbase/callback/argbool)

### 💡 Why uCalc? (Comparative Analysis)

In many languages like C# or C++, a callback or delegate signature explicitly names its parameters:

```csharp
// Standard C# delegate
public delegate double MathOperation(double operand1, double operand2);
```

uCalc uses a different architectural pattern. The callback receives a single, unified `Callback` object (`cb`), and you use methods like `Arg1()` and `Arg2()` to retrieve arguments by position from that object. This model offers several advantages:

*   **Flexibility**: A single callback function can be registered to handle multiple uCalc functions or operators, even those with different numbers of arguments. The callback can use [ArgCount()](/reference/ucalcbase/callback/argcount) at runtime to determine how it was called.
*   **Metaprogramming**: This object-based approach allows the callback to access rich metadata about the arguments via methods like [ArgItem()](/reference/ucalcbase/callback/argitem) or [ArgExpr()](/reference/ucalcbase/callback/argexpr), which is not possible with simple value parameters.

**Examples:**

---

## ArgAddr - ID: 96
/doc/reference/classes/ucalc.callback/argaddr/

**Description:** Retrieves a direct memory pointer to the value of an argument passed to a callback function.

**Syntax:** ArgAddr(int)
**Parameters:**
index - int - The 1-based index of the argument. The first argument is at index 1, the second at 2, and so on.
**Return:** IntPtr - Returns a raw memory pointer (`void*` or `IntPtr`) to the argument's value. This pointer must be cast to the correct type before use.
**Remarks:**

The `ArgAddr` method is a low-level tool for advanced callback scenarios, providing direct memory access to an argument's value. It is typically used when a strongly-typed accessor (like `ArgInt32` or `ArgStr`) is not available for a specific data type, or when you need to interact with the argument's underlying memory.

### Core Use Cases

1.  **Generic Value Retrieval**: When working with custom or non-standard data types, `ArgAddr` provides a universal way to get a pointer to the value. You can then use the argument's [DataType](/reference/ucalc/datatype) object to safely read or convert this value.

2.  **Modifying `ByRef` Arguments**: If a function parameter is defined with the `ByRef` modifier, `ArgAddr` gives you the memory address of the original variable. This allows the callback to modify the variable's value in the caller's scope, a key feature for creating functions with side effects.

### `ArgAddr` vs. `ArgPtr`

It is crucial to understand the distinction between these two methods:

*   `ArgAddr(n)`: Returns the memory address **of the nth argument itself**. This is the location on the call stack or in a register where the argument's value is stored.
*   `ArgPtr(n)`: Returns the value **of the nth argument**, assuming that value is a pointer. It reads the data from the argument's location and interprets it as a memory address.

See the internal test example for a practical demonstration of this difference.

### ⚖️ Comparative Analysis

In native C/C++, accessing function arguments might involve variadic argument lists (`va_list`) or direct stack manipulation, which can be unsafe and complex. uCalc's [Callback](/reference/ucalc/callback) model abstracts this away.

*   **Without uCalc**: You would rely on the language's native argument passing mechanisms. Interacting with different data types would require templates (C++) or boxing/unboxing (C#), and getting a pointer to an argument can be tricky.
*   **With uCalc**: `ArgAddr` provides a consistent, safe, and platform-agnostic way to get a memory pointer to an argument within the sandboxed uCalc environment. It simplifies interoperability between the uCalc engine and the host application's data.

**Note**: The argument `index` is 1-based. The first argument is at index 1, not 0.

**Examples:**

### Example ID: 16

**Description:** How to handle and retrieve various data types (including pointers) within a callback.

**Code:**
```pseudocode
[head]
[callback MyFunction]
   var uc = cb.@uCalc();
   wl("------ MyFunc ------")

   // Retrieve standard 32-bit and 64-bit integer arguments directly
   wl(cb.ArgInt32(1))
   wl(cb.ArgInt64(2))

   // Retrieve the value of a pointer argument by referencing its exact data type.
   wl(uc.ItemOf("Int8").@DataType().ToString(cb.ArgAddr(3)))

   // The Item object correctly identifies the type before conversion
   wl(uc.ItemOf("Int").@DataType().ToString(cb.ArgPtr(4)))
[/callback]

[callback MyFunction2]
   var uc = cb.@uCalc();
   wl("------ MyFunc2 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_8).ToString(cb.ArgPtr(1)))
[/callback]

[callback MyFunction3]
   var uc = cb.@uCalc();
   wl("------ MyFunc3 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_16).ToString(cb.ArgPtr(1)))
[/callback]
[body]
uc.DefineVariable("x As Int = 123"); // Int32
uc.DefineVariable("xPtr As Int Ptr = AddressOf(x)");
uc.DefineFunction("MyFunc(a As Int32, b As Int64, c As Byte, d As Int Ptr)", MyFunction);
uc.Eval("MyFunc(x*10, 1+1, 255, xPtr)");

uc.DefineVariable("x2 As Int8 = -123");
uc.DefineVariable("xPtr2 As Int8 Ptr = AddressOf(x2)");
uc.DefineFunction("MyFunc2(d As Int8 Ptr)", MyFunction2);
uc.Eval("MyFunc2(xPtr2)");

uc.DefineVariable("x3 As Int16 = 1234");
uc.DefineVariable("xPtr3 As Int16 Ptr = AddressOf(x3)");
uc.DefineFunction("MyFunc3(d As Int16 Ptr)", MyFunction3);
uc.Eval("MyFunc3(xPtr3)");
```

**Output:**
```
------ MyFunc ------
1230
2
-1
123
------ MyFunc2 ------
-123
------ MyFunc3 ------
1234
```

---

---

## ArgBool - ID: 97
/doc/reference/classes/ucalc.callback/argbool/

**Description:** Retrieves a boolean argument passed to a user-defined callback function.

**Syntax:** ArgBool(int)
**Parameters:**
index - int - The 1-based index of the argument to retrieve.
**Return:** bool - The boolean value of the specified argument.
**Remarks:**

The `ArgBool` method retrieves a boolean argument from within a callback function. It is the type-safe counterpart to the generic [Arg](/reference/ucalc/callback/arg) method.

When a function is defined with a parameter explicitly typed as `Bool` (e.g., via [DefineFunction](/reference/ucalc/definefunction)), this method should be used within the callback to retrieve its value.

### Type Safety and Conversion
Using `ArgBool` provides compile-time type safety and improves code clarity. It also leverages uCalc's internal type system, which will automatically attempt to convert compatible numeric types into booleans:

*   A non-zero numeric value is typically converted to `true`.
*   A zero value is converted to `false`.

This behavior makes expressions more flexible, as a user could pass `1` or `0` to a function expecting a boolean value.

### Comparative Analysis

*   **vs. Generic `Arg()`**: The generic [Arg()](/reference/ucalc/callback/arg) (or `ArgDbl()`) method returns a `double`. While a boolean could be retrieved and then cast, `ArgBool()` is more direct, efficient, and less error-prone. It signals clear intent in the code.

*   **vs. Native C#/C++ Arguments**: In a native function, arguments are passed directly on the stack or in registers. uCalc's callback model is different: arguments are stored in an internal structure within the `uCalc.Callback` object. Methods like `ArgBool` are the designated accessors for retrieving this data in a type-safe manner.

**Examples:**

### Example ID: 85

**Description:** Return and other type-specific versions of Return

**Code:**
```pseudocode
[head]
[callback BooleanAnd]
   cb.ReturnBool(cb.ArgBool(1) [C]&&[/C][vb]And[/vb] cb.ArgBool(2));
[/callback]
[callback AddInt16]
   [cs]//C# promots Int16 to int for arithmetic hence (Int16) to convert it back 
cb.ReturnInt16((Int16)(cb.ArgInt16(1) + cb.ArgInt16(2)));[/cs]
   [NotCs]cb.ReturnInt16(cb.ArgInt16(1) + cb.ArgInt16(2));[/NotCs]
[/callback]
[callback AddInt32]
   cb.ReturnInt32(cb.ArgInt32(1) + cb.ArgInt32(2));
[/callback]
[callback AddInt64]
   cb.ReturnInt64(cb.ArgInt64(1) + cb.ArgInt64(2));
[/callback]
[body]

uc.DefineFunction("BooleanAnd(x As Bool, y As Bool) As Bool", BooleanAnd);
uc.DefineFunction("AddInt16(x As Int16, y As Int16) As Int16", AddInt16);
uc.DefineFunction("AddInt32(x As Int32, y As Int32) As Int32", AddInt32);
uc.DefineFunction("AddInt64(x As Int64, y As Int64) As Int64", AddInt64);

wl(uc.EvalStr("BooleanAnd(true, false)"))
wl(uc.EvalStr("AddInt16(5.2, 4.1)"))
wl(uc.EvalStr("AddInt32(2, 3)"))
wl(uc.EvalStr("AddInt64(10, 20)"))
```

**Output:**
```
false
9
5
30
```

---

---

## ArgCount - ID: 98
/doc/reference/classes/ucalc.callback/argcount/

**Description:** Gets the number of arguments passed to the current callback function, essential for creating variadic functions.

**Syntax:** ArgCount()
**Return:** int - The total number of arguments passed to the callback. Returns 0 if the function was called with no arguments.
**Remarks:**

The `ArgCount` method returns the total number of arguments passed to a callback function. It is the primary tool for creating **variadic functions**—functions that can accept a variable number of arguments.

This method can only be called from within a callback context, typically one registered via [DefineFunction](/Reference/uCalcBase/uCalc/DefineFunction) or [DefineOperator](/Reference/uCalcBase/uCalc/DefineOperator). It is commonly used as the upper bound for a loop that iterates through the provided arguments.

```pseudocode
[head]
[callback MySum]
var(double, total) = 0;
// Use ArgCount() to determine how many times to loop.
for(int i = 1 to cb.ArgCount())
   total = total + cb.Arg(i);
end for
cb.Return(total);
[/callback]
[body]
// The '...' syntax marks this as a variadic function.
uc.DefineFunction("Sum(...)", MySum);
wl(uc.Eval("Sum(10, 20, 30)")); // Outputs 60
```

### 💡 Comparative Analysis

Most modern languages have a mechanism for variadic functions, but uCalc's integration with its dynamic expression engine is unique.

*   **vs. C# `params` / C++ `...`**: In compiled languages, variadic functions are a compile-time feature. The function signature is fixed in code.

    ```csharp
    // C# Example
    public double Sum(params double[] numbers) { ... }
    ```

    uCalc's advantage is its **runtime dynamism**. A user can define a variadic function within a string expression that is evaluated at runtime, providing a level of flexibility impossible in pre-compiled code. The `ArgCount` method is the key that unlocks this capability within the callback's logic.

*   **vs. JavaScript `...args`**: While JavaScript's rest parameters (`...args`) are also dynamic, uCalc's `ArgCount` and its companion methods ([Arg](/Reference/uCalcBase/Callback/Arg), [ArgItem](/Reference/uCalcBase/Callback/ArgItem), etc.) provide a more structured and type-aware API for inspecting arguments from within a strongly-typed host environment (like C# or C++), which is a distinct advantage over loosely-typed scripting.

**Examples:**

### Example ID: 12

**Description:** Defining a callback function with a variable number of arguments

**Code:**
```pseudocode
[head]
[callback MyAverage]
var(double, Total) = 0;
for(int x = 1 to cb.ArgCount())
   Total = Total + cb.Arg(x);
end for
cb.Return(Total / cb.ArgCount());
[/callback]
[body]
uc.DefineFunction("Average(x ...)", MyAverage);
wl(uc.Eval("Average(10, 3, 7, 4)"))
```

**Output:**
```
6
```

---

### Example ID: 13

**Description:** Passing arg ByHandle to retrieve meta data such as arg data type; and AnyType

**Code:**
```pseudocode
[head]
[callback DisplayArgs]
for(int x = 1 to cb.ArgCount())
   wl(cb.ArgItem(x).ValueStr() + "  Type: " + cb.ArgItem(x).@DataType().@Name())
end for
[/callback]
[body]
uc.DefineFunction("DisplayArgs(ByHandle Arg As AnyType ...)", DisplayArgs);
uc.Eval("DisplayArgs(5, 3+2*#i, 'Hello', True, False, Int16(5+4.1))");
```

**Output:**
```
5  Type: double
3+2i  Type: complex
Hello  Type: string
true  Type: bool
false  Type: bool
9  Type: int16
```

---

---

## ArgDbl - ID: 99
/doc/reference/classes/ucalc.callback/argdbl/

**Description:** Retrieves a callback argument specifically as a double-precision floating-point number, with automatic type conversion.

**Syntax:** ArgDbl(int)
**Parameters:**
index - int - The 1-based index of the argument. The first argument is at index 1. For better performance with the first two arguments, consider using Arg1() and Arg2().
**Return:** double - The argument's value, converted to a double-precision floating-point number if necessary.
**Remarks:**

The `ArgDbl` method retrieves an argument passed to a callback function, ensuring the value is returned as a `double`. It is a type-specific accessor that improves code clarity by making the expected data type explicit.

### Functional Equivalence with Arg()

This method is functionally identical to its more generic counterpart, [`Arg`](/reference/ucalc/callback/arg/). The `Arg()` method exists primarily for historical reasons, as `double` is the default numeric type in uCalc. Using `ArgDbl` is recommended when you specifically expect a floating-point number, as it makes your code more self-documenting.

### Implicit Type Conversion

A key feature of `ArgDbl` is its ability to perform automatic type conversion. If a function parameter was defined as a different numeric type (e.g., `Int32`, `Boolean`), and the callback retrieves it using `ArgDbl`, uCalc will safely convert the value to a `double` before returning it. This provides flexibility when a function needs to handle various numeric inputs.

### 💡 Comparative Analysis

In many frameworks, callback arguments are passed in a generic collection, like an `object[]` in C# or a `std::vector<std::any>` in C++. Accessing a value requires explicit casting and type checking:

```csharp
// Typical C# approach
double length = (double)args[0]; 
```

This approach is verbose and can lead to runtime `InvalidCastException` errors if the type is not what was expected.

uCalc's type-specific accessors like `ArgDbl`, [`ArgInt32`](/reference/ucalc/callback/argint32/), and [`ArgStr`](/reference/ucalc/callback/argstr/) streamline this process. They handle the type conversion internally and provide a cleaner, more robust interface, reducing boilerplate code and the potential for casting errors.

**Examples:**

### Example ID: 84

**Description:** ArgDbl (same as Arg)

**Code:**
```pseudocode
[head]
[callback MyArea]
var Length = cb.ArgDbl(1); // Same as cb.Arg(1);
var Width = cb.ArgDbl(2); // Same as cb.Arg(2);
cb.Return(Length * Width);
[/callback]
[body]
uc.DefineFunction("Area(x, y)", MyArea);
wl(uc.Eval("Area(3, 4)"))
```

**Output:**
```
12
```

---

---

## ArgExpr - ID: 100
/doc/reference/classes/ucalc.callback/argexpr/

**Description:** Retrieves an argument passed by expression, allowing for lazy evaluation within a callback.

**Syntax:** ArgExpr(int)
**Parameters:**
index - int - The 1-based index of the argument to retrieve.
**Return:** Expression - Returns the unevaluated [Expression](/classes/expression/) object passed as an argument. The callback can then choose to evaluate it, inspect it, or ignore it.
**Remarks:**

## ⚙️ How It Works

The `ArgExpr` method is the key to lazy evaluation in uCalc. It retrieves an argument that was passed not as a final value, but as a raw, unevaluated [Expression](/classes/expression/) object. This is accomplished by marking a parameter with the `ByExpr` modifier in its [DefineFunction](/classes/ucalc/definefunction/) signature.

[pseudocode]`uc.DefineFunction("MyFunc(ByExpr formula)", MyCallback);`

Inside the `MyCallback` function, calling `cb.ArgExpr(1)` retrieves the parsed expression tree for whatever argument was passed to `formula`. The callback then has complete control over when and if that expression is ever evaluated by calling [`.Evaluate()`](/classes/expression/evaluate/) on the returned object.

## 💡 The Power of Lazy Evaluation

Passing expressions instead of values unlocks several advanced capabilities:

*   **Short-Circuiting Logic**: You can create functions that only evaluate the arguments they need. The most common example is a custom `IIf` function, which evaluates either the `then` or the `else` expression, but never both. This prevents side effects and errors (like division by zero) in the unevaluated branch.

*   **Custom Control Structures**: `ByExpr` enables you to build your own looping and aggregation functions. The callback can evaluate the same expression multiple times with different variable values, effectively creating custom `for` loops or `sum` functions directly within the uCalc engine.

*   **Metaprogramming**: Because you receive an `Expression` object, your callback can inspect the argument's raw text via [pseudocode]`myExpr.Str()` before deciding to execute it. This allows for powerful pre-evaluation validation, transformation, or logging.

## 🆚 Comparative Analysis

*   **vs. C# Delegates/Lambdas**: Passing an expression with `ByExpr` is conceptually similar to passing a `Func<T>` delegate in C#. Both techniques pass a piece of code to be executed later. However, uCalc's approach is designed for dynamic, string-based scripting environments where you can't compile a lambda ahead of time. The ability to inspect the expression's text also gives it a metaprogramming advantage over standard delegates.

*   **vs. C++ Function Pointers**: While also a way to pass executable logic, `ByExpr` is a much higher-level and safer construct. The entire lifecycle of the [Expression](/classes/expression/) object is managed by the uCalc engine, avoiding the complexities of manual memory management associated with raw function pointers.

**Examples:**

### Example ID: 14

**Description:** Passing arg ByExpr (delayed lazy eval) and ByHandle

**Code:**
```pseudocode
[head]
[callback MySum]
   var Total = 0.0;
   var Expr = cb.ArgExpr(1);
   var Start = cb.Arg(2);
   var Finish = cb.Arg(3);
   var Variable = cb.ArgItem(4);

   for(double x = Start to Finish)
      Variable.Value(x);
      Total += Expr.Evaluate();
   end for
   cb.Return(Total);
[/callback]
[body]
uc.DefineVariable("x");
uc.DefineFunction("Sum(ByExpr Expr, Start, Finish, ByHandle Var)", MySum);
wl(uc.Eval("Sum(x ^ 2, 1, 10, x)"))

```

**Output:**
```
385
```

---

---

## ArgInt16 - ID: 614
/doc/reference/classes/ucalc.callback/argint16/

**Description:** Retrieves a 16-bit integer argument passed to a user-defined callback function.

**Syntax:** ArgInt16(int)
**Parameters:**
index - int - The 1-based index of the argument to retrieve. The first argument is at index 1.
**Return:** int16 - The value of the specified argument as a 16-bit integer.
**Remarks:**

The [pseudocode]`ArgInt16` method retrieves an argument from within a user-defined callback. This method does not perform any type conversion itself; rather, it provides type-safe access to an argument that the uCalc engine has already processed and stored as a 16-bit integer. This is based on the function signature you provide to [DefineFunction](/reference/ucalcbase/ucalc/definefunction) or [DefineOperator](/reference/ucalcbase/ucalc/defineoperator).

### Argument Indexing
It's crucial to note that the `index` parameter is **1-based**. The first argument passed to your function is retrieved with [pseudocode]`ArgInt16(1)`, the second with [pseudocode]`ArgInt16(2)`, and so on.

### ⚙️ Engine-Level Type Coercion
When you define a function with strongly-typed parameters, such as `MyFunc(x As Int16)`, the uCalc evaluation engine takes responsibility for type coercion. If a user's expression provides a different numeric type, like `MyFunc(123.8)`, the engine will automatically convert `123.8` to the `Int16` value `123` (by truncating the decimal part) *before* your callback function is invoked. The [pseudocode]`ArgInt16(1)` call inside your callback then simply reads this pre-converted 16-bit integer value.

This design ensures that by the time your callback code executes, the arguments are already in the expected format, simplifying your logic and preventing runtime type errors.

### 💡 Comparative Analysis

*   **vs. Native C#/C++**: In native languages, you might handle variant types or `object` parameters, requiring manual type checking and casting inside the function body. uCalc's approach is different: the engine enforces the type contract defined in the function signature *before* execution enters the callback. This moves the responsibility of type safety from the callback implementer to the engine itself, resulting in cleaner, safer code.

*   **vs. Generic `Arg(index)`**: A generic `Arg` method would return a variant type that requires inspection. The type-specific accessors like [pseudocode]`ArgInt16` align with uCalc's philosophy of strong typing at the script level, allowing you to confidently retrieve an argument in the format you declared.

**Examples:**

### Example ID: 85

**Description:** Return and other type-specific versions of Return

**Code:**
```pseudocode
[head]
[callback BooleanAnd]
   cb.ReturnBool(cb.ArgBool(1) [C]&&[/C][vb]And[/vb] cb.ArgBool(2));
[/callback]
[callback AddInt16]
   [cs]//C# promots Int16 to int for arithmetic hence (Int16) to convert it back 
cb.ReturnInt16((Int16)(cb.ArgInt16(1) + cb.ArgInt16(2)));[/cs]
   [NotCs]cb.ReturnInt16(cb.ArgInt16(1) + cb.ArgInt16(2));[/NotCs]
[/callback]
[callback AddInt32]
   cb.ReturnInt32(cb.ArgInt32(1) + cb.ArgInt32(2));
[/callback]
[callback AddInt64]
   cb.ReturnInt64(cb.ArgInt64(1) + cb.ArgInt64(2));
[/callback]
[body]

uc.DefineFunction("BooleanAnd(x As Bool, y As Bool) As Bool", BooleanAnd);
uc.DefineFunction("AddInt16(x As Int16, y As Int16) As Int16", AddInt16);
uc.DefineFunction("AddInt32(x As Int32, y As Int32) As Int32", AddInt32);
uc.DefineFunction("AddInt64(x As Int64, y As Int64) As Int64", AddInt64);

wl(uc.EvalStr("BooleanAnd(true, false)"))
wl(uc.EvalStr("AddInt16(5.2, 4.1)"))
wl(uc.EvalStr("AddInt32(2, 3)"))
wl(uc.EvalStr("AddInt64(10, 20)"))
```

**Output:**
```
false
9
5
30
```

---

---

## ArgInt32 - ID: 101
/doc/reference/classes/ucalc.callback/argint32/

**Description:** Retrieves a 32-bit integer argument passed to a user-defined callback function.

**Syntax:** ArgInt32(int)
**Parameters:**
index - int - The 1-based index of the argument to retrieve. The first argument is at index 1.
**Return:** int32 - The value of the specified argument as a 32-bit integer.
**Remarks:**

The [pseudocode]`ArgInt32` method retrieves an argument from within a user-defined callback. This method does not perform any type conversion itself; rather, it provides type-safe access to an argument that the uCalc engine has already processed and stored as a 32-bit integer. This is based on the function signature you provide to [DefineFunction](/reference/ucalcbase/ucalc/definefunction) or [DefineOperator](/reference/ucalcbase/ucalc/defineoperator).

### Argument Indexing
It's crucial to note that the `index` parameter is **1-based**. The first argument passed to your function is retrieved with [pseudocode]`ArgInt32(1)`, the second with [pseudocode]`ArgInt32(2)`, and so on.

### ⚙️ Engine-Level Type Coercion
When you define a function with strongly-typed parameters, such as `MyFunc(x As Int32)`, the uCalc evaluation engine takes responsibility for type coercion. If a user's expression provides a different numeric type, like `MyFunc(123.8)`, the engine will automatically convert `123.8` to the `Int32` value `123` (by truncating the decimal part) *before* your callback function is invoked. The [pseudocode]`ArgInt32(1)` call inside your callback then simply reads this pre-converted 32-bit integer value.

This design ensures that by the time your callback code executes, the arguments are already in the expected format, simplifying your logic and preventing runtime type errors.

### 💡 Comparative Analysis
*   **vs. Native C#/C++**: In native languages, you might handle variant types or `object` parameters, requiring manual type checking and casting inside the function body. uCalc's approach is different: the engine enforces the type contract defined in the function signature *before* execution enters the callback. This moves the responsibility of type safety from the callback implementer to the engine itself, resulting in cleaner, safer code.

*   **vs. Generic `Arg(index)`**: A generic `Arg` method would return a variant type that requires inspection. The type-specific accessors like [pseudocode]`ArgInt32` align with uCalc's philosophy of strong typing at the script level, allowing you to confidently retrieve an argument in the format you declared.

**Examples:**

### Example ID: 16

**Description:** How to handle and retrieve various data types (including pointers) within a callback.

**Code:**
```pseudocode
[head]
[callback MyFunction]
   var uc = cb.@uCalc();
   wl("------ MyFunc ------")

   // Retrieve standard 32-bit and 64-bit integer arguments directly
   wl(cb.ArgInt32(1))
   wl(cb.ArgInt64(2))

   // Retrieve the value of a pointer argument by referencing its exact data type.
   wl(uc.ItemOf("Int8").@DataType().ToString(cb.ArgAddr(3)))

   // The Item object correctly identifies the type before conversion
   wl(uc.ItemOf("Int").@DataType().ToString(cb.ArgPtr(4)))
[/callback]

[callback MyFunction2]
   var uc = cb.@uCalc();
   wl("------ MyFunc2 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_8).ToString(cb.ArgPtr(1)))
[/callback]

[callback MyFunction3]
   var uc = cb.@uCalc();
   wl("------ MyFunc3 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_16).ToString(cb.ArgPtr(1)))
[/callback]
[body]
uc.DefineVariable("x As Int = 123"); // Int32
uc.DefineVariable("xPtr As Int Ptr = AddressOf(x)");
uc.DefineFunction("MyFunc(a As Int32, b As Int64, c As Byte, d As Int Ptr)", MyFunction);
uc.Eval("MyFunc(x*10, 1+1, 255, xPtr)");

uc.DefineVariable("x2 As Int8 = -123");
uc.DefineVariable("xPtr2 As Int8 Ptr = AddressOf(x2)");
uc.DefineFunction("MyFunc2(d As Int8 Ptr)", MyFunction2);
uc.Eval("MyFunc2(xPtr2)");

uc.DefineVariable("x3 As Int16 = 1234");
uc.DefineVariable("xPtr3 As Int16 Ptr = AddressOf(x3)");
uc.DefineFunction("MyFunc3(d As Int16 Ptr)", MyFunction3);
uc.Eval("MyFunc3(xPtr3)");
```

**Output:**
```
------ MyFunc ------
1230
2
-1
123
------ MyFunc2 ------
-123
------ MyFunc3 ------
1234
```

---

### Example ID: 85

**Description:** Return and other type-specific versions of Return

**Code:**
```pseudocode
[head]
[callback BooleanAnd]
   cb.ReturnBool(cb.ArgBool(1) [C]&&[/C][vb]And[/vb] cb.ArgBool(2));
[/callback]
[callback AddInt16]
   [cs]//C# promots Int16 to int for arithmetic hence (Int16) to convert it back 
cb.ReturnInt16((Int16)(cb.ArgInt16(1) + cb.ArgInt16(2)));[/cs]
   [NotCs]cb.ReturnInt16(cb.ArgInt16(1) + cb.ArgInt16(2));[/NotCs]
[/callback]
[callback AddInt32]
   cb.ReturnInt32(cb.ArgInt32(1) + cb.ArgInt32(2));
[/callback]
[callback AddInt64]
   cb.ReturnInt64(cb.ArgInt64(1) + cb.ArgInt64(2));
[/callback]
[body]

uc.DefineFunction("BooleanAnd(x As Bool, y As Bool) As Bool", BooleanAnd);
uc.DefineFunction("AddInt16(x As Int16, y As Int16) As Int16", AddInt16);
uc.DefineFunction("AddInt32(x As Int32, y As Int32) As Int32", AddInt32);
uc.DefineFunction("AddInt64(x As Int64, y As Int64) As Int64", AddInt64);

wl(uc.EvalStr("BooleanAnd(true, false)"))
wl(uc.EvalStr("AddInt16(5.2, 4.1)"))
wl(uc.EvalStr("AddInt32(2, 3)"))
wl(uc.EvalStr("AddInt64(10, 20)"))
```

**Output:**
```
false
9
5
30
```

---

---

## ArgInt64 - ID: 102
/doc/reference/classes/ucalc.callback/argint64/

**Description:** Retrieves a 64-bit integer argument from within a user-defined callback function.

**Syntax:** ArgInt64(int)
**Parameters:**
index - int - The 1-based index of the argument to retrieve. For example, the first argument has an index of 1.
**Return:** int64 - The 64-bit integer value of the specified argument.
**Remarks:**

The `ArgInt64` method retrieves an argument from within a user-defined callback. This method does not perform any type conversion itself; rather, it provides type-safe access to an argument that the uCalc engine has already processed and stored as a 64-bit integer. This behavior is based on the function signature you provide to [pseudocode]`DefineFunction` or [pseudocode]`DefineOperator`.

### 🔢 Argument Indexing
It's crucial to note that the `index` parameter is 1-based. The first argument passed to your function is retrieved with [pseudocode]`ArgInt64(1)`, the second with [pseudocode]`ArgInt64(2)`, and so on.

### ⚙️ Engine-Level Type Coercion
When you define a function with strongly-typed parameters, such as [pseudocode]`MyFunc(x As Int64)`, the uCalc evaluation engine takes responsibility for type coercion. If a user's expression provides a different but compatible numeric type, like [pseudocode]`MyFunc(123.8)`, the engine will automatically convert `123.8` to the `Int64` value `123` (by truncating the decimal part) before your callback function is invoked. The [pseudocode]`ArgInt64(1)` call inside your callback then simply reads this pre-converted 64-bit integer value.

This design ensures that by the time your callback code executes, the arguments are already in the expected format, simplifying your logic and preventing runtime type errors.

### 💡 Comparative Analysis
*   **vs. Native C#/C++:** In native languages, you might handle variant types or `object` parameters, requiring manual type checking and casting inside the function body. uCalc's approach is different: the engine enforces the type contract defined in the function signature *before* execution enters the callback. This moves the responsibility of type safety from the callback implementer to the engine itself, resulting in cleaner, safer code.
*   **vs. Generic `Arg(index)`:** A generic `Arg` method would return a variant type that requires runtime inspection. The type-specific accessors like `ArgInt64` align with uCalc's philosophy of strong typing at the script level, allowing you to confidently retrieve an argument in the format you declared.

**Examples:**

### Example ID: 16

**Description:** How to handle and retrieve various data types (including pointers) within a callback.

**Code:**
```pseudocode
[head]
[callback MyFunction]
   var uc = cb.@uCalc();
   wl("------ MyFunc ------")

   // Retrieve standard 32-bit and 64-bit integer arguments directly
   wl(cb.ArgInt32(1))
   wl(cb.ArgInt64(2))

   // Retrieve the value of a pointer argument by referencing its exact data type.
   wl(uc.ItemOf("Int8").@DataType().ToString(cb.ArgAddr(3)))

   // The Item object correctly identifies the type before conversion
   wl(uc.ItemOf("Int").@DataType().ToString(cb.ArgPtr(4)))
[/callback]

[callback MyFunction2]
   var uc = cb.@uCalc();
   wl("------ MyFunc2 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_8).ToString(cb.ArgPtr(1)))
[/callback]

[callback MyFunction3]
   var uc = cb.@uCalc();
   wl("------ MyFunc3 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_16).ToString(cb.ArgPtr(1)))
[/callback]
[body]
uc.DefineVariable("x As Int = 123"); // Int32
uc.DefineVariable("xPtr As Int Ptr = AddressOf(x)");
uc.DefineFunction("MyFunc(a As Int32, b As Int64, c As Byte, d As Int Ptr)", MyFunction);
uc.Eval("MyFunc(x*10, 1+1, 255, xPtr)");

uc.DefineVariable("x2 As Int8 = -123");
uc.DefineVariable("xPtr2 As Int8 Ptr = AddressOf(x2)");
uc.DefineFunction("MyFunc2(d As Int8 Ptr)", MyFunction2);
uc.Eval("MyFunc2(xPtr2)");

uc.DefineVariable("x3 As Int16 = 1234");
uc.DefineVariable("xPtr3 As Int16 Ptr = AddressOf(x3)");
uc.DefineFunction("MyFunc3(d As Int16 Ptr)", MyFunction3);
uc.Eval("MyFunc3(xPtr3)");
```

**Output:**
```
------ MyFunc ------
1230
2
-1
123
------ MyFunc2 ------
-123
------ MyFunc3 ------
1234
```

---

### Example ID: 85

**Description:** Return and other type-specific versions of Return

**Code:**
```pseudocode
[head]
[callback BooleanAnd]
   cb.ReturnBool(cb.ArgBool(1) [C]&&[/C][vb]And[/vb] cb.ArgBool(2));
[/callback]
[callback AddInt16]
   [cs]//C# promots Int16 to int for arithmetic hence (Int16) to convert it back 
cb.ReturnInt16((Int16)(cb.ArgInt16(1) + cb.ArgInt16(2)));[/cs]
   [NotCs]cb.ReturnInt16(cb.ArgInt16(1) + cb.ArgInt16(2));[/NotCs]
[/callback]
[callback AddInt32]
   cb.ReturnInt32(cb.ArgInt32(1) + cb.ArgInt32(2));
[/callback]
[callback AddInt64]
   cb.ReturnInt64(cb.ArgInt64(1) + cb.ArgInt64(2));
[/callback]
[body]

uc.DefineFunction("BooleanAnd(x As Bool, y As Bool) As Bool", BooleanAnd);
uc.DefineFunction("AddInt16(x As Int16, y As Int16) As Int16", AddInt16);
uc.DefineFunction("AddInt32(x As Int32, y As Int32) As Int32", AddInt32);
uc.DefineFunction("AddInt64(x As Int64, y As Int64) As Int64", AddInt64);

wl(uc.EvalStr("BooleanAnd(true, false)"))
wl(uc.EvalStr("AddInt16(5.2, 4.1)"))
wl(uc.EvalStr("AddInt32(2, 3)"))
wl(uc.EvalStr("AddInt64(10, 20)"))
```

**Output:**
```
false
9
5
30
```

---

---

## ArgItem - ID: 103
/doc/reference/classes/ucalc.callback/argitem/

**Description:** Retrieves the full metadata object for a specific argument passed to a callback function.

**Syntax:** ArgItem(int)
**Parameters:**
index - int - The 1-based index of the argument to retrieve (the first argument is at index 1).
**Return:** Item - Returns the `Item` object for the specified argument, providing access to its metadata such as name, data type, and underlying value pointer. Returns an empty item if the index is out of bounds.
**Remarks:**

### 🔎 Introspection Power: Value vs. Metadata

The `ArgItem` method is the primary tool for introspection within a callback. While other `Arg*` functions (`Arg()`, `ArgStr()`, etc.) return the *value* of an argument, `ArgItem` returns the argument's underlying [Item](/reference/ucalcbase/item/) object. This gives you access to a wealth of metadata, allowing you to build highly dynamic and context-aware functions.

### `Arg()` vs. `ArgItem()`

| Method | Returns | Use Case |
| :--- | :--- | :--- |
| [pseudocode]`cb.Arg(1)` | `double` (the value) | Simple numeric calculations. |
| [pseudocode]`cb.ArgStr(1)` | `string` (the value) | Simple string manipulation. |
| [pseudocode]`cb.ArgItem(1)` | `Item` (the object) | Accessing metadata: name, data type, original expression, value pointer. |

---

# 🎯 Primary Use Cases

### 1. Handling `ByHandle` and `ByRef` Arguments
This is the most common use case. When a parameter is defined with `ByHandle`, its `Item` object is passed instead of its value. `ArgItem` is the only way to retrieve this object.

### 2. Variadic Functions (`...`)
For functions that accept a variable number of arguments, `ArgItem` allows you to loop through each argument and inspect its type and value, enabling you to create flexible functions like `Sum()` or `Print()`.

### 3. Metaprogramming
By accessing an argument's metadata, you can change your function's behavior based on the caller's context. For example, you can check if an argument was a literal constant or a variable and process it differently.

---

# ⚖️ Comparative Analysis

*   **vs. Reflection (C# `ParameterInfo`, Java `Parameter`)**:
    `ArgItem` provides functionality similar to reflection APIs in other languages but is more lightweight and integrated directly into the evaluation flow. Retrieving metadata is a simple method call, avoiding the complexity of navigating `MethodInfo` or `Assembly` objects.

*   **vs. Dynamic Languages (Python `*args`, `**kwargs`)**:
    `ArgItem` brings the introspective power of dynamic languages into uCalc's strongly-typed (but flexible) environment. It provides a structured way to inspect arguments that is safer than simple type-checking in a fully dynamic context.

**Examples:**

### Example ID: 13

**Description:** Passing arg ByHandle to retrieve meta data such as arg data type; and AnyType

**Code:**
```pseudocode
[head]
[callback DisplayArgs]
for(int x = 1 to cb.ArgCount())
   wl(cb.ArgItem(x).ValueStr() + "  Type: " + cb.ArgItem(x).@DataType().@Name())
end for
[/callback]
[body]
uc.DefineFunction("DisplayArgs(ByHandle Arg As AnyType ...)", DisplayArgs);
uc.Eval("DisplayArgs(5, 3+2*#i, 'Hello', True, False, Int16(5+4.1))");
```

**Output:**
```
5  Type: double
3+2i  Type: complex
Hello  Type: string
true  Type: bool
false  Type: bool
9  Type: int16
```

---

### Example ID: 14

**Description:** Passing arg ByExpr (delayed lazy eval) and ByHandle

**Code:**
```pseudocode
[head]
[callback MySum]
   var Total = 0.0;
   var Expr = cb.ArgExpr(1);
   var Start = cb.Arg(2);
   var Finish = cb.Arg(3);
   var Variable = cb.ArgItem(4);

   for(double x = Start to Finish)
      Variable.Value(x);
      Total += Expr.Evaluate();
   end for
   cb.Return(Total);
[/callback]
[body]
uc.DefineVariable("x");
uc.DefineFunction("Sum(ByExpr Expr, Start, Finish, ByHandle Var)", MySum);
wl(uc.Eval("Sum(x ^ 2, 1, 10, x)"))

```

**Output:**
```
385
```

---

### Example ID: 86

**Description:** Returning a pointer with ReturnPtr

**Code:**
```pseudocode
[head]
[callback GetAddressOf]
   cb.ReturnPtr(cb.ArgItem(1).ValueAddr());
[/callback]
[body]

// This example is for sake of illustration
// There is already a built-in AddressOf() function

uc.DefineFunction("GetAddressOf(ByHandle Variable As AnyType) As SameTypeAs:0 Ptr", GetAddressOf);

uc.DefineVariable("MyVariable = 123.456");
uc.DefineVariable("MyStr = 'Hello world!'");

wl(uc.EvalStr("ValueAt(GetAddressOf(MyVariable))"))
wl(uc.EvalStr("ValueAt(GetAddressOf(MyStr))"))
```

**Output:**
```
123.456
Hello world!
```

---

---

## ArgPtr - ID: 104
/doc/reference/classes/ucalc.callback/argptr/

**Description:** Retrieves the value of an argument that was passed as a pointer.

**Syntax:** ArgPtr(int)
**Parameters:**
index - int - The 1-based index of the argument to retrieve.
**Return:** IntPtr - The memory address that was passed as the argument's value. Returns 0 if the argument is not a pointer type.
**Remarks:**

The `ArgPtr` method is used within a callback to retrieve the value of an argument that was defined as a pointer type in a [DefineFunction](/reference/ucalc/definefunction) or [DefineOperator](/reference/ucalc/defineoperator) signature.

### The Core Distinction: `ArgPtr` vs. `ArgAddr`

It is crucial to understand the difference between retrieving a pointer *value* and retrieving the memory address *of* an argument. `ArgPtr` is for the former, while [ArgAddr](/reference/ucalc/callback/argaddr) is for the latter.

| Method | Purpose | Returns | Example `DefineFunction` Parameter |
| :--- | :--- | :--- | :--- |
| `cb.ArgPtr(n)` | Gets the **value of** the nth argument, which must be a pointer type. | An address (as an `IntPtr`). | `MyFunc(p As Int Ptr)` |
| `cb.ArgAddr(n)` | Gets the memory **address of** the nth argument's storage location. | The address where the argument's value is stored. | `MyFunc(x As Int)` |

In short, use `ArgPtr` when the argument *is* a pointer. Use `ArgAddr` to find out *where* any argument is stored in memory.

### ⚙️ Dereferencing the Pointer

The address returned by `ArgPtr` is most often used with [uCalc.ValueAt](/reference/ucalc/valueat) to dereference the pointer and retrieve the data it points to. This allows a callback to read from or write to memory locations in the host application.

### ⚖️ Comparative Analysis

In native C++ or C# `unsafe` contexts, a callback might receive a raw pointer (`int*`) which can be dereferenced directly (`*my_ptr`). uCalc provides a safer, more abstract model. `ArgPtr` retrieves the pointer value as a managed handle/integer, which is then safely dereferenced using engine functions like `ValueAt`. This insulates the user from raw memory manipulation while still providing the power of pointer-based data access.

**Examples:**

### Example ID: 16

**Description:** How to handle and retrieve various data types (including pointers) within a callback.

**Code:**
```pseudocode
[head]
[callback MyFunction]
   var uc = cb.@uCalc();
   wl("------ MyFunc ------")

   // Retrieve standard 32-bit and 64-bit integer arguments directly
   wl(cb.ArgInt32(1))
   wl(cb.ArgInt64(2))

   // Retrieve the value of a pointer argument by referencing its exact data type.
   wl(uc.ItemOf("Int8").@DataType().ToString(cb.ArgAddr(3)))

   // The Item object correctly identifies the type before conversion
   wl(uc.ItemOf("Int").@DataType().ToString(cb.ArgPtr(4)))
[/callback]

[callback MyFunction2]
   var uc = cb.@uCalc();
   wl("------ MyFunc2 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_8).ToString(cb.ArgPtr(1)))
[/callback]

[callback MyFunction3]
   var uc = cb.@uCalc();
   wl("------ MyFunc3 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_16).ToString(cb.ArgPtr(1)))
[/callback]
[body]
uc.DefineVariable("x As Int = 123"); // Int32
uc.DefineVariable("xPtr As Int Ptr = AddressOf(x)");
uc.DefineFunction("MyFunc(a As Int32, b As Int64, c As Byte, d As Int Ptr)", MyFunction);
uc.Eval("MyFunc(x*10, 1+1, 255, xPtr)");

uc.DefineVariable("x2 As Int8 = -123");
uc.DefineVariable("xPtr2 As Int8 Ptr = AddressOf(x2)");
uc.DefineFunction("MyFunc2(d As Int8 Ptr)", MyFunction2);
uc.Eval("MyFunc2(xPtr2)");

uc.DefineVariable("x3 As Int16 = 1234");
uc.DefineVariable("xPtr3 As Int16 Ptr = AddressOf(x3)");
uc.DefineFunction("MyFunc3(d As Int16 Ptr)", MyFunction3);
uc.Eval("MyFunc3(xPtr3)");
```

**Output:**
```
------ MyFunc ------
1230
2
-1
123
------ MyFunc2 ------
-123
------ MyFunc3 ------
1234
```

---

---

## ArgStr - ID: 105
/doc/reference/classes/ucalc.callback/argstr/

**Description:** Retrieves an argument passed to a callback function, automatically converting its value to a string.

**Syntax:** ArgStr(int)
**Parameters:**
index - int - The 1-based index of the argument to retrieve. For example, the first argument is at index 1.
**Return:** string - The string representation of the requested argument's value.
**Remarks:**

The `ArgStr` method retrieves an argument passed to a callback function as a string. Its key feature is **automatic type conversion**: if the original argument is a number, boolean, or another type, `ArgStr` will automatically convert its value to a string representation before returning it.

This simplifies callback logic significantly, as you do not need to check the argument's type and perform manual conversions. It is the most versatile of the `Arg` functions for retrieving display-ready values.

`ArgStr` is typically used within a callback that is registered with [DefineFunction](/Reference/uCalcBase/uCalc/DefineFunction) or [DefineOperator](/Reference/uCalcBase/uCalc/DefineOperator).

### ⚖️ Comparative Analysis

*   **vs. Native Delegates (C#) / Function Pointers (C++)**: In native code, callback arguments have fixed types. To get a string from an integer, you must manually call a conversion function (e.g., `ToString()`, `std::to_string`). uCalc's `ArgStr` handles this conversion implicitly, making the callback code cleaner and more focused on logic rather than type marshalling.

*   **vs. Other `Arg` Methods**: While methods like [ArgDbl](/Reference/uCalcBase/Callback/ArgDbl) or [ArgInt32](/Reference/uCalcBase/Callback/ArgInt32) are more efficient for direct numeric calculations, `ArgStr` is the ideal choice when the ultimate goal is to build, format, or display a string.

**Examples:**

### Example ID: 15

**Description:** Returning a string (from a callback)

**Code:**
```pseudocode
[head]
[callback TwiceStr]
   cb.ReturnStr(cb.ArgStr(1) + cb.ArgStr(1));
[/callback]
[body]
uc.DefineFunction("Twice(Txt As String) As String", TwiceStr);
wl(uc.EvalStr("Twice('Bye')"))
```

**Output:**
```
ByeBye
```

---

---

## Error = [ErrorInfo] - ID: 873
/doc/reference/classes/ucalc.callback/error-=-[errorinfo]/

**Examples:**

### Example ID: 39

**Description:** Raises an error in a callback using a customized message with ErrorRaiseMessage

**Code:**
```pseudocode
[head]
[callback RaiseErrorMessageCallback]
if (cb.Arg(1) == 123)
   cb.@Error().Raise("I do not like this value!");
   cb.Return(cb.Arg(1));
end if
[/callback]
[body]

uc.DefineFunction("ErrRaiseMsgTest(Value)", RaiseErrorMessageCallback);
wl(uc.EvalStr("ErrRaiseMsgTest(111)"))
wl(uc.EvalStr("ErrRaiseMsgTest(123)"))
```

**Output:**
```
111
I do not like this value!
```

---

### Example ID: 482

**Description:** A function that unconditionally raises a custom error.

**Code:**
```pseudocode
[head]
[callback:u MyHandler]
    // This handler just logs the error and aborts
    wl("Error Handler Caught: ", uc.@Error().@Message())
[/callback]
[callback MyFunc]
    // This function always fails with a custom message
    cb.@Error().Raise("Validation failed for input.");
[/callback]
[body]
uc.@Error().AddHandler(MyHandler);
uc.DefineFunction("Validate()", MyFunc);
uc.EvalStr("Validate()"); // This call will trigger the error
```

**Output:**
```
Error Handler Caught: Validation failed for input.
```

---

### Example ID: 483

**Description:** Raises an error with a dynamic message if a validation check fails within a callback.

**Code:**
```pseudocode
[head]
[callback ValidateValue]
    var val = cb.Arg(1);
    if (val > 100)
        // The error message includes the problematic value, making it dynamic.
        cb.@Error().Raise("Value exceeds maximum of 100. Got: " + [cpp]to_string((int)val)[/cpp][NotCpp]val.ToString()[/NotCpp]);
    else
        cb.Return(val);
    end if
[/callback]
[body]
uc.DefineFunction("CheckValue(val)", ValidateValue);
wl(uc.EvalStr("CheckValue(50)"))
wl(uc.EvalStr("CheckValue(123)"))
```

**Output:**
```
50
Value exceeds maximum of 100. Got: 123
```

---

### Example ID: 484

**Description:** Internal Test: Demonstrates error recovery by having an error handler resume execution after a custom error is raised.

**Code:**
```pseudocode
[head]
[callback:u RecoveryHandler]
    wl("Handler: Caught '", uc.@Error().@Message(), "'")
    // Attempt to recover by resuming execution.
    uc.@Error().@Response(ErrorHandlerResponse::Resume);
    wl("Handler: Resuming execution...")
[/callback]
[callback RiskyOperation]
    var input = cb.ArgStr(1);
    if (input == "bad")
        cb.@Error().Raise("A recoverable error occurred.");
        // After the error handler resumes, this return value will be used.
 
    else
        cb.ReturnStr("Normal_OK");
    end if
[/callback]
[body]
uc.@Error().AddHandler(RecoveryHandler);
uc.DefineFunction("DoWork(s As String) As String", RiskyOperation);

wl("Result: " + uc.EvalStr("DoWork('good')"))
wl("---")
wl("Result: " + uc.EvalStr("DoWork('bad')"))
```

**Output:**
```
Result: Normal_OK
---
Handler: Caught 'A recoverable error occurred.'
Handler: Resuming execution...
Result: A recoverable error occurred.
```

---

### Example ID: 479

**Description:** Triggering a standard syntax error if the input value is negative.

**Code:**
```pseudocode
[head]
[callback DoublePositive]
  // If input is negative, raise a syntax error.
  if (cb.Arg(1) < 0)
    cb.@Error().Raise(ErrorCode::Syntax_Error);
  end if
  cb.Return(cb.Arg(1) * 2);
[/callback]
[body]
uc.DefineFunction("DoublePositive(x)", DoublePositive);
wl(uc.EvalStr("DoublePositive(10)"))
wl(uc.EvalStr("DoublePositive(-5)"))
```

**Output:**
```
20
Syntax error
```

---

### Example ID: 37

**Description:** Raising an error in a callback with ErrorRaise

**Code:**
```pseudocode
[head]
[callback RaiseErrorCallback]
if (cb.Arg(1) == 123)
  cb.@Error().Raise(ErrorCode::Unrecognized_Command);
end if
cb.Return(cb.Arg(1));
[/callback]
[body]

uc.DefineFunction("ErrRaiseTest(Value)", RaiseErrorCallback);
wl(uc.EvalStr("ErrRaiseTest(111)"))
wl(uc.EvalStr("ErrRaiseTest(123)")) // The callback arbitrarily raises an error for 123
```

**Output:**
```
111
Unrecognized command
```

---

---

## Handle - ID: 109
/doc/reference/classes/ucalc.callback/handle/

**Description:** Retrieves the internal, low-level identifier for the callback context object.

**Syntax:** Handle()
**Return:** ADDR - Returns the current `Callback` object, which can be implicitly converted to its handle. The handle is an opaque, internal identifier whose numeric value is not guaranteed to be consistent across application runs.
**Remarks:**

This method retrieves the internal handle of the `Callback` object, which is an opaque, pointer-like identifier used by the uCalc library to manage object instances at a low level. It is primarily intended for advanced debugging and internal diagnostics.

### What is a Handle?
A handle is a unique, low-level identifier for a specific `uCalc` instance in memory. Its actual numeric value is unpredictable and can change every time the application runs. It should not be stored or used for serialization. For a stable and predictable identifier, use the `MemoryIndex` property of the associated object.

### ⚖️ `Handle` vs. `MemoryIndex`

While both are identifiers, they serve different purposes. Understanding the distinction is key to using the diagnostic API correctly.

| Feature | Handle | MemoryIndex |
| :--- | :--- | :--- |
| **Stability** | **Volatile**. The value changes between application runs. | **Stable**. Predictable and sequential. |
| **Uniqueness** | Guaranteed unique for the object's lifetime. | Can be **recycled** after an object is released. |
| **Purpose** | Low-level object identification for the C++ core. | High-level diagnostics and tracking object lifetime. |
| **Use Case** | Advanced debugging. | Identifying specific instances for logging or in diagnostic tools. |

### Comparative Analysis

In C# or C++, you can think of a handle as being similar to an `IntPtr` or a raw pointer (`void*`). It refers to a specific memory location managed by the uCalc engine. However, unlike raw pointers, the uCalc handle is managed within the uCalc ecosystem. The key takeaway for developers is to use `MemoryIndex` for any form of stable identification and to treat the `Handle` as a transient, internal-only value.

**Examples:**

---

## Item = [Item] - ID: 110
/doc/reference/classes/ucalc.callback/item-=-[item]/

**Description:** Retrieves the Item object for the function or operator that triggered the callback.

**Remarks:**

### 🕵️‍♀️ Introspecting the Caller

The `Item()` method, available on the `cb` (callback) object, provides a powerful introspection capability. It returns the complete [Item](/Reference/uCalcBase/Item) object that represents the function or operator whose execution triggered the current callback. This allows your native code to access the full definition and metadata of the symbol that is currently being evaluated.

### 🎯 Primary Use Case: Shared Callbacks

Its most critical use case is for disambiguation when multiple functions or operators are mapped to a single, generic callback function. Inside the callback, `cb.Item()` is the primary mechanism to determine which specific symbol was invoked, enabling you to implement different logic based on the caller.

By inspecting the returned `Item` object, you can query its properties:
*   **Name**: [Item.Name()](/Reference/uCalcBase/Item/Name)
*   **Data Type**: [Item.DataType()](/Reference/uCalcBase/Item/DataType)
*   **Parameter Count**: [Item.Count()](/Reference/uCalcBase/Item/Count)
*   **Symbol Type**: [Item.IsProperty(ItemIs::Function)](/Reference/uCalcBase/Item/IsProperty)
*   **Original Definition**: [Item.Text()](/Reference/uCalcBase/Item/Text)
*   **User-Supplied Description**: [Item.Description()](/Reference/uCalcBase/Item/Description)

### 💡 Comparative Analysis

*   **vs. Reflection (C# `MethodBase.GetCurrentMethod()` / C++ `__func__`)**: Standard language features for introspection typically return only the name of the current function as a string. uCalc's `cb.Item()` is significantly more powerful. It returns a rich, structured object that provides deep access to the symbol's properties as defined within the uCalc engine. This allows for more intelligent, context-aware logic inside your callbacks than is possible with simple name-based reflection.

**Examples:**

### Example ID: 486

**Description:** Disambiguates which function or operator triggered a shared callback.

**Code:**
```pseudocode
[head]
[callback SharedCallback]
   wl("Callback triggered by: ", cb.@Item().@Name())
[/callback]
[body]
// Define two different symbols that use the same callback
uc.DefineFunction("FuncA(x, y)", SharedCallback);
uc.DefineOperator("{x} OpB {y}", 100, Associativity::LeftToRight, SharedCallback);

// Call both symbols
uc.EvalStr("FuncA(1, 2)");
uc.EvalStr("1 OpB 2");

```

**Output:**
```
Callback triggered by: funca
Callback triggered by: opb
```

---

### Example ID: 40

**Description:** Determining properties of an expression part

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   wl("Name: ", cb.@Item().@Name())
   wl("Data type: ", cb.@Item().@DataType().@Name())
   wl("Param count: ", cb.@Item().@Count())
   w("Procedure type: ")
   if (cb.@Item().IsProperty(ItemIs::Operator))
      wl("Operator")
   else if (cb.@Item().IsProperty(ItemIs::Function))
      wl("Function")
   end if
   wl(cb.@Item().@Text())
   wl(cb.@Item().@Description())
   wl("---")
[/callback]
[body]

uc.DefineFunction("AAA() As Double", ItemCallback).@Description("Does this and that");
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).@Description("Does something else");
uc.DefineOperator("{x} CCC {y} As Int32", 0, Associativity::LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");

```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Function: AAA() As Double
Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Function: BBB(x, y, z) As String
Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Operator: {x} CCC {y} As Int32

---
```

---

---

## Return - ID: 112
/doc/reference/classes/ucalc.callback/return/

**Description:** Sets the double-precision floating-point return value for a custom function or operator implemented via callback.

**Syntax:** Return(double)
**Parameters:**
value - double - The double-precision value to be returned from the callback to the uCalc engine.
**Return:** void - This method does not return a value.
**Remarks:**

The `Return` method (or synonymous `ReturnDbl`) is the primary mechanism for sending a `double` result from a native callback function back to the uCalc evaluation engine. When a custom function or operator is called within an expression, this method must be used to provide its output.

### Type-Specific Returns

This method is specifically for returning `double` values. uCalc provides a family of type-safe return methods for other data types. Using the correct method ensures data integrity and avoids unnecessary type conversions.

*   **`Return` / `ReturnDbl`**: For `double` values (this method).
*   **[`ReturnStr`](/Reference/uCalcBase/Callback/ReturnStr)**: For string values.
*   **[`ReturnBool`](/Reference/uCalcBase/Callback/ReturnBool)**: For boolean values.
*   **[`ReturnInt32`](/Reference/uCalcBase/Callback/ReturnInt32)**: For 32-bit integers.
*   **[`ReturnInt64`](/Reference/uCalcBase/Callback/ReturnInt64)**: For 64-bit integers.

### Comparative Analysis

Unlike a native `return` statement in C# or C++, which is a language-level control flow keyword, `cb.Return()` is a method call that interacts with the uCalc engine's internal state. It effectively places the provided value onto the evaluation stack, allowing the engine to continue processing the expression. This distinction is crucial: the callback function itself is typically `void` in the host language, and `cb.Return()` is the designated channel for communicating results back to the parser.

**Examples:**

### Example ID: 11

**Description:** How to define a custom function using a native callback.

**Code:**
```pseudocode
[head]
[callback MyArea]
// Retrieve the 1st and 2nd arguments passed to the function
var Length = cb.Arg(1); 
var Width = cb.Arg(2);

// Calculate the area and return the result to the uCalc engine.
// This logic pattern translates seamlessly across languages.
cb.Return(Length * Width); // Same as cb.ReturnDbl
[/callback]
[body]
uc.DefineFunction("Area(x, y)", MyArea);
wl(uc.Eval("Area(3, 4)"))
```

**Output:**
```
12
```

---

### Example ID: 12

**Description:** Defining a callback function with a variable number of arguments

**Code:**
```pseudocode
[head]
[callback MyAverage]
var(double, Total) = 0;
for(int x = 1 to cb.ArgCount())
   Total = Total + cb.Arg(x);
end for
cb.Return(Total / cb.ArgCount());
[/callback]
[body]
uc.DefineFunction("Average(x ...)", MyAverage);
wl(uc.Eval("Average(10, 3, 7, 4)"))
```

**Output:**
```
6
```

---

### Example ID: 297

**Description:** Demonstrates defining a function that is implemented by a native callback in the host application.

**Code:**
```pseudocode
[head]
[callback MyAreaCallback]
  var length = cb.Arg(1);
  var width = cb.Arg(2);
  cb.Return(length * width);
[/callback]

[body]
// The signature is defined, but the logic is provided by 'MyAreaCallback'.
uc.DefineFunction("Area(x, y)", MyAreaCallback);
wl(uc.Eval("Area(3, 4)"))
```

**Output:**
```
12
```

---

---

## ReturnBool - ID: 113
/doc/reference/classes/ucalc.callback/returnbool/

**Description:** Sets the boolean return value for a callback function.

**Syntax:** ReturnBool(bool)
**Parameters:**
value - bool - The boolean value to be returned to the uCalc engine.
**Return:** void - This method does not return a value.
**Remarks:**

The `ReturnBool` method is used within a callback function to send a boolean result back to the uCalc evaluation engine. It is the designated method for returning values from functions whose signatures are defined with `As Bool`.

When you create a custom function using [DefineFunction](/reference/ucalc/definefunction) and bind it to a native callback, the callback does not use a standard `return` statement to pass data back to uCalc. Instead, it uses the family of `Return...` methods on the `uCalc.Callback` object (`cb`). `ReturnBool` is the type-safe method for boolean values.

### Type-Specific Returns

uCalc provides a specific return method for each primary data type to ensure type safety and clarity:

*   [Return](/reference/ucalc/callback/return): For `Double` (default numeric type).
*   `ReturnBool`: For `Boolean`.
*   [ReturnInt32](/reference/ucalc/callback/returnint32), [ReturnInt64](/reference/ucalc/callback/returnint64), etc.: For specific integer types.
*   [ReturnStr](/reference/ucalc/callback/returnstr): For `String` values.

Using the correct method corresponding to the function's declared return type is crucial for predictable behavior.

### 💡 Comparative Analysis

In a native language like C# or C++, a function returns a value directly:
```csharp
// Native C# function
bool IsPositive(int num) 
{
    return num > 0;
}
```

uCalc's callback mechanism acts as a bridge between the uCalc engine and your native code. The `ReturnBool` method is the tool you use to send a value across that bridge. It is not a direct language `return` but a command to the uCalc engine, telling it what the result of the callback's execution was.

This design allows for deep integration, enabling you to expose complex, high-performance native logic to the uCalc scripting environment in a controlled and type-aware manner.

**Examples:**

### Example ID: 85

**Description:** Return and other type-specific versions of Return

**Code:**
```pseudocode
[head]
[callback BooleanAnd]
   cb.ReturnBool(cb.ArgBool(1) [C]&&[/C][vb]And[/vb] cb.ArgBool(2));
[/callback]
[callback AddInt16]
   [cs]//C# promots Int16 to int for arithmetic hence (Int16) to convert it back 
cb.ReturnInt16((Int16)(cb.ArgInt16(1) + cb.ArgInt16(2)));[/cs]
   [NotCs]cb.ReturnInt16(cb.ArgInt16(1) + cb.ArgInt16(2));[/NotCs]
[/callback]
[callback AddInt32]
   cb.ReturnInt32(cb.ArgInt32(1) + cb.ArgInt32(2));
[/callback]
[callback AddInt64]
   cb.ReturnInt64(cb.ArgInt64(1) + cb.ArgInt64(2));
[/callback]
[body]

uc.DefineFunction("BooleanAnd(x As Bool, y As Bool) As Bool", BooleanAnd);
uc.DefineFunction("AddInt16(x As Int16, y As Int16) As Int16", AddInt16);
uc.DefineFunction("AddInt32(x As Int32, y As Int32) As Int32", AddInt32);
uc.DefineFunction("AddInt64(x As Int64, y As Int64) As Int64", AddInt64);

wl(uc.EvalStr("BooleanAnd(true, false)"))
wl(uc.EvalStr("AddInt16(5.2, 4.1)"))
wl(uc.EvalStr("AddInt32(2, 3)"))
wl(uc.EvalStr("AddInt64(10, 20)"))
```

**Output:**
```
false
9
5
30
```

---

---

## ReturnDbl - ID: 114
/doc/reference/classes/ucalc.callback/returndbl/

**Description:** Sets the double-precision floating-point return value for a custom function or operator implemented via callback.

**Syntax:** ReturnDbl(double)
**Parameters:**
value - double - The double-precision value to be returned from the callback to the uCalc engine.
**Return:** void - This method does not return a value.
**Remarks:**

The `Return` method (or synonymous `ReturnDbl`) is the primary mechanism for sending a `double` result from a native callback function back to the uCalc evaluation engine. When a custom function or operator is called within an expression, this method must be used to provide its output.

### Type-Specific Returns

This method is specifically for returning `double` values. uCalc provides a family of type-safe return methods for other data types. Using the correct method ensures data integrity and avoids unnecessary type conversions.

*   **`Return` / `ReturnDbl`**: For `double` values (this method).
*   **[`ReturnStr`](/Reference/uCalcBase/Callback/ReturnStr)**: For string values.
*   **[`ReturnBool`](/Reference/uCalcBase/Callback/ReturnBool)**: For boolean values.
*   **[`ReturnInt32`](/Reference/uCalcBase/Callback/ReturnInt32)**: For 32-bit integers.
*   **[`ReturnInt64`](/Reference/uCalcBase/Callback/ReturnInt64)**: For 64-bit integers.

### Comparative Analysis

Unlike a native `return` statement in C# or C++, which is a language-level control flow keyword, `cb.Return()` is a method call that interacts with the uCalc engine's internal state. It effectively places the provided value onto the evaluation stack, allowing the engine to continue processing the expression. This distinction is crucial: the callback function itself is typically `void` in the host language, and `cb.Return()` is the designated channel for communicating results back to the parser.

**Examples:**

### Example ID: 11

**Description:** How to define a custom function using a native callback.

**Code:**
```pseudocode
[head]
[callback MyArea]
// Retrieve the 1st and 2nd arguments passed to the function
var Length = cb.Arg(1); 
var Width = cb.Arg(2);

// Calculate the area and return the result to the uCalc engine.
// This logic pattern translates seamlessly across languages.
cb.Return(Length * Width); // Same as cb.ReturnDbl
[/callback]
[body]
uc.DefineFunction("Area(x, y)", MyArea);
wl(uc.Eval("Area(3, 4)"))
```

**Output:**
```
12
```

---

---

## ReturnInt16 - ID: 615
/doc/reference/classes/ucalc.callback/returnint16/

**Description:** Sets the 16-bit integer (short) return value for a callback function.

**Syntax:** ReturnInt16(int16)
**Parameters:**
value - int16 - The 16-bit integer value to be returned to the uCalc engine.
**Return:** void - This method does not return a value.
**Remarks:**

The `ReturnInt16` method is the mechanism for sending a 16-bit integer result from a native callback function back to the uCalc evaluation engine. When a custom function defined with `As Int16` is called within an expression, this method must be used to provide its output.

### ⚙️ Type-Specific Returns

This method is specifically for returning 16-bit integer values. uCalc provides a family of type-safe return methods for other data types. Using the correct method ensures data integrity and avoids unnecessary type conversions.

*   [Return](/reference/ucalc/callback/return): For `Double` values (default numeric type).
*   [ReturnStr](/reference/ucalc/callback/returnstr): For `String` values.
*   [ReturnBool](/reference/ucalc/callback/returnbool): For `Boolean` values.
*   `ReturnInt16`: For 16-bit integers (this method).
*   [ReturnInt32](/reference/ucalc/callback/returnint32): For 32-bit integers.
*   [ReturnInt64](/reference/ucalc/callback/returnint64): For 64-bit integers.

### 💡 Comparative Analysis

Unlike a native `return` statement in C# or C++, which is a language-level control flow keyword, [pseudocode]`cb.ReturnInt16()` is a method call that interacts with the uCalc engine's internal state. It effectively places the provided value onto the evaluation stack, allowing the engine to continue processing the expression. This distinction is crucial: the callback function itself is typically `void` in the host language, and `cb.ReturnInt16()` is the designated channel for communicating results back to the parser.

**Examples:**

### Example ID: 85

**Description:** Return and other type-specific versions of Return

**Code:**
```pseudocode
[head]
[callback BooleanAnd]
   cb.ReturnBool(cb.ArgBool(1) [C]&&[/C][vb]And[/vb] cb.ArgBool(2));
[/callback]
[callback AddInt16]
   [cs]//C# promots Int16 to int for arithmetic hence (Int16) to convert it back 
cb.ReturnInt16((Int16)(cb.ArgInt16(1) + cb.ArgInt16(2)));[/cs]
   [NotCs]cb.ReturnInt16(cb.ArgInt16(1) + cb.ArgInt16(2));[/NotCs]
[/callback]
[callback AddInt32]
   cb.ReturnInt32(cb.ArgInt32(1) + cb.ArgInt32(2));
[/callback]
[callback AddInt64]
   cb.ReturnInt64(cb.ArgInt64(1) + cb.ArgInt64(2));
[/callback]
[body]

uc.DefineFunction("BooleanAnd(x As Bool, y As Bool) As Bool", BooleanAnd);
uc.DefineFunction("AddInt16(x As Int16, y As Int16) As Int16", AddInt16);
uc.DefineFunction("AddInt32(x As Int32, y As Int32) As Int32", AddInt32);
uc.DefineFunction("AddInt64(x As Int64, y As Int64) As Int64", AddInt64);

wl(uc.EvalStr("BooleanAnd(true, false)"))
wl(uc.EvalStr("AddInt16(5.2, 4.1)"))
wl(uc.EvalStr("AddInt32(2, 3)"))
wl(uc.EvalStr("AddInt64(10, 20)"))
```

**Output:**
```
false
9
5
30
```

---

---

## ReturnInt32 - ID: 115
/doc/reference/classes/ucalc.callback/returnint32/

**Description:** Sets the 32-bit integer return value for a callback function.

**Syntax:** ReturnInt32(int32)
**Parameters:**
value - int32 - The 32-bit integer value to be returned to the uCalc engine.
**Return:** void - This method does not return a value.
**Remarks:**

The `ReturnInt32` method is the mechanism for sending a 32-bit integer result from a native callback function back to the uCalc evaluation engine. When a custom function defined with `As Int32` is called within an expression, this method must be used to provide its output.

### ⚙️ Type-Specific Returns

This method is specifically for returning 32-bit integer values. uCalc provides a family of type-safe return methods for other data types. Using the correct method ensures data integrity and avoids unnecessary type conversions.

*   [Return](/reference/ucalc/callback/return): For `Double` values (default numeric type).
*   [ReturnStr](/reference/ucalc/callback/returnstr): For `String` values.
*   [ReturnBool](/reference/ucalc/callback/returnbool): For `Boolean` values.
*   [ReturnInt16](/reference/ucalc/callback/returnint16): For 16-bit integers.
*   `ReturnInt32`: For 32-bit integers (this method).
*   [ReturnInt64](/reference/ucalc/callback/returnint64): For 64-bit integers.

### 💡 Comparative Analysis

Unlike a native `return` statement in C# or C++, which is a language-level control flow keyword, [pseudocode]`cb.ReturnInt32()` is a method call that interacts with the uCalc engine's internal state. It effectively places the provided value onto the evaluation stack, allowing the engine to continue processing the expression. This distinction is crucial: the callback function itself is typically `void` in the host language, and `cb.ReturnInt32()` is the designated channel for communicating results back to the parser.

**Examples:**

### Example ID: 85

**Description:** Return and other type-specific versions of Return

**Code:**
```pseudocode
[head]
[callback BooleanAnd]
   cb.ReturnBool(cb.ArgBool(1) [C]&&[/C][vb]And[/vb] cb.ArgBool(2));
[/callback]
[callback AddInt16]
   [cs]//C# promots Int16 to int for arithmetic hence (Int16) to convert it back 
cb.ReturnInt16((Int16)(cb.ArgInt16(1) + cb.ArgInt16(2)));[/cs]
   [NotCs]cb.ReturnInt16(cb.ArgInt16(1) + cb.ArgInt16(2));[/NotCs]
[/callback]
[callback AddInt32]
   cb.ReturnInt32(cb.ArgInt32(1) + cb.ArgInt32(2));
[/callback]
[callback AddInt64]
   cb.ReturnInt64(cb.ArgInt64(1) + cb.ArgInt64(2));
[/callback]
[body]

uc.DefineFunction("BooleanAnd(x As Bool, y As Bool) As Bool", BooleanAnd);
uc.DefineFunction("AddInt16(x As Int16, y As Int16) As Int16", AddInt16);
uc.DefineFunction("AddInt32(x As Int32, y As Int32) As Int32", AddInt32);
uc.DefineFunction("AddInt64(x As Int64, y As Int64) As Int64", AddInt64);

wl(uc.EvalStr("BooleanAnd(true, false)"))
wl(uc.EvalStr("AddInt16(5.2, 4.1)"))
wl(uc.EvalStr("AddInt32(2, 3)"))
wl(uc.EvalStr("AddInt64(10, 20)"))
```

**Output:**
```
false
9
5
30
```

---

---

## ReturnInt64 - ID: 116
/doc/reference/classes/ucalc.callback/returnint64/

**Description:** Returns a 64-bit integer value from a callback function to the evaluator.

**Syntax:** ReturnInt64(int64)
**Parameters:**
value - int64 - The 64-bit integer value to be returned.
**Return:** void - This method does not return a value; it communicates the result back to the uCalc engine via the callback context.
**Remarks:**

The `ReturnInt64` method is the primary mechanism for sending a 64-bit integer result from a native callback function back to the uCalc evaluation engine. When a custom function or operator is called within an expression, this method must be used within the callback to provide its output.

### 📦 Type-Specific Returns
This method is specifically for returning 64-bit integer values. uCalc provides a family of type-safe return methods for other data types. Using the correct method ensures data integrity and avoids unnecessary type conversions.

*   **Return / ReturnDbl**: For double-precision floating-point values.
*   **ReturnStr**: For string values.
*   **ReturnBool**: For boolean values.
*   **ReturnInt32**: For 32-bit integers.
*   **ReturnInt64**: For 64-bit integers (this method).

### ⚖️ Comparative Analysis
Unlike a native `return` statement in C# or C++, which is a language-level keyword, `ReturnInt64()` is a method call that interacts with the uCalc engine's internal state. It effectively places the provided value onto the evaluation stack, allowing the engine to continue processing the expression. This distinction is crucial: the callback function itself is typically `void` in the host language, and [pseudocode]`cb.ReturnInt64()` is the designated channel for communicating results back to the parser.

**Examples:**

### Example ID: 85

**Description:** Return and other type-specific versions of Return

**Code:**
```pseudocode
[head]
[callback BooleanAnd]
   cb.ReturnBool(cb.ArgBool(1) [C]&&[/C][vb]And[/vb] cb.ArgBool(2));
[/callback]
[callback AddInt16]
   [cs]//C# promots Int16 to int for arithmetic hence (Int16) to convert it back 
cb.ReturnInt16((Int16)(cb.ArgInt16(1) + cb.ArgInt16(2)));[/cs]
   [NotCs]cb.ReturnInt16(cb.ArgInt16(1) + cb.ArgInt16(2));[/NotCs]
[/callback]
[callback AddInt32]
   cb.ReturnInt32(cb.ArgInt32(1) + cb.ArgInt32(2));
[/callback]
[callback AddInt64]
   cb.ReturnInt64(cb.ArgInt64(1) + cb.ArgInt64(2));
[/callback]
[body]

uc.DefineFunction("BooleanAnd(x As Bool, y As Bool) As Bool", BooleanAnd);
uc.DefineFunction("AddInt16(x As Int16, y As Int16) As Int16", AddInt16);
uc.DefineFunction("AddInt32(x As Int32, y As Int32) As Int32", AddInt32);
uc.DefineFunction("AddInt64(x As Int64, y As Int64) As Int64", AddInt64);

wl(uc.EvalStr("BooleanAnd(true, false)"))
wl(uc.EvalStr("AddInt16(5.2, 4.1)"))
wl(uc.EvalStr("AddInt32(2, 3)"))
wl(uc.EvalStr("AddInt64(10, 20)"))
```

**Output:**
```
false
9
5
30
```

---

---

## ReturnPtr - ID: 117
/doc/reference/classes/ucalc.callback/returnptr/

**Description:** Returns a pointer value from a callback function.

**Syntax:** ReturnPtr(IntPtr)
**Parameters:**
value - IntPtr - The pointer or handle to be returned from the callback.
**Return:** void - This method does not return a value.
**Remarks:**

`ReturnPtr` is the specialized method within a [uCalc.Callback](/Reference/uCalcBase/Callback/Constructor) for returning a raw memory address (a pointer or handle) from a native function back to the uCalc expression engine. This is the primary mechanism for interoperability when an expression needs to work with references to host-application objects or internal data structures rather than their values.

### 🎯 Core Use Case: Host Application Interop

While standard `Return` functions deal with values that uCalc understands (like numbers and strings), `ReturnPtr` is used when the value is an opaque handle meaningful only to the host application or other specialized uCalc functions. Common scenarios include:

*   Returning handles to files, database connections, or UI elements.
*   Passing pointers to complex C/C++ structs or C# objects that will be used by other callback functions.
*   Implementing custom memory allocators or object factories within uCalc.

The expression that receives the pointer can then pass this handle to other custom functions that know how to use it (e.g., `ReadFile(handle)`).

### ⚙️ Pointer Safety and Semantics

The uCalc engine treats the returned pointer as an opaque integer value. It does **not** attempt to dereference, validate, or manage the memory at that address. All responsibility for the pointer's validity and lifetime rests with the host application.

⚠️ **Important**: Do not return pointers to stack-allocated variables within your callback function. The memory will be invalid as soon as the callback returns, leading to undefined behavior.

### 🆚 Comparative Analysis

*   **vs. Native C++/C# Pointers**: In native code, returning a pointer is a direct operation. `ReturnPtr` acts as the necessary bridge to safely transport that native pointer across the boundary into the sandboxed uCalc environment. The value is not in "improving" on native pointers, but in *enabling* their use within uCalc expressions.

*   **vs. `Return()` / `ReturnStr()`**: The standard `Return` methods pass *values* that are copied into uCalc's memory management system. `ReturnPtr` passes a *reference* that remains outside of uCalc's control. Use standard `Return` for data, and `ReturnPtr` for handles or references.

### Example Breakdown
The practical example demonstrates creating a custom version of the built-in `AddressOf` function.
1.  A function `GetAddressOf` is defined with a `ByHandle` parameter, allowing it to inspect the argument's metadata.
2.  The callback uses `cb.ArgItem(1).ValueAddr()` to get the internal memory address of the variable passed to it.
3.  `cb.ReturnPtr(...)` sends this address back to the evaluator.
4.  The [ValueAt()](/Reference/uCalcBase/uCalc/ValueAt) function is then used in the expression to dereference the pointer and retrieve the original variable's value, proving the round trip was successful.

This showcases a complete cycle: passing a reference into a callback, getting its address, returning the address as a pointer, and using that pointer in another function.

**Examples:**

### Example ID: 86

**Description:** Returning a pointer with ReturnPtr

**Code:**
```pseudocode
[head]
[callback GetAddressOf]
   cb.ReturnPtr(cb.ArgItem(1).ValueAddr());
[/callback]
[body]

// This example is for sake of illustration
// There is already a built-in AddressOf() function

uc.DefineFunction("GetAddressOf(ByHandle Variable As AnyType) As SameTypeAs:0 Ptr", GetAddressOf);

uc.DefineVariable("MyVariable = 123.456");
uc.DefineVariable("MyStr = 'Hello world!'");

wl(uc.EvalStr("ValueAt(GetAddressOf(MyVariable))"))
wl(uc.EvalStr("ValueAt(GetAddressOf(MyStr))"))
```

**Output:**
```
123.456
Hello world!
```

---

---

## ReturnStr - ID: 118
/doc/reference/classes/ucalc.callback/returnstr/

**Description:** Sets the string return value for a user-defined callback function, passing it back to the uCalc expression engine.

**Syntax:** ReturnStr(string)
**Parameters:**
returnValue - string - The string value that the callback function should return to the expression evaluator.
**Return:** void - This method does not return a value to the host application; it communicates the return value back to the uCalc engine via the callback object.
**Remarks:**

The `ReturnStr` method is the mechanism for sending a string result from a native callback function back to the uCalc evaluation engine. When a custom function defined with `As String` is called within an expression, this method must be used to provide its output.

### ⚙️ Type-Specific Returns

This method is specifically for returning string values. uCalc provides a family of type-safe return methods for other data types. Using the correct method ensures data integrity and avoids unnecessary type conversions.

*   [Return](/reference/ucalc/callback/return): For `Double` values (default numeric type).
*   `ReturnStr`: For `String` values (this method).
*   [ReturnBool](/reference/ucalc/callback/returnbool): For `Boolean` values.
*   [ReturnInt16](/reference/ucalc/callback/returnint16): For 16-bit integers.
*   [ReturnInt32](/reference/ucalc/callback/returnint32): For 32-bit integers.
*   [ReturnInt64](/reference/ucalc/callback/returnint64): For 64-bit integers.

### 💡 Comparative Analysis

Unlike a native `return` statement in C# or C++, which is a language-level control flow keyword, [pseudocode]`cb.ReturnStr()` is a method call that interacts with the uCalc engine's internal state. It effectively places the provided value onto the evaluation stack, allowing the engine to continue processing the expression. This distinction is crucial: the callback function itself is typically `void` in the host language, and [pseudocode]`cb.ReturnStr()` is the designated channel for communicating results back to the parser.

**Examples:**

### Example ID: 15

**Description:** Returning a string (from a callback)

**Code:**
```pseudocode
[head]
[callback TwiceStr]
   cb.ReturnStr(cb.ArgStr(1) + cb.ArgStr(1));
[/callback]
[body]
uc.DefineFunction("Twice(Txt As String) As String", TwiceStr);
wl(uc.EvalStr("Twice('Bye')"))
```

**Output:**
```
ByeBye
```

---

---

## uCalc = [uCalc] - ID: 119
/doc/reference/classes/ucalc.callback/ucalc-=-[ucalc]/

**Description:** Retrieves the parent uCalc instance that owns the function or operator currently executing the callback.

**Remarks:**

The `uCalc()` method provides access to the parent `uCalc` instance from within a callback function. This is a crucial feature that elevates callbacks from simple, isolated calculations to powerful, interactive components that can query and modify the engine's state.

### 🎯 Core Use Cases

Accessing the parent instance allows your callback to:

*   **Evaluate Expressions**: Use methods like [EvalStr](/reference/ucalc/evalstr) or [Parse](/reference/ucalc/parse) to perform secondary calculations within the same context.
*   **Access Engine Services**: Retrieve type definitions with [DataTypeOf](/reference/ucalc/datatypeof), look up other items with [ItemOf](/reference/ucalc/itemof), or inspect instance settings.
*   **Modify State**: Dynamically create new symbols with [DefineVariable](/reference/ucalc/definevariable) or [DefineFunction](/reference/ucalc/definefunction) based on the callback's logic.
*   **Access Variables**: Read or write to other variables that exist within the instance's scope.

### 💡 Comparative Analysis

In many programming environments (like C# or C++), a callback function is typically stateless and unaware of its invocation context unless that context is explicitly passed as an argument. The `uCalc()` method provides this context automatically.

This is akin to having a built-in dependency injection system for every callback. Instead of a function being a simple black box that takes inputs and produces an output, it becomes an agent that can interact with the entire parsing environment it lives in. This enables highly dynamic and stateful behavior that is difficult to achieve in other systems without significant boilerplate code.

**Examples:**

### Example ID: 16

**Description:** How to handle and retrieve various data types (including pointers) within a callback.

**Code:**
```pseudocode
[head]
[callback MyFunction]
   var uc = cb.@uCalc();
   wl("------ MyFunc ------")

   // Retrieve standard 32-bit and 64-bit integer arguments directly
   wl(cb.ArgInt32(1))
   wl(cb.ArgInt64(2))

   // Retrieve the value of a pointer argument by referencing its exact data type.
   wl(uc.ItemOf("Int8").@DataType().ToString(cb.ArgAddr(3)))

   // The Item object correctly identifies the type before conversion
   wl(uc.ItemOf("Int").@DataType().ToString(cb.ArgPtr(4)))
[/callback]

[callback MyFunction2]
   var uc = cb.@uCalc();
   wl("------ MyFunc2 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_8).ToString(cb.ArgPtr(1)))
[/callback]

[callback MyFunction3]
   var uc = cb.@uCalc();
   wl("------ MyFunc3 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_16).ToString(cb.ArgPtr(1)))
[/callback]
[body]
uc.DefineVariable("x As Int = 123"); // Int32
uc.DefineVariable("xPtr As Int Ptr = AddressOf(x)");
uc.DefineFunction("MyFunc(a As Int32, b As Int64, c As Byte, d As Int Ptr)", MyFunction);
uc.Eval("MyFunc(x*10, 1+1, 255, xPtr)");

uc.DefineVariable("x2 As Int8 = -123");
uc.DefineVariable("xPtr2 As Int8 Ptr = AddressOf(x2)");
uc.DefineFunction("MyFunc2(d As Int8 Ptr)", MyFunction2);
uc.Eval("MyFunc2(xPtr2)");

uc.DefineVariable("x3 As Int16 = 1234");
uc.DefineVariable("xPtr3 As Int16 Ptr = AddressOf(x3)");
uc.DefineFunction("MyFunc3(d As Int16 Ptr)", MyFunction3);
uc.Eval("MyFunc3(xPtr3)");
```

**Output:**
```
------ MyFunc ------
1230
2
-1
123
------ MyFunc2 ------
-123
------ MyFunc3 ------
1234
```

---

---

## uCalc.DataType - ID: 120
/doc/reference/classes/ucalc.datatype/

**Description:** Class for working with uCalc data types

---

## Introduction - ID: 960
/doc/reference/classes/ucalc.datatype/introduction/

**Description:** An overview of the DataType class, which provides metadata and functionality for specific data types within the uCalc engine.

**Remarks:**

# ⚙️ The DataType Class: Runtime Type Introspection

The `DataType` class is a first-class object that represents the metadata and behavior of a specific data type within the uCalc engine. It's more than just a simple type identifier; it's an interactive object that holds information about a type's name, size in memory, and associated conversion and formatting logic.

This class is the foundation of uCalc's dynamic type system, providing the tools for runtime introspection, type safety, and the creation of custom data types.

---

## Core Concepts

*   **Runtime Introspection**: Unlike compile-time type systems (like C#'s `typeof` or C++'s `typeid`), uCalc's `DataType` objects can be retrieved and inspected at runtime using string names or enums via the [uCalc.DataTypeOf](/Reference/uCalcBase/uCalc/DataTypeOf) method. This allows your application to make dynamic decisions based on the types of variables or expression results.

*   **Instance-Specific Behavior**: Every [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance maintains its own registry of `DataType` objects. This powerful feature allows you to customize the behavior of a type (e.g., its string representation) in one parser instance without affecting any others.

*   **Custom Types**: While uCalc comes with a rich set of built-in types, you can define new data types or create aliases for existing ones at runtime using the [DataType Constructor](/Reference/uCalcBase/DataType/Constructor). This is essential for building expressive Domain-Specific Languages (DSLs).

## Boolean properties

The numeric value for a Boolean when True, and the string to return for `True` and `False` can be changed using `Define("Boolean:")`.

For instance, if you want the numeric representation of a Boolean to to be -1, and for it to return `Yes` and `No` for `true` and `false` when converted to a string, you can do:
```
uc.Define("Boolean: -1, Yes, No");
```

If you want the numeric representation of a Boolean to to be 1, and for it to return `Correct` and `Incorrect` for `true` and `false` when converted to a string, you can do:
```
uc.Define("Boolean: 1, Correct, Incorrect");
```

The numeric value for a Boolean when `false` is always 0.

---

## 📖 Class Members

The following properties and methods are available on a `DataType` object.

| Member                                                         | Description                                                                                                  |
| :------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------------- |
| [Constructor](/Reference/uCalcBase/DataType/Constructor)         | Creates a new data type definition within a uCalc instance or an empty placeholder.                        |
| [BuiltInTypeEnum](/Reference/uCalcBase/DataType/BuiltInTypeEnum)     | Retrieves the `BuiltInType` enumeration member that uniquely identifies a built-in data type.             |
| [ByteSize](/Reference/uCalcBase/DataType/ByteSize)               | Gets the size, in bytes, that a single value of this data type occupies in memory.                           |
| [Description](/Reference/uCalcBase/DataType/Description)           | Gets or sets a user-defined text description for a DataType object.                                          |
| [Handle](/Reference/uCalcBase/DataType/Handle)                   | Returns the internal, low-level handle of the DataType object.                                               |
| [IsCompound](/Reference/uCalcBase/DataType/IsCompound)             | Determines if the data type represents a compound value, such as a String or Complex number.                 |
| [IsDefault](/Reference/uCalcBase/DataType/IsDefault)               | Gets or sets whether this data type is the engine's default for implicit typing.                             |
| [Item](/Reference/uCalcBase/DataType/Item)                       | Retrieves the underlying [Item](/Reference/uCalcBase/Item/Constructor) object that represents this data type.                                  |
| [MemoryIndex](/Reference/uCalcBase/DataType/MemoryIndex)           | Returns the unique, stable index value that identifies the data type object.                                 |
| [Name](/Reference/uCalcBase/DataType/Name)                       | Retrieves the canonical string name of the data type.                                                        |
| [Release](/Reference/uCalcBase/DataType/Release)                 | Unregisters a custom data type and releases its associated resources.                                        |
| [Reset](/Reference/uCalcBase/DataType/Reset)                     | Resets a scalar variable to the default value for its data type.                                             |
| [SetScalar](/Reference/uCalcBase/DataType/SetScalar)               | Performs a low-level copy of a scalar value from a source memory address to a destination address.             |
| [SwapScalarValues](/Reference/uCalcBase/DataType/SwapScalarValues)   | Efficiently swaps the values of two uCalc variables of the same underlying data type.                            |
| [ToString](/Reference/uCalcBase/DataType/ToString)                 | Converts a value to its string representation, either from a memory address or by parsing a string.          |
| [uCalc](/Reference/uCalcBase/DataType/uCalc)                     | Retrieves the parent [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance that owns and manages this data type definition.                 |


**Examples:**

### Example ID: 2

**Description:** Getting data type object with DataTypeOf

**Code:**
```pseudocode
wl(uc.DataTypeOf(BuiltInType::Integer_8u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Integer_16u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Boolean).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::String).ToString("-1"))

wl(uc.DataTypeOf(BuiltInType::Integer_8u).@Name())
wl(uc.DataTypeOf(BuiltInType::Integer_32).@ByteSize())
```

**Output:**
```
255
65535
true
-1
int8u
4
```

---

### Example ID: 3

**Description:** Returning the data type of an expression

**Code:**
```pseudocode
wl(uc.DataTypeOf("10 + 20 - 3").@Name())
wl(uc.DataTypeOf(" 'What type ' + 'is this?' ").@Name())
wl(uc.DataTypeOf("3 < 10").@Name())
wl(uc.DataTypeOf("5 + 7 * #i").@Name())
wl("---")

uc.DefineFunction("func(x) as string = 'Hello' * 3");
wl(uc.DataTypeOf("func").@Name())
wl(uc.DataTypeOf("Int").@Name())
wl(uc.DataTypeOf("NonExistantType").@Name()) // Empty string
wl(uc.DataTypeOf("&&").@Name())


```

**Output:**
```
double
string
bool
complex
---
string
int

bool
```

---

---

## (Constructor) - ID: 650
/doc/reference/classes/ucalc.datatype/-constructor/

**Description:** Creates a new data type definition within a uCalc instance or an empty placeholder.

**Remarks:**

## ⚙️ uCalc.DataType Constructor

The `DataType` constructor is the primary mechanism for defining custom data types at runtime within a `uCalc` instance. While you often retrieve existing types using methods like [uCalc.DataTypeOf](/reference/ucalc/datatypeof), this constructor allows you to extend the engine with new types or create aliases for existing ones.

This is functionally equivalent to calling [uCalc.Define](/reference/ucalc/define) with a `DataType:` command string.

--- 

## Constructor Overloads

### 1. `DataType(string Definition)`
This is the main constructor for creating a new data type. The `Definition` string follows a specific syntax:

`DataType: NewTypeName : BaseTypeName`

*   **`DataType:`**: A required keyword indicating the type of definition.
*   **`NewTypeName`**: The name for your new data type.
*   **`:`**: A required separator.
*   **`BaseTypeName`**: The existing, built-in uCalc type that your new type inherits from (e.g., `Integer_32`, `Double`, `String`).

### 2. `DataType(uCalc uc, string Definition)`
Creates the data type within a specific `uCalc` instance rather than the default one.

### 3. `DataType(DataType::Empty)`
Creates an empty placeholder `DataType` object. This is useful for deferred initialization where you can create a variable to hold the type and assign a full definition to it later.

--- 

## 💡 Comparative Analysis: Why uCalc?

In statically-typed languages like C# or C++, types are defined at compile time. You cannot create a new `class` or `struct` while the program is running.

**uCalc's key advantage is dynamism.** The `DataType` constructor allows your application to define new types at runtime, based on configuration files, user input, or other dynamic conditions. This is fundamental for building:

*   **Domain-Specific Languages (DSLs)**: Create types that are meaningful to your domain (e.g., `Currency`, `Coordinate`, `ProductID`) to make expressions more readable and self-documenting.
*   **Adaptable Systems**: Allow end-users to define their own data structures within a scripting environment.
*   **Type Aliasing**: Simplify complex type names with shorter, more convenient aliases.

This runtime extensibility provides a level of flexibility that is impossible to achieve with a compiled, static type system.

**Examples:**

### Example ID: 2

**Description:** Getting data type object with DataTypeOf

**Code:**
```pseudocode
wl(uc.DataTypeOf(BuiltInType::Integer_8u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Integer_16u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Boolean).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::String).ToString("-1"))

wl(uc.DataTypeOf(BuiltInType::Integer_8u).@Name())
wl(uc.DataTypeOf(BuiltInType::Integer_32).@ByteSize())
```

**Output:**
```
255
65535
true
-1
int8u
4
```

---

### Example ID: 3

**Description:** Returning the data type of an expression

**Code:**
```pseudocode
wl(uc.DataTypeOf("10 + 20 - 3").@Name())
wl(uc.DataTypeOf(" 'What type ' + 'is this?' ").@Name())
wl(uc.DataTypeOf("3 < 10").@Name())
wl(uc.DataTypeOf("5 + 7 * #i").@Name())
wl("---")

uc.DefineFunction("func(x) as string = 'Hello' * 3");
wl(uc.DataTypeOf("func").@Name())
wl(uc.DataTypeOf("Int").@Name())
wl(uc.DataTypeOf("NonExistantType").@Name()) // Empty string
wl(uc.DataTypeOf("&&").@Name())


```

**Output:**
```
double
string
bool
complex
---
string
int

bool
```

---

### Example ID: 4

**Description:** Setting/retrieving default data type

**Code:**
```pseudocode
// Check default data type
wl(uc.@DefaultDataType().@Name())

// This examples shows setting the default data type in 3
// different ways: by BuiltInType enum, DataType ojbect,
// or data type by name (string)

// Change default default data type
uc.@DefaultDataType(uc.DataTypeOf(BuiltInType::Integer_16));
wl(uc.@DefaultDataType().@Name())

// Test new default (returns integers instead of double)

uc.DefineFunction("ff(x, y) = (x + y)/3");
// same as ff(x As int16, y As int16) As int16 = ...

uc.DefineFunction("gg(x) = x*100");
// same as gg(x As int16) As int16 = ...

wl(uc.Eval("ff(4, 12)"))
wl(uc.Eval("gg(6.1)"))

uc.SetDefaultDataType("Single");
wl(uc.@DefaultDataType().@Name())

// Change back to original default (double)
uc.SetDefaultDataType(BuiltInType::Float_Double);

// Verify that default is now double
wl(uc.@DefaultDataType().@Name())
```

**Output:**
```
double
int16
5
600
single
double
```

---

### Example ID: 41

**Description:** Displaying the data type of a parsed expression

**Code:**
```pseudocode
wl(uc.Parse(" 3 + 6 * 10 ").@DataType().@Name())
wl(uc.Parse(" 'This ' + 'is a string' ").@DataType().@Name())
wl(uc.Parse(" 2 + 8 * #i / 2").@DataType().@Name())
wl(uc.Parse(" 10 + 2 > 3").@DataType().@Name())
```

**Output:**
```
double
string
complex
bool
```

---

### Example ID: 50

**Description:** Displaying the data type name and size of a variable

**Code:**
```pseudocode
var MyVariable = uc.DefineVariable("MyVariable");
wl("MyVariable type: " + MyVariable.@DataType().@Name())
wl("MyVariable size: ", MyVariable.@DataType().@ByteSize())
```

**Output:**
```
MyVariable type: double
MyVariable size: 8
```

---

---

## BuiltInTypeEnum = [BuiltInType] - ID: 123
/doc/reference/classes/ucalc.datatype/builtintypeenum-=-[builtintype]/

**Description:** Retrieves the `BuiltInType` enumeration member that uniquely identifies a built-in data type.

**Remarks:**

This method returns the specific [BuiltInType](/reference/enums/builtintype/) enum member that corresponds to the `DataType` object. It provides a fast and reliable way to identify built-in types using a stable, numeric code.

### 🎯 Why Use This Method?

While you can identify a type by its [Name](/reference/ucalcbase/datatype/name) (e.g., `"Double"`), using its enum value is often superior for several reasons:

*   **Performance**: Comparing two integers is significantly faster than comparing two strings. This is critical in performance-sensitive callbacks or tight loops.
*   **Robustness**: The enum value is stable. The display name of a data type might be changed or localized, but its underlying `BuiltInType` member will remain the same.
*   **Clarity in Logic**: The enum is ideal for use in `switch` statements or `if`/`else if` chains, making type-dispatching logic clean and readable.

### ⚖️ Comparative Analysis

*   **vs. .NET `Type.GetTypeCode()`**: This method is functionally very similar to `GetTypeCode()` in the .NET Framework, which returns a `TypeCode` enum for primitive types. Developers familiar with this pattern will find this method intuitive.

*   **vs. C++ `typeid` and `std::is_same`**: In C++, type identification is often done at compile-time with templates or at runtime with RTTI (`typeid`). uCalc's method provides a simple, runtime mechanism that works consistently across all supported languages (C#, C++, VB) without requiring complex template metaprogramming.

The [Name()](/reference/ucalcbase/datatype/name) method is good for display and logging, while this method is designed for programmatic logic and type checking.

**Examples:**

### Example ID: 66

**Description:** Operator ByRef, AnyType, SameTypeAs, Precedence, RightToLeft, callback

**Code:**
```pseudocode
[head]
[callback AssignValueA]
   cb.@uCalc().DataTypeOf(BuiltInType::Integer_64).SetScalar(cb.ArgPtr(1), cb.ArgAddr(2));
   // C++ can do it with pointers instead like the commented line below:
   // *(int64_t *)cb.ArgInt64(1) = cb.ArgInt64(2);
[/callback]
[callback AssignValueB]
   if (cb.ArgItem(1).@DataType().@BuiltInTypeEnum() == BuiltInType::String)
      cb.ArgItem(1).ValueStr(cb.ArgItem(2).ValueStr());
   else
      cb.ArgItem(1).@DataType().SetScalar(cb.ArgItem(1).ValueAddr(), cb.ArgItem(2).ValueAddr());
   end if
[/callback]
[body]

// ByRef approach (only for primitive types only, like double, int, etc., not composite types like strings)
wl("-- ByRef approach --")
uc.DefineOperator("{ByRef variable As AnyType} SetValA {value As SameTypeAs:0} As SameTypeAs:0", uc.ItemOf("=").@Precedence(), Associativity::RightToLeft, AssignValueA);
uc.DefineVariable("MyDbl As Double");
uc.DefineVariable("MyInt As Int");
uc.DefineVariable("MyStr As String");

uc.Eval("MyDbl SetValA 3.14");
uc.Eval("MyInt SetValA Int(3.14 * 10)");

wl("MyDbl: " + uc.EvalStr("MyDbl"))
wl("MyInt: " + uc.EvalStr("MyInt"))

// ByHandle approach
wl("-- ByHandle approach --")
uc.DefineOperator("{ByHandle variable As AnyType} SetValB {ByHandle val As SameTypeAs:0}", uc.ItemOf("=").@Precedence(), Associativity::RightToLeft, AssignValueB);
uc.Eval("MyDbl SetValB 123.456");
uc.Eval("MyInt SetValB Int(555.123)");
uc.Eval("MyStr SetValB 'Hello World'");

wl("MyDbl: " + uc.EvalStr("MyDbl"))
wl("MyInt: " + uc.EvalStr("MyInt"))
wl("MyStr: " + uc.EvalStr("MyStr"))

```

**Output:**
```
-- ByRef approach --
MyDbl: 3.14
MyInt: 31
-- ByHandle approach --
MyDbl: 123.456
MyInt: 555
MyStr: Hello World
```

---

---

## ByteSize = [int] - ID: 121
/doc/reference/classes/ucalc.datatype/bytesize-=-[int]/

**Description:** Gets the size, in bytes, that a single value of this data type occupies in memory.

**Remarks:**

The `ByteSize` method returns the number of bytes a single unit of this data type occupies in memory. This is essential for understanding memory layout, performing serialization, or interfacing with external native code that requires explicit size information.

### Common Data Type Sizes

The following table shows the byte sizes for some of uCalc's common built-in types on a typical 64-bit system.

| Data Type Name | `BuiltInType` Enum Member | ByteSize | Notes |
| :--- | :--- | :--- | :--- |
| 32-bit Integer | `Integer_32` | 4 | Standard integer size. |
| 64-bit Integer | `Integer_64` | 8 | Long integer. |
| Double | `Float_Double` | 8 | Default floating-point type. |
| Boolean | `Boolean` | 4 | Typically aligned to an integer. |
| String | `String` | 8 | Size of the handle/pointer to the string data, not the character length. |
| Pointer | `Pointer` | 8 | Size of a memory address. |

**Note on Dynamic Types**: For compound or variable-length types like [`String`](/reference/enums/builtintype), `ByteSize` returns the size of the internal handle or pointer, not the size of the allocated content. To get the number of characters in a string, use the `Length()` function.

### ⚖️ Comparative Analysis

*   **vs. C++/C# `sizeof(T)`**: In C++ and C#, `sizeof` is a **compile-time operator** that returns the size of a type. uCalc's `ByteSize()` is a **runtime method**. This means you can dynamically query the size of a data type whose identity might not be known until the program is running, which is a key advantage for scripting and dynamic environments.

*   **Utility**: `ByteSize` is particularly useful when working with arrays or when binding uCalc variables to structured memory buffers in the host application. It allows you to perform pointer arithmetic and calculate memory offsets correctly based on uCalc's internal type system.

**Examples:**

### Example ID: 50

**Description:** Displaying the data type name and size of a variable

**Code:**
```pseudocode
var MyVariable = uc.DefineVariable("MyVariable");
wl("MyVariable type: " + MyVariable.@DataType().@Name())
wl("MyVariable size: ", MyVariable.@DataType().@ByteSize())
```

**Output:**
```
MyVariable type: double
MyVariable size: 8
```

---

---

## Description = [string] - ID: 872
/doc/reference/classes/ucalc.datatype/description-=-[string]/

**Remarks:**

This sets/returns a Description associated with a DataType object.

---

## Handle - ID: 122
/doc/reference/classes/ucalc.datatype/handle/

**Description:** Returns the internal, low-level handle of the DataType object, used for internal engine communication and advanced debugging.

**Syntax:** Handle()
**Return:** ADDR - Returns the internal handle of the `DataType` object. While typed as a `DataType` for convenience, it represents an opaque identifier whose numeric value is not guaranteed to be consistent across application runs.
**Remarks:**

This method retrieves the internal handle of a `DataType` object. Handles are opaque, pointer-like identifiers used by the uCalc library to manage instances. This is primarily intended for advanced debugging and internal diagnostics.

### What is a Handle?
A handle is a unique, low-level identifier for a specific `DataType` instance in memory. Its actual numeric value is unpredictable and can change every time the application runs. It should not be stored or used for serialization.

For a stable and predictable identifier, use [MemoryIndex](/reference/ucalcbase/datatype/memoryindex) instead.

--- 

### ⚖️ `Handle` vs. `MemoryIndex`

| Feature | Handle | [MemoryIndex](/reference/ucalcbase/datatype/memoryindex) |
| :--- | :--- | :--- |
| **Stability** | **Volatile**. Changes between application runs. | **Stable**. Predictable and sequential. |
| **Uniqueness** | Guaranteed unique for the object's lifetime. | Can be **recycled** after an object is released. |
| **Purpose** | Low-level object identification for the C++ core. | High-level diagnostics and tracking object lifetime. |
| **Use Case** | Advanced debugging. | Identifying specific instances for logging or in diagnostic tools. |

--- 

### Comparative Analysis

In C# or C++, you might think of a handle as being similar to an `IntPtr` or a raw pointer (`void*`). It refers to a specific memory location managed by the uCalc engine. However, unlike raw pointers, the uCalc handle is managed within the uCalc ecosystem. The key takeaway for developers is to use [MemoryIndex](/reference/ucalcbase/datatype/memoryindex) for any form of stable identification and to treat the `Handle` as a transient, internal-only value.

**Examples:**

---

## IsCompound = [bool] - ID: 659
/doc/reference/classes/ucalc.datatype/iscompound-=-[bool]/

**Description:** Determines if the data type represents a compound value, such as a String or Complex number.

**Remarks:**

The `IsCompound` property helps distinguish between simple, fundamental data types and more complex, composite ones.

A compound data type is one that is not a simple, primitive numeric or boolean value. In uCalc, this currently includes `String` and `Complex` types. This is useful for logic that needs to handle strings and numbers differently without checking for every possible numeric type individually.

### Type Categories

#### ✅ Returns `true` for Compound Types
*   `String`: A sequence of characters.
*   `Complex`: A number consisting of a real and an imaginary part.

#### ❌ Returns `false` for Simple Types
*   `Boolean`
*   `Byte` (Int8)
*   `Int16`, `Int32`, `Int64`
*   `Single`, `Double`

### Comparative Analysis

Without uCalc, determining if a type is "compound" in a host language like C# can be ambiguous. A developer might check if a `Type` object `IsPrimitive` or `IsValueType`, but these concepts don't map directly to uCalc's domain. For example, a C# `string` is a class (a reference type), not a primitive, while a `System.Numerics.Complex` is a struct (a value type).

uCalc's `IsCompound` provides a consistent and straightforward way to classify types based on their role within the expression engine, simplifying the logic for the end-user.

For example, to categorize results:
```pseudocode
var dt = uc.DataTypeOf(expression);
if (dt.IsCompound())
  // Handle string or complex result
else
  // Handle numeric or boolean result
end if
```

**Examples:**

### Example ID: 87

**Description:** Determining if a data type is compound or not with IsCompound

**Code:**
```pseudocode
wl(bool(uc.DataTypeOf("2 * (3 + 4)").@IsCompound()))
wl(bool(uc.DataTypeOf(" 'Hello ' + 'world!' ").@IsCompound()))
wl(bool(uc.DataTypeOf("3 + 4 * #i").@IsCompound()))
wl(bool(uc.DataTypeOf(BuiltInType::String).@IsCompound()))
wl(bool(uc.DataTypeOf("Bool").@IsCompound()))
```

**Output:**
```
False
True
True
True
False
```

---

---

## IsDefault = [bool] - ID: 661
/doc/reference/classes/ucalc.datatype/isdefault-=-[bool]/

**Description:** Sets or unsets this data type as the engine's default for implicit typing.

**Remarks:**

This property sets the data type for the current object as the default for its parent `uCalc` instance. It is a convenient shortcut for calling [uCalc.DefaultDataType](/Reference/uCalcBase/uCalc/DefaultDataType).

### ⚙️ How it Works

By default, uCalc uses `Double` as the data type for any variable or function parameter that is not explicitly typed. This method allows you to change that default.

*   Calling [pseudocode]`myIntType.IsDefault(true)` is equivalent to calling [pseudocode]`uc.DefaultDataType(myIntType)`.
*   Calling [pseudocode]`myIntType.IsDefault(false)` reverts the default data type back to `Double` if `myIntType` was the active default.

To check if a data type is the current default, use the getter overload: [IsDefault()](/Reference/uCalcBase/DataType/IsDefault/IsDefault).

### 🤔 Why Change the Default Data Type?

Changing the default is useful when an application's logic is primarily centered around a specific data type:

*   **Integer-Based Applications**: For applications dealing with counters, indices, or bitwise operations, setting the default to `Int32` or `Int64` avoids floating-point inaccuracies and can simplify code.
*   **String Processing**: For text manipulation tools, making `String` the default can be more intuitive.
*   **Enforcing Precision**: In financial or scientific applications, you might set `Decimal` or a custom high-precision numeric type as the default.

### 💡 Comparative Analysis

*   **vs. C# `var` / C++ `auto`**: In these languages, type is *inferred* from an initialization value (e.g., `var x = 5;` becomes an `int`). uCalc does this too, but if a variable is defined without an initial value (e.g., [pseudocode]`uc.DefineVariable("x")`), it must fall back to a default type. This method controls that fallback.

*   **vs. Visual Basic `Option Strict Off`**: In VB, an untyped variable often defaults to `Object`. uCalc's approach is more specialized for mathematical and parsing contexts, defaulting to `Double` for performance and convenience in numerical calculations unless configured otherwise.

**Examples:**

### Example ID: 89

**Description:** Sets a data type as the default

**Code:**
```pseudocode
wl(bool(uc.DataTypeOf("double").@IsDefault()))
wl(bool(uc.DataTypeOf("int64").@IsDefault()))
wl(uc.@DefaultDataType().@Name())
wl("---")

uc.DataTypeOf("int64").@IsDefault(true);

wl(bool(uc.DataTypeOf("double").@IsDefault()))
wl(bool(uc.DataTypeOf("int64").@IsDefault()))
wl(uc.@DefaultDataType().@Name())
wl("---")

uc.DataTypeOf("int64").@IsDefault(false);

wl(bool(uc.DataTypeOf("double").@IsDefault()))
wl(bool(uc.DataTypeOf("int64").@IsDefault()))
wl(uc.@DefaultDataType().@Name())
```

**Output:**
```
True
False
double
---
False
True
int64
---
True
False
double
```

---

### Example ID: 530

**Description:** Sets the default data type to `Int32` for implicit variable definitions.

**Code:**
```pseudocode
var intType = uc.DataTypeOf("Int32");
intType.@IsDefault(true);

// Define a variable without specifying a type or initial value.
var myVar = uc.DefineVariable("myVar");

// Check the variable's type.
wl("Default type is now: ", uc.@DefaultDataType().@Name());
wl("myVar's type is: ", myVar.@DataType().@Name());
```

**Output:**
```
Default type is now: int
myVar's type is: int
```

---

### Example ID: 532

**Description:** Internal Test: Verifies the ability to set and unset a data type as the default.

**Code:**
```pseudocode
// Initial state: Double is the default
wl("Double is default: ", bool(uc.DataTypeOf("double").@IsDefault()))
wl("Int64 is default: ", bool(uc.DataTypeOf("int64").@IsDefault()))
wl("Current default: ", uc.@DefaultDataType().@Name())
wl("---")

// Set Int64 as the default
uc.DataTypeOf("int64").@IsDefault(true);
wl("Double is default: ", bool(uc.DataTypeOf("double").@IsDefault()))
wl("Int64 is default: ", bool(uc.DataTypeOf("int64").@IsDefault()))
wl("Current default: ", uc.@DefaultDataType().@Name())
wl("---")

// Revert back to Double by un-setting Int64
uc.DataTypeOf("int64").@IsDefault(false);
wl("Double is default: ", bool(uc.DataTypeOf("double").@IsDefault()))
wl("Int64 is default: ", bool(uc.DataTypeOf("int64").@IsDefault()))
wl("Current default: ", uc.@DefaultDataType().@Name())
```

**Output:**
```
Double is default: True
Int64 is default: False
Current default: double
---
Double is default: False
Int64 is default: True
Current default: int64
---
Double is default: True
Int64 is default: False
Current default: double
```

---

---

## Item = [Item] - ID: 124
/doc/reference/classes/ucalc.datatype/item-=-[item]/

**Description:** Retrieves the underlying Item object that represents this data type, enabling access to common symbol properties.

**Remarks:**

In the uCalc engine, every defined symbol—whether it's a [variable](/reference/ucalc/item/isproperty), [function](/reference/ucalc/item/isproperty), or even a **data type**—is fundamentally represented by a universal [Item](/reference/ucalc/item) object. This method serves as the bridge, allowing you to access the underlying `Item` for a specific [DataType](/reference/ucalc/datatype) instance.

By retrieving the `Item`, you can treat a data type polymorphically and use the common `Item` interface to:
*   Get its registered [Name()](/reference/ucalc/item/name).
*   Read or set its [Description()](/reference/ucalc/item/description).
*   Check its properties with [IsProperty()](/reference/ucalc/item/isproperty) (e.g., `IsProperty(ItemIs::DataType)`).
*   [Release()](/reference/ucalc/item/release) a user-defined data type from memory.

### 💡 Comparative Analysis

This concept is similar to reflection in languages like C# or Java.
*   In C#, `typeof(int)` returns a `System.Type` object.
*   In uCalc, [uc.DataTypeOf("Int")](/reference/ucalc/ucalc/datatypeof) returns a `DataType` object, and calling `.Item()` on that object provides access to the unified symbol table representation.

The key difference is that uCalc's `Item` provides a consistent interface for *all* engine symbols, not just types, simplifying introspection logic.

**Examples:**

### Example ID: 533

**Description:** How to retrieve the Item from a DataType to access its name.

**Code:**
```pseudocode
var intType = uc.DataTypeOf(BuiltInType::Integer_32);

// Get the Item representation of the DataType
var itemHandle = intType.@Item();

wl("Data Type Name via Item: ", itemHandle.@Name())
```

**Output:**
```
Data Type Name via Item: int
```

---

### Example ID: 535

**Description:** Internal test to verify behavior when retrieving the Item for a non-existent data type.

**Code:**
```pseudocode
// Attempt to get an invalid DataType
var invalidType = uc.DataTypeOf("NoSuchType");

// Get its Item representation
var invalidItem = invalidType.@Item();

// Check its properties
wl("Item Is Found: ", bool([c]![/c][vb]Not [/vb] invalidItem.IsProperty(ItemIs::NotFound)))
wl("Item Name: '", invalidItem.@Name(), "'")
```

**Output:**
```
Item Is Found: False
Item Name: ''
```

---

---

## MemoryIndex = [int] - ID: 605
/doc/reference/classes/ucalc.datatype/memoryindex-=-[int]/

**Description:** Returns the unique, stable index value that identifies the data type object within the uCalc engine.

**Remarks:**

### ⚙️ MemoryIndex: Stable Object Identifier

The `MemoryIndex` method returns a stable, predictable integer that uniquely identifies a `DataType` object instance within its parent [uCalc](/reference/ucalc/ucalc) engine. This value is primarily used for advanced debugging and diagnostics, allowing you to track the lifecycle of objects.

### 💡 Key Characteristics

*   **Stable & Predictable**: Unlike the internal [Handle](/reference/ucalc/datatype/handle), which can change between application runs, the `MemoryIndex` is assigned sequentially starting from 1. The special `Empty` object for each class is always assigned index 0.
*   **Recycled on Release**: When a `DataType` object is released, its `MemoryIndex` is returned to a pool. The next `DataType` object created will reuse that index. This behavior is crucial for detecting object leaks or verifying that objects are being released as expected.
*   **Instance-Specific**: The index is unique *within a single uCalc instance*. Two different `uCalc` instances will have their own independent sets of `DataType` objects, each with its own `MemoryIndex` sequence.

### ⚖️ Comparative Analysis: `MemoryIndex` vs. Other Identifiers

| Feature | `MemoryIndex` | `Handle` | C# `GetHashCode()` | C++ Pointer Address |
| :--- | :--- | :--- | :--- | :--- |
| **Stability** | **Stable**. Predictable and sequential. | **Volatile**. Changes between application runs. | Unstable. Can change if an object is moved by the GC. | Volatile. Changes on every run. |
| **Uniqueness** | Unique for the object's lifetime. **Recycled** after release. | Guaranteed unique for the object's lifetime. | Not guaranteed to be unique. | Guaranteed unique. |
| **Purpose** | High-level diagnostics and tracking object lifecycles. | Low-level object identification for the C++ core. | Hashing for collections. | Direct memory access. |

The primary advantage of `MemoryIndex` is for building diagnostic tools. You can log the index of an object at creation and verify that the same index is reused after you expect it to have been released, confirming your memory management logic is correct.

**Examples:**

---

## Name = [string] - ID: 125
/doc/reference/classes/ucalc.datatype/name-=-[string]/

**Description:** Retrieves the canonical string name of the data type, such as 'double', 'string', or 'int'.

**Remarks:**

The `Name()` method retrieves the canonical string name of a [DataType](/Reference/uCalc/DataType) object. This name is used for identification, debugging, and can be used in other methods that accept a type name as a string, such as [uc.DataTypeOf(string)](/Reference/uCalc/DataTypeOf).

### 🏷️ Canonical Names vs. Aliases
uCalc's type system includes several convenient aliases for common data types. The `Name()` method will always return the base, or *canonical*, name for the type, even if the [DataType](/Reference/uCalc/DataType) object was retrieved using an alias.

For instance, the following all refer to the same underlying 32-bit integer type, but `Name()` will consistently return "int":
*   [pseudocode]`uc.DataTypeOf("Int")`
*   [pseudocode]`uc.DataTypeOf("Integer")`
*   [pseudocode]`uc.DataTypeOf("Int32")`

This consistency is useful for reliable type checking in your application logic.

### 💡 Comparative Analysis

*   **vs. C# `typeof(T).Name`**: In C#, type names are determined at compile time. While useful, they represent a static language feature. uCalc's [DataType](/Reference/uCalc/DataType) objects are dynamic, runtime entities. Their names are part of a configurable system, providing greater flexibility for scripting and dynamic environments.

*   **vs. C++ `typeid(T).name()`**: The name returned by C++'s `typeid` is implementation-defined and can often be a "mangled" name that isn't user-friendly (e.g., `i` for `int`). uCalc's `Name()` method is guaranteed to return a clean, human-readable string like "int", "double", or "string", which is far better suited for user-facing output and diagnostics.

**Examples:**

### Example ID: 539

**Description:** Retrieves and displays the name of a built-in data type.

**Code:**
```pseudocode
var intType = uc.DataTypeOf(BuiltInType::Integer_32);
wl("The canonical name for Integer_32 is: ", intType.@Name())

var strType = uc.DataTypeOf(BuiltInType::String);
wl("The canonical name for String is: ", strType.@Name())
```

**Output:**
```
The canonical name for Integer_32 is: int
The canonical name for String is: string
```

---

### Example ID: 540

**Description:** Introspects the inferred data types of several variables and prints their names.

**Code:**
```pseudocode
// Define variables where the type is inferred from the initial value
uc.DefineVariable("myNumber = 10.5");
uc.DefineVariable("myText = 'hello'");
uc.DefineVariable("myFlag = true");

// Get the item and then its data type name
var item1 = uc.ItemOf("myNumber");
wl("'myNumber' is of type: ", item1.@DataType().@Name())

var item2 = uc.ItemOf("myText");
wl("'myText' is of type: ", item2.@DataType().@Name())

var item3 = uc.ItemOf("myFlag");
wl("'myFlag' is of type: ", item3.@DataType().@Name())
```

**Output:**
```
'myNumber' is of type: double
'myText' is of type: string
'myFlag' is of type: bool
```

---

### Example ID: 50

**Description:** Displaying the data type name and size of a variable

**Code:**
```pseudocode
var MyVariable = uc.DefineVariable("MyVariable");
wl("MyVariable type: " + MyVariable.@DataType().@Name())
wl("MyVariable size: ", MyVariable.@DataType().@ByteSize())
```

**Output:**
```
MyVariable type: double
MyVariable size: 8
```

---

### Example ID: 13

**Description:** Passing arg ByHandle to retrieve meta data such as arg data type; and AnyType

**Code:**
```pseudocode
[head]
[callback DisplayArgs]
for(int x = 1 to cb.ArgCount())
   wl(cb.ArgItem(x).ValueStr() + "  Type: " + cb.ArgItem(x).@DataType().@Name())
end for
[/callback]
[body]
uc.DefineFunction("DisplayArgs(ByHandle Arg As AnyType ...)", DisplayArgs);
uc.Eval("DisplayArgs(5, 3+2*#i, 'Hello', True, False, Int16(5+4.1))");
```

**Output:**
```
5  Type: double
3+2i  Type: complex
Hello  Type: string
true  Type: bool
false  Type: bool
9  Type: int16
```

---

### Example ID: 17

**Description:** DefineVariable examples

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var MyInt = uc.DefineVariable("MyInt As Int");
var MyStr = uc.DefineVariable("MyStr As String");
uc.DefineVariable("OtherStr = 'string type inferred'");
uc.DefineVariable("MyInt16 = Int16(100/3)"); // type inferred
uc.DefineVariable("MyBool = True"); // type inferred
uc.DefineVariable("MyComplex = 3 + 4*#i"); // type inferred

MyVar.Value(123);
MyInt.ValueInt32(456);
MyStr.ValueStr("This is a test");

wl("MyVar = " + uc.EvalStr("MyVar"))
wl("MyInt = " + uc.EvalStr("MyInt"))
wl("MyStr = " + uc.EvalStr("MyStr"))
wl("OtherStr = " + uc.EvalStr("OtherStr"))
wl("MyInt16 = " + uc.EvalStr("MyInt16"))
wl("MyBool = " + uc.EvalStr("MyBool"))
wl("MyComplex = " + uc.EvalStr("MyComplex"))
wl("---")
wl(MyVar.Value())
wl(MyInt.ValueInt32())
wl(MyStr.ValueStr())
wl("---")
wl(uc.ItemOf("MyVar").@DataType().@Name())
wl(uc.ItemOf("MyInt").@DataType().@Name())
wl(uc.ItemOf("MyStr").@DataType().@Name())
wl(uc.ItemOf("OtherStr").@DataType().@Name())
wl(uc.ItemOf("MyInt16").@DataType().@Name())
wl(uc.ItemOf("MyBool").@DataType().@Name())
wl("---")

var Expression = "x^2 * 10";
var VarX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse(Expression);

w("Expression = ")
wl(Expression)
for (int x = 1 to 10)
   VarX.Value(x); // In C++ you can skip this by passing &x to DefineVariable
   wl("x = " + VarX.ValueStr() + "  Result = " + ParsedExpr.EvaluateStr())
end for

ParsedExpr.Release();
VarX.Release();
```

**Output:**
```
MyVar = 123
MyInt = 456
MyStr = This is a test
OtherStr = string type inferred
MyInt16 = 33
MyBool = true
MyComplex = 3+4i
---
123
456
This is a test
---
double
int
string
string
int16
bool
---
Expression = x^2 * 10
x = 1  Result = 10
x = 2  Result = 40
x = 3  Result = 90
x = 4  Result = 160
x = 5  Result = 250
x = 6  Result = 360
x = 7  Result = 490
x = 8  Result = 640
x = 9  Result = 810
x = 10  Result = 1000
```

---

---

## Release - ID: 126
/doc/reference/classes/ucalc.datatype/release/

**Description:** Unregisters a custom data type and releases its associated resources from the uCalc instance.

**Syntax:** Release()
**Return:** void - This method does not return a value.
**Remarks:**

### 💾 Releasing a Data Type

This method manually removes a custom data type definition from its parent `uCalc` instance. Releasing a data type frees up its associated memory and makes its name available for reuse.

### When to Use `Release`

While not frequently needed, manually releasing a data type is useful in specific scenarios:

*   **Dynamic Environments**: In applications where data types are created and destroyed dynamically, `Release` allows for precise control over the parser's state and memory usage.
*   **Un-shadowing Definitions**: If you define a new data type with the same name as an existing one, the new definition "shadows" the old one. Releasing the new data type will restore the previous definition. See the practical example below.
*   **Resource Management**: For long-running server applications or plugins, explicitly releasing unused definitions can prevent memory bloat over time.

### Automatic vs. Manual Release

It's important to understand uCalc's resource management model. All objects created within a `uCalc` instance (including functions, variables, and data types) are owned by that instance.

*   **Automatic Release**: When you call [uCalc.Release](/ucalc/release) on the parent `uCalc` object, all associated data types are automatically released. This is the most common and safest way to clean up resources.
*   **Manual Release**: Calling [pseudocode]`myDataType.Release()` provides granular control but requires you to manage the object's lifecycle carefully.

This model is analogous to RAII (Resource Acquisition Is Initialization) in C++, where object lifetime is tied to scope. The `uCalc` object acts as the scope for all its definitions.

### ⚠️ Caution

*   **Built-in Types**: Do not attempt to release built-in data types like `String`, `Int`, or `Double`.
*   **In-Use Types**: Releasing a data type that is currently being used by a variable, function return type, or expression can lead to errors or undefined behavior. Ensure that all items referencing the data type are released *before* releasing the data type itself.

**Examples:**

---

## Reset - ID: 128
/doc/reference/classes/ucalc.datatype/reset/

**Description:** Resets a scalar variable to the default value for its data type.

**Syntax:** Reset(POINTER)
**Parameters:**
valuePointer - POINTER - A pointer to the scalar variable's value that should be reset.
**Return:** void - This method does not return a value.
**Remarks:**

### 🎯 Function

Resets a scalar variable to its default value based on its underlying data type. This is an in-place modification, meaning it directly alters the memory where the variable's value is stored.

Default values for common types include:
*   **Numeric (double, int, etc.):** `0`
*   **String:** An empty string (`""`)
*   **Boolean:** `false`
*   **Complex:** `0+0i`

### 🤔 Why Use `DataType.Reset`?

At first glance, this method might seem redundant. After all, you can achieve a similar result with a simple assignment:

```pseudocode
// Using simple assignment
var(double, x) = 123.45;
x = 0;
```

However, [pseudocode]`DataType.Reset` offers a distinct advantage in specific scenarios. It operates directly on the memory address of the value. This is particularly useful for:

1.  **Performance-Critical Loops:** In tight loops where you frequently need to reset a variable, `Reset` can be more efficient as it avoids the overhead associated with reassignment, especially for complex types that might involve memory deallocation and reallocation.
2.  **Low-Level Manipulation:** When interfacing with code that passes data by reference or pointer, this method provides a direct way to clear the underlying data without needing a reference to the `Variable` object itself.

### ⚖️ Comparative Analysis

| Method | Syntax | Mechanism | Use Case |
| :--- | :--- | :--- | :--- |
| **Assignment** | [pseudocode]`MyVar = 0;` | Assigns a new value. May involve memory deallocation/reallocation for complex types. | Everyday, general-purpose variable resets. Simple and readable. |
| **`DataType.Reset`** | [pseudocode]`uc.DataTypeOf("double").Reset(MyVar.ValueAddr());` | Modifies the existing memory in-place to its default state. | High-performance scenarios, low-level memory manipulation, or when you only have a pointer to the value. |

**Examples:**

### Example ID: 88

**Description:** Data type Reset

**Code:**
```pseudocode
var MyDbl = uc.DefineVariable("MyDbl = 123.456");
var MyStr = uc.DefineVariable("MyStr = 'Hello world!'");
var MyCplx = uc.DefineVariable("MyCplx = 3 + 4 * #i");

wl(uc.EvalStr("MyDbl"))
wl(uc.EvalStr("MyStr"))
wl(uc.EvalStr("MyCplx"))

uc.DataTypeOf("double").Reset(MyDbl.ValueAddr());
uc.DataTypeOf("string").Reset(MyStr.ValueAddr()); // empty string ""
uc.DataTypeOf("complex").Reset(MyCplx.ValueAddr());

wl(uc.EvalStr("MyDbl"))
wl(uc.EvalStr("MyStr"))
wl(uc.EvalStr("MyCplx"))


```

**Output:**
```
123.456
Hello world!
3+4i
0

0+0i
```

---

---

## SetScalar - ID: 131
/doc/reference/classes/ucalc.datatype/setscalar/

**Description:** Performs a low-level copy of a scalar value from a source memory address to a destination address.

**Syntax:** SetScalar(POINTER, POINTER)
**Parameters:**
destinationPtr - POINTER - The memory address of the scalar value to be modified.
sourcePtr - POINTER - The memory address of the value to be copied. It must be of the same data type as the destination.
**Return:** void - This method does not return a value.
**Remarks:**

### 💾 Direct Memory Copy: SetScalar

The `SetScalar` method performs a low-level, direct memory copy of a scalar value from a source address to a destination address. It is the uCalc equivalent of C's `memcpy` for single scalar values.

### 🎯 Primary Use Case: Callbacks

The most common use for [pseudocode]`SetScalar` is within callback routines for custom functions and operators, particularly when arguments are passed by reference (`ByRef`). In these scenarios, you receive a pointer to the original variable's data, and `SetScalar` provides the mechanism to modify that data.

### 🤔 How is this different from regular assignment?

In a uCalc script, you would simply write [pseudocode]`MyVar1 = MyVar2;`. However, inside a host application callback (C#, C++, VB), you are working with pointers to uCalc's internal memory. The standard assignment operator (`=`) of the host language cannot modify uCalc's memory directly. `SetScalar` bridges this gap, allowing your host code to manipulate the script's variables.

### ⚠️ Important Considerations

*   **Type Safety:** `SetScalar` performs a raw byte-for-byte copy. It does not perform any type checking or conversion. Copying between pointers of different data types can lead to undefined behavior or corrupted data if their sizes differ.
*   **Strings and Complex Types:** While `SetScalar` works for strings, it's managing uCalc's internal string representation. The copy is handled correctly, including reference counting. For other complex types, ensure you are copying between identical types.

**Examples:**

### Example ID: 90

**Description:** SetScalar

**Code:**
```pseudocode
var MyVar1 = uc.DefineVariable("MyVar1 = 123.456");
var MyVar2 = uc.DefineVariable("MyVar2 = 654.321");
var MyStr1 = uc.DefineVariable("MyStr1 = 'First string'");
var MyStr2 = uc.DefineVariable("MyStr2 = 'Second string'");

uc.DataTypeOf("double").SetScalar(MyVar1.ValueAddr(), MyVar2.ValueAddr());
uc.DataTypeOf("string").SetScalar(MyStr1.ValueAddr(), MyStr2.ValueAddr());

wl(uc.EvalStr("MyVar1")) // Now contains value copied from MyVar2
wl(uc.EvalStr("MyStr1")) // Now contains value copied from MyStr2
```

**Output:**
```
654.321
Second string
```

---

### Example ID: 18

**Description:** DefineVariable; using pointers

**Code:**
```pseudocode
var Int8Var = uc.DefineVariable("x As Int8 = -1");
var Int16Var = uc.DefineVariable("y As Int16 = -1");
var StrVar = uc.DefineVariable("MyStr = 'Hello there'");
wl(uc.EvalStr("x"))
wl(uc.EvalStr("y"))
wl(uc.EvalStr("MyStr"))

var xPtr = uc.DefineVariable("xPtr As Pointer"); // General pointer
var yPtr = uc.DefineVariable("yPtr As Int16u Ptr"); // pointer specific to unsigned Int16
var yPtrB = uc.DefineVariable("yPtrB As Int16 Ptr = AddressOf(y)"); // Using AddressOf
var StrPtr = uc.DefineVariable("StrPtr As String Ptr");
xPtr.ValuePtr(Int8Var.ValueAddr()); // Sets the pointer address
yPtr.ValuePtr(Int16Var.ValueAddr()); // Note: address of signed Int16 going to an unsigned Ptr
StrPtr.ValuePtr(StrVar.ValueAddr());

// Note: for the ints we are now returning unsigned values; so -1 turns into positive numbers
wl(uc.EvalStr("ValueAt(Int8u, xPtr)")) // Type required because it's defined as generar pointer
wl(uc.EvalStr("ValueAt(yPtr)")) // Type name not needed because it's defined as Int16u Ptr
wl(uc.EvalStr("ValueAt(yPtrB)"))
wl(uc.EvalStr("ValueAt(StrPtr)"))

// Iterate through uc.ItemOf(ItemIs.DataType, n).Name()
// to see data type names you can use with ValueAt

var OtherInt = uc.DefineVariable("OtherInt As Int16 = 1234");
uc.DataTypeOf(BuiltInType::Integer_16).SetScalar(Int16Var.ValueAddr(), OtherInt.ValueAddr());

wl(uc.EvalStr("OtherInt"))
wl(uc.EvalStr("ValueAt(yPtrB)"))





```

**Output:**
```
-1
-1
Hello there
255
65535
-1
Hello there
1234
1234
```

---

---

## SwapScalarValues - ID: 132
/doc/reference/classes/ucalc.datatype/swapscalarvalues/

**Description:** Efficiently swaps the values of two uCalc variables of the same underlying data type.

**Syntax:** SwapScalarValues(POINTER, POINTER)
**Parameters:**
pointerA - POINTER - The memory address of the first variable's value, obtained via `Variable.ValueAddr()`.
pointerB - POINTER - The memory address of the second variable's value, obtained via `Variable.ValueAddr()`.
**Return:** void - This method does not return a value.
**Remarks:**

### ⚙️ Functionality
This method performs a highly efficient swap of two variable values. Instead of copying the actual data from one variable to another (which can be slow for large strings or complex objects), it swaps the internal pointers that point to the data. This makes the operation nearly instantaneous regardless of the data size.

To use this method, you must first obtain a `DataType` object corresponding to the type of variables you wish to swap. Both variables must be of the same type.

### 🆚 Comparative Analysis
In most high-level languages, swapping variables is straightforward:

*   **C# (Tuple Deconstruction):** `(a, b) = (b, a);`
*   **Traditional (Temp Variable):** `temp = a; a = b; b = temp;`

The uCalc `SwapScalarValues` method is a lower-level operation. While the syntax is more verbose because it requires getting the `DataType` and value pointers, it provides a direct hook into the engine's memory management. This approach guarantees the most performant swap possible within the uCalc ecosystem, mirroring the efficiency of pointer manipulation in languages like C++.

**Usage Example:**
```pseudocode
// 1. Define variables
var a = uc.DefineVariable("a = 10");
var b = uc.DefineVariable("b = 20");

// 2. Get the DataType for integers
var intType = uc.DataTypeOf("integer");

// 3. Swap using their value addresses
intType.SwapScalarValues(a.ValueAddr(), b.ValueAddr());
```

> **⚠️ Warning:** Both variables involved in the swap *must* be of the same data type associated with the `DataType` object. Attempting to swap values of incompatible types (e.g., an integer with a string) will result in undefined behavior, potentially leading to memory corruption or application instability.

**Examples:**

### Example ID: 91

**Description:** SwapScalarValues

**Code:**
```pseudocode
var MyVar1 = uc.DefineVariable("MyVar1 = 123.456");
var MyVar2 = uc.DefineVariable("MyVar2 = 654.321");
var MyStr1 = uc.DefineVariable("MyStr1 = 'First string'");
var MyStr2 = uc.DefineVariable("MyStr2 = 'Second string'");

wl(uc.EvalStr("MyVar1"))
wl(uc.EvalStr("MyVar2"))
wl(uc.EvalStr("MyStr1"))
wl(uc.EvalStr("MyStr2"))
wl("---")

uc.DataTypeOf("double").SwapScalarValues(MyVar1.ValueAddr(), MyVar2.ValueAddr());
uc.DataTypeOf("string").SwapScalarValues(MyStr1.ValueAddr(), MyStr2.ValueAddr());

wl(uc.EvalStr("MyVar1")) // Values of MyVar1 and MyVar2 are now swapped
wl(uc.EvalStr("MyVar2"))
wl(uc.EvalStr("MyStr1")) // Values of MyStr1 and MyStr2 are now swapped
wl(uc.EvalStr("MyStr2"))
```

**Output:**
```
123.456
654.321
First string
Second string
---
654.321
123.456
Second string
First string
```

---

---

## ToString - ID: 133
/doc/reference/classes/ucalc.datatype/tostring/

---

## ToString(POINTER, bool) - ID: 134
/doc/reference/classes/ucalc.datatype/tostring/tostring-pointer,-bool/

**Description:** Converts a value at a specified memory address to its string representation, optionally applying custom formatting rules.

**Syntax:** ToString(POINTER, bool)
**Parameters:**
valuePtr - POINTER - A pointer to the memory location of the value to be converted.
formatOutput - bool [default = false] - If true, the output string is processed by any applicable formatters defined with [Format](/Reference/uCalc/uCalcBase/Format).
**Return:** string - The string representation of the value at the specified address.
**Remarks:**

### ⚙️ How It Works
This overload of `ToString` is a powerful low-level utility that converts a raw value in memory into a human-readable string. Its behavior is dictated by the [DataType](/Reference/uCalc/uCalcBase/DataType) object it is called on. For example, calling `ToString` on an `Integer_8u` [DataType](/Reference/uCalc/uCalcBase/DataType) will interpret the byte at the given address as an unsigned 8-bit integer and format it accordingly.

This method is primarily used in advanced scenarios, especially within [callbacks](/Reference/uCalc/uCalcBase/Callback/Constructor) where you might receive a value's memory address via [ArgAddr()](/Reference/uCalc/uCalcBase/Callback/ArgAddr) instead of the value itself.

# 🎨 Custom Formatting
The `formatOutput` parameter provides control over whether the result is post-processed by custom formatting rules.
*   **`false` (Default):** Returns the raw, default string representation of the value.
*   **`true`:** The raw string is passed through the formatting pipeline defined by [uCalc.Format](/Reference/uCalc/uCalcBase/Format), allowing for application-wide consistent output for things like currency, date formats, or scientific notation.

# 🆚 Comparative Analysis

### vs. Native `.ToString()` / `std::to_string`
In languages like C# or C++, string conversion is tied to the **compile-time type** of a variable. `myInt.ToString()` knows it's an integer because `myInt` was declared as one.

uCalc's `DataType.ToString(pointer)` is different; it's a form of **dynamic dispatch**. The formatting logic is determined at **runtime** by the `DataType` object you call it on, not by the type of the pointer. This allows you to interpret the same block of memory in different ways, which is impossible with static language features.

```pseudocode
// Assume 'ptr' points to a 4-byte block in memory holding the integer 1000.
var int32Type = uc.DataTypeOf("Int32");

// Interpret the memory as a standard integer
wl(int32Type.ToString(ptr)); // Output: 1000

// If you had a custom Hex type, you could interpret the same memory differently:
// var hexType = uc.DataTypeOf("Hex");
// wl(hexType.ToString(ptr)); // Would output: 3E8
```
This demonstrates a level of runtime introspection and flexibility that goes beyond typical language-level string conversion.

**Examples:**

### Example ID: 16

**Description:** How to handle and retrieve various data types (including pointers) within a callback.

**Code:**
```pseudocode
[head]
[callback MyFunction]
   var uc = cb.@uCalc();
   wl("------ MyFunc ------")

   // Retrieve standard 32-bit and 64-bit integer arguments directly
   wl(cb.ArgInt32(1))
   wl(cb.ArgInt64(2))

   // Retrieve the value of a pointer argument by referencing its exact data type.
   wl(uc.ItemOf("Int8").@DataType().ToString(cb.ArgAddr(3)))

   // The Item object correctly identifies the type before conversion
   wl(uc.ItemOf("Int").@DataType().ToString(cb.ArgPtr(4)))
[/callback]

[callback MyFunction2]
   var uc = cb.@uCalc();
   wl("------ MyFunc2 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_8).ToString(cb.ArgPtr(1)))
[/callback]

[callback MyFunction3]
   var uc = cb.@uCalc();
   wl("------ MyFunc3 ------")
   wl(uc.DataTypeOf(BuiltInType::Integer_16).ToString(cb.ArgPtr(1)))
[/callback]
[body]
uc.DefineVariable("x As Int = 123"); // Int32
uc.DefineVariable("xPtr As Int Ptr = AddressOf(x)");
uc.DefineFunction("MyFunc(a As Int32, b As Int64, c As Byte, d As Int Ptr)", MyFunction);
uc.Eval("MyFunc(x*10, 1+1, 255, xPtr)");

uc.DefineVariable("x2 As Int8 = -123");
uc.DefineVariable("xPtr2 As Int8 Ptr = AddressOf(x2)");
uc.DefineFunction("MyFunc2(d As Int8 Ptr)", MyFunction2);
uc.Eval("MyFunc2(xPtr2)");

uc.DefineVariable("x3 As Int16 = 1234");
uc.DefineVariable("xPtr3 As Int16 Ptr = AddressOf(x3)");
uc.DefineFunction("MyFunc3(d As Int16 Ptr)", MyFunction3);
uc.Eval("MyFunc3(xPtr3)");
```

**Output:**
```
------ MyFunc ------
1230
2
-1
123
------ MyFunc2 ------
-123
------ MyFunc3 ------
1234
```

---

---

## ToString(string) - ID: 135
/doc/reference/classes/ucalc.datatype/tostring/tostring-string/

**Description:** Parses and converts an input string into a new string, formatted according to the rules of the specific data type.

**Syntax:** ToString(string)
**Parameters:**
valueString - string - The input string to be parsed and converted.
**Return:** string - The resulting string after parsing the input and reformatting it based on the data type's rules.
**Remarks:**

The `ToString` method is a powerful, type-aware parsing utility. Unlike a typical `ToString` function that serializes an object's current state, this method takes an external string and interprets it according to the rules of the [DataType](/Reference/uCalc/DataType) object it is called on.

This is particularly useful for data normalization and validation, as it can convert a single string representation into the canonical format for a given type.

For example, when called on an unsigned 8-bit integer type, it correctly handles overflow wrapping:
```pseudocode
// The Int8u type interprets -1 as its max value (255)
var dt = uc.DataTypeOf(BuiltInType::Integer_8u);
wl(dt.ToString("-1")); // Output: 255
```

### `ToString` vs. `EvalStr`

It is crucial to distinguish this method from [EvalStr](/Reference/uCalc/EvalStr):
*   `DataType.ToString(string)`: Parses a single **literal value**. It does not evaluate expressions. For example, [pseudocode]`uc.DataTypeOf("Int").ToString("1+1")` would likely fail to parse "1+1" as a valid integer and return "0".
*   `uc.EvalStr(string)`: Parses and evaluates a full **expression**. For example, [pseudocode]`uc.EvalStr("1+1")` returns "2".

### ⚖️ Comparative Analysis

In languages like C#, parsing is a static operation tied to a specific type (e.g., `int.Parse()`, `bool.Parse()`). This requires compile-time knowledge of the target type.

uCalc's approach is dynamic. You can hold a `DataType` object in a variable and call `ToString` on it without knowing at compile time which specific type it represents. This enables the creation of generic, powerful data validation and conversion routines that can be configured at runtime.

See also: [ToString(pointer)](/Reference/uCalc/DataType/ToString), the overload which converts a value from a memory address.

**Examples:**

### Example ID: 92

**Description:** Using ToString to convert a value to a string

**Code:**
```pseudocode
wl(uc.DataTypeOf(BuiltInType::Integer_8).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Integer_8u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Integer_16u).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::Boolean).ToString("-1"))
wl(uc.DataTypeOf(BuiltInType::String).ToString("-1"))
```

**Output:**
```
-1
255
65535
true
-1
```

---

---

## uCalc = [uCalc] - ID: 648
/doc/reference/classes/ucalc.datatype/ucalc-=-[ucalc]/

**Description:** Retrieves the parent uCalc instance that owns and manages this data type definition.

**Remarks:**

This method returns the parent [uCalc](/reference/ucalcbase/ucalc) instance to which the current [DataType](/reference/ucalcbase/datatype) object belongs.

### 🎯 Core Concept: Instance-Specific Types

In uCalc, every component—including variables, functions, and data types—exists within the context of a specific `uCalc` engine instance. This architecture is fundamental to creating isolated, sandboxed environments. For example, the `String` data type in `uc1` can have different properties or formatters than the `String` data type in `uc2`.

The `DataType.uCalc()` method provides the crucial link back to this parent environment. If you have a reference to a `DataType` object, you can use this method to access the full scope of its owner, allowing you to:

*   Evaluate expressions within that specific context.
*   Define new variables of that type.
*   Look up other items (functions, operators) that belong to the same instance.

### 💡 Comparative Analysis

*   **vs. Native .NET/C# `Type` Objects**: In .NET, a `Type` object retrieved via `typeof(int)` or `myVar.GetType()` is global to the AppDomain. It has no concept of an "owner" instance. uCalc's model is different: its data types are instance-specific. This allows for powerful customization on a per-instance basis, and `DataType.uCalc()` is the mechanism to navigate from a type definition back to its specific execution environment.

*   **vs. Other Expression Engines**: Simpler evaluators often have a single, global type system. uCalc's instance-based approach provides superior encapsulation and is essential for applications that need to run multiple, independent calculation environments simultaneously (e.g., in a multi-threaded server or a plugin-based architecture).

**Examples:**

### Example ID: 560

**Description:** How to retrieve the parent uCalc instance from a DataType object.

**Code:**
```pseudocode
uc.@Description("Main uCalc Instance");

// Get the DataType object for Int32
var intType = uc.DataTypeOf(BuiltInType::Integer_32);

// Use the .uCalc() method to get back to the parent instance and read its description.
wl(intType.@uCalc().@Description())
```

**Output:**
```
Main uCalc Instance
```

---

### Example ID: 562

**Description:** Internal test to confirm instance isolation by proving a DataType is strictly bound to its parent uCalc instance.

**Code:**
```pseudocode
// Create two completely separate uCalc instances.
New(uCalc, uc1)
uc1.DefineVariable("x = 100");

New(uCalc, uc2)
uc2.DefineVariable("x = 200");

// Get the DataType for 'Int' from the *first* instance.
var intType_from_uc1 = uc1.DataTypeOf("Int");

// Use the .uCalc() method to get the parent instance.
// This should be uc1, so evaluating 'x' should yield 100.
var parent = intType_from_uc1.@uCalc();
wl("Parent of intType_from_uc1 evaluates 'x' to: ", parent.Eval("x"))

// Get the DataType for 'Int' from the *second* instance.
var intType_from_uc2 = uc2.DataTypeOf("Int");

// This should be uc2, so evaluating 'x' should yield 200.
parent = intType_from_uc2.@uCalc();
wl("Parent of intType_from_uc2 evaluates 'x' to: ", parent.Eval("x"))
```

**Output:**
```
Parent of intType_from_uc1 evaluates 'x' to: 100
Parent of intType_from_uc2 evaluates 'x' to: 200
```

---

---

## uCalc.DataTypesAccessor - ID: 855
/doc/reference/classes/ucalc.datatypesaccessor/

**Description:** Data type accessor

---

## Introduction - ID: 961
/doc/reference/classes/ucalc.datatypesaccessor/introduction/

**Description:** Provides access to the collection of all data types registered within a uCalc instance.

**Remarks:**

# 🗂️ The DataTypesAccessor Class

The `DataTypesAccessor` class is a read-only collection that provides access to all [DataType](/Reference/uCalcBase/DataType/Constructor) definitions registered within a specific [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance. It is the primary tool for introspecting the engine's type system at runtime.

You do not create an instance of this class directly. Instead, you retrieve it from the [uCalc.DataTypes](/Reference/uCalcBase/uCalc/DataTypes) property.

---

## ⚙️ Usage Patterns

The `DataTypesAccessor` behaves like a standard collection and supports two main access patterns:

### 1. Iteration (Recommended)
The most common way to use this class is to iterate through it with a `foreach` loop to inspect every available data type.

```pseudocode
wl("Available Data Types:")
foreach(var dt in uc.@DataTypes())
   wl("- ", dt.@Name(), " (Size: ", dt.@ByteSize(), " bytes)")
end foreach
```

### 2. Indexed Access
You can also retrieve a specific `DataType` by its zero-based index in the collection.

```pseudocode
var types = uc.@DataTypes();
if (bool(types.Count() > 0))
    var firstType = types[0];
    wl("The first registered data type is: ", firstType.@Name())
end if
```

---

## Class Members

| Member | Description |
| :--- | :--- |
| `Count` | Gets the total number of data types in the collection. |
| `Indexer[]` | Retrieves a [DataType](/Reference/uCalcBase/DataType/Constructor) object by its zero-based index. |

---

## 💡 Why uCalc? (Comparative Analysis)

`DataTypesAccessor` provides functionality similar to reflection APIs in other languages, but it is tailored specifically for the uCalc engine.

*   **vs. .NET/Java Reflection**: Reflection is a general-purpose system for inspecting assemblies and compile-time types. `DataTypesAccessor` is a much simpler, higher-level API focused exclusively on the types defined *within the uCalc engine's dynamic runtime environment*. It's a specialized introspection tool, not a full reflection system.

*   **vs. C++ RTTI**: C++'s `typeid` provides runtime type information but is limited. uCalc's system allows for rich introspection of a dynamic collection of types, including custom ones defined at runtime, which is not possible with standard RTTI.

**Examples:**

### Example ID: 801

**Description:** Lists the names of all standard data types registered in the current uCalc instance.

**Code:**
```pseudocode
foreach(var Item in uc.@DataTypes())
   wl(Item.@Name())
end foreach
```

**Output:**
```
anytype
bool
bool
int8u
complex
double
single
int
int16
int16u
int
int32u
int64
int64u
int8
int8u
int
omnitype
pointer
sametypeas
single
size_t
string
void
```

---

---

## Indexer[] - ID: 938
/doc/reference/classes/ucalc.datatypesaccessor/indexer[]/

**Syntax:** Indexer[]()
**Return:**  - 
**Remarks:**

Returns the nth Data type

---

## Enumerator - ID: 940
/doc/reference/classes/ucalc.datatypesaccessor/enumerator/

**Syntax:** Enumerator()
**Return:**  - 
---

## uCalc.Expression - ID: 136
/doc/reference/classes/ucalc.expression/

**Description:** Class for evaluating an already parsed expression or executing parsed code

---

## Introduction - ID: 962
/doc/reference/classes/ucalc.expression/introduction/

**Description:** An overview of the compiled expression object, the core component for high-performance, repeated evaluation.

**Remarks:**

# ⚡️ The Expression Class: A Compiled Formula

The `Expression` class represents a pre-parsed, compiled, and reusable formula. It is the cornerstone of uCalc's high-performance evaluation model, allowing you to separate the computationally expensive task of parsing a string from the lightning-fast task of executing it.

An `Expression` object is created by calling [uCalc.Parse](/Reference/uCalcBase/uCalc/Parse) or by using the [Expression constructor](/Reference/uCalcBase/Expression/Constructor). Once created, it can be evaluated repeatedly with different variable values, achieving performance that approaches native compiled code.

---

## 🚀 The "Parse-Once, Evaluate-Many" Pattern

The primary purpose of the `Expression` object is to enable the "Parse-Once, Evaluate-Many" pattern, which is critical for performance in loops or other repetitive calculations.

*   **The Inefficient Way**: Calling [uCalc.EvalStr](/Reference/uCalcBase/uCalc/EvalStr) inside a loop forces the engine to re-parse the same string on every iteration.
*   **The uCalc Way**: Parse the string *once* into an `Expression` object before the loop, and call a method like [Evaluate](/Reference/uCalcBase/Expression/Evaluate) or [Execute](/Reference/uCalcBase/Expression/Execute) on that object inside the loop.

For a detailed guide, see the [Optimizing Performance](/Tutorials/Getting-Started:-The-Expression-Parser/Optimizing-Performance) tutorial.

---

## 🔗 Context and Lifetime

*   **Evaluation Context**: Every `Expression` is intrinsically linked to the parent [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance that created it. This parent instance provides the context of variables, functions, and operators needed for evaluation. You can retrieve this parent using the [uCalc](/Reference/uCalcBase/Expression/uCalc) property.
*   **Memory Management**: An `Expression` object holds native resources and must be released to prevent memory leaks. This is best done using language-idiomatic scoping mechanisms like `using` in C# or RAII via the [Owned](/Reference/uCalcBase/Expression/Owned) method in C++. For manual control, you can use the [Release](/Reference/uCalcBase/Expression/Release) method.

---

## Class Members

Below is a list of members for the `Expression` class.

### Core Evaluation Methods
| Member | Description |
| :--- | :--- |
| [`Evaluate`](/Reference/uCalcBase/Expression/Evaluate) | Evaluates a pre-parsed expression, returning a numeric result. This is the high-performance second step in the parse-evaluate workflow. |
| [`EvaluateBool`](/Reference/uCalcBase/Expression/EvaluateBool) | Evaluates a pre-parsed boolean expression, returning the native true or false result efficiently. |
| [`EvaluateDbl`](/Reference/uCalcBase/Expression/EvaluateDbl) | Rapidly evaluates a pre-parsed expression, optimized specifically for double-precision floating-point results. |
| [`EvaluateInt32`](/Reference/uCalcBase/Expression/EvaluateInt32) | Evaluates a pre-parsed expression and returns the result as a 32-bit integer. |
| [`EvaluateStr`](/Reference/uCalcBase/Expression/EvaluateStr) | Evaluates a pre-parsed expression and returns the result of any data type as a string. |
| [`EvaluateVoid`](/Reference/uCalcBase/Expression/EvaluateVoid) | Evaluates the expression and returns a native pointer to the result's memory location. |
| [`Execute`](/Reference/uCalcBase/Expression/Execute) | Executes a pre-parsed expression without returning a value, optimized for operations valued for their side effects rather than their result. |

### Construction & Management
| Member | Description |
| :--- | :--- |
| [`Constructor`](/Reference/uCalcBase/Expression/Constructor) | Creates a new, compiled expression object from a string, ready for repeated evaluation. |
| [`Parse`](/Reference/uCalcBase/Expression/Parse) | Parses a new expression. |
| [`Clone`](/Reference/uCalcBase/Expression/Clone) | Creates an identical, yet completely independent, copy of a parsed expression object. |
| [`Release`](/Reference/uCalcBase/Expression/Release) | Frees the memory and resources associated with a compiled expression object, making it invalid for future use. |
| [`Owned`](/Reference/uCalcBase/Expression/Owned) | Manages automatic resource release for an object, enabling RAII-style lifetime management primarily for C++. |

### Introspection & Metadata
| Member | Description |
| :--- | :--- |
| [`DataType`](/Reference/uCalcBase/Expression/DataType) | Retrieves the resulting data type of a parsed expression without needing to evaluate it. |
| [`uCalc`](/Reference/uCalcBase/Expression/uCalc) | Returns the parent uCalc instance that owns this expression, providing access to its evaluation context. |
| [`Handle`](/Reference/uCalcBase/Expression/Handle) | Returns the internal handle of the Expression object, a unique identifier used by the library for low-level operations. |
| [`MemoryIndex`](/Reference/uCalcBase/Expression/MemoryIndex) | Returns a stable, predictable integer index for the expression object, useful for diagnostics and tracking object lifetime. |

**Examples:**

### Example ID: 563

**Description:** Demonstrates the basic creation and immediate evaluation of an expression object.

**Code:**
```pseudocode
// Basic construction and evaluation using the default uCalc instance.
NewUsing(uCalc::Expression, MyExpr("10 * (2 + 3)"))
wl(MyExpr.Evaluate())
End Using
```

**Output:**
```
50
```

---

### Example ID: 31

**Description:** Illustrates the core relationship between the uCalc engine, an Item (variable), and a compiled Expression.

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");
var Expression = "x^2 * 10"; // Replace this with your expression

wl("--- Efficient: Parse() once, then Evaluate() in a loop ---")
var ParsedExpr = uc.Parse(Expression);
for(double x = 1 to 10)
   VariableX.Value(x);
   wl(ParsedExpr.Evaluate())
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
--- Efficient: Parse() once, then Evaluate() in a loop ---
10
40
90
160
250
360
490
640
810
1000
```

---

---

## (Constructor) - ID: 651
/doc/reference/classes/ucalc.expression/-constructor/

**Description:** Creates a new, compiled expression object from a string, ready for repeated evaluation.

**Remarks:**

The `Expression` constructor is one of two primary ways to create a compiled expression object, the other being the [uCalc.Parse](/Reference/uCalc/uCalc/Parse) method. An `Expression` object represents a pre-parsed, optimized form of a string formula, designed for efficient, repeated evaluation.

### Key Distinction: `Constructor` vs. `uCalc.Parse()`

The fundamental difference lies in the **context** used for parsing:

*   **[Pseudocode]`New(uCalc::Expression, ...)`**: When you use the constructor, the expression is parsed within the context of the **default `uCalc` instance** ([uCalc.Default](/Reference/uCalc/uCalc/Default)). Any variables, functions, or operators defined in the default instance are available.
*   **`uc.Parse(...)`**: This method parses the expression within the context of the **specific `uCalc` instance (`uc`)** it was called from. This is the preferred method when working with multiple, isolated parser environments.

### Constructor Overloads

1.  **[Pseudocode]`New(uCalc::Expression, MyExpr(expression [, returnType]))`**
    Creates an expression using the default `uCalc` instance. This is the most common constructor.
    *   `expression`: The string containing the formula to parse.
    *   `returnType`: An optional [DataType](/Reference/uCalc/DataType) object specifying the expression's expected result type.

2.  **[Pseudocode]`New(uCalc::Expression, MyExpr(ucalcInstance, expression [, returnType]))`**
    Creates an expression using a specific `uCalc` instance for context, bypassing the default instance.

3.  **[Pseudocode]`New(uCalc::Expression, MyExpr())`**
    Creates an empty `Expression` object. You must call the [Parse](/Reference/uCalc/Expression/Parse) method on this object later to associate it with a formula.

4.  **[Pseudocode]`New(uCalc::Expression, MyExpr(uCalc::Expression::Empty))`**
    Creates an empty placeholder handle that does not allocate significant resources. It can be assigned a real instance later.

### Lifetime Management & Auto-Release

An `Expression` object holds compiled resources and should be released when no longer needed to free memory. This can be done manually with [Release()](/Reference/uCalc/Expression/Release) or automatically through language-specific scoping mechanisms:

*   **C#**: Use the `using` statement: `using var myExpr = new uCalc.Expression("1+1");`
*   **C++**: Set the last arg to true: `uCalc::Expression myExpr("1+1", true);`

### Comparative Analysis

*   **vs. `Eval()`/`EvalStr()`**: Methods like [EvalStr](/Reference/uCalc/uCalc/EvalStr) are convenient for one-off calculations but are inefficient in loops because they parse the string on every call. The two-step process of creating an `Expression` object once and then calling [Evaluate()](/Reference/uCalc/Expression/Evaluate) repeatedly is significantly faster for performance-critical tasks.

*   **vs. Other Libraries**: While many libraries provide an `eval` function, uCalc's `Expression` object is deeply integrated into its parent `uCalc` instance. This means it can leverage custom functions, operators, variables, and even pre-processing transformers, offering a level of flexibility beyond simple mathematical evaluators.

**Examples:**

### Example ID: 563

**Description:** Demonstrates the basic creation and immediate evaluation of an expression object.

**Code:**
```pseudocode
// Basic construction and evaluation using the default uCalc instance.
NewUsing(uCalc::Expression, MyExpr("10 * (2 + 3)"))
wl(MyExpr.Evaluate())
End Using
```

**Output:**
```
50
```

---

### Example ID: 564

**Description:** Shows how the constructor's context (default vs. specific instance) affects variable resolution during parsing.

**Code:**
```pseudocode
// Set up two different uCalc contexts with the same variable name 'x'.
uCalc::@DefaultInstance().DefineVariable("x = 1.2");
uc.DefineVariable("x = 10");

wl("--- Testing Expression Contexts ---")

// 1. Expression created in the *default* context uses x = 1.2
NewUsing(uCalc::Expression, exprDefault("x + 5"))
wl("Default context (x=1.2): ", exprDefault.Evaluate())

// 2. Expression created in a *specific* context ('uc') uses x = 10
NewUsing(uCalc::Expression, exprSpecific(uc, "x + 5"))
wl("Specific context (x=10):  ", exprSpecific.Evaluate())

// 3. Create empty, then parse later (uses default context for the Parse call)
NewUsing(uCalc::Expression, exprEmpty)
exprEmpty.Parse("x * 10");
wl("Empty then parsed (x=1.2):", exprEmpty.Evaluate())
End Using
End Using
End Using
```

**Output:**
```
--- Testing Expression Contexts ---
Default context (x=1.2): 6.2
Specific context (x=10):  15
Empty then parsed (x=1.2):12
```

---

### Example ID: 94

**Description:** Expression constructor

**Code:**
```pseudocode
uCalc::@DefaultInstance().DefineVariable("x = 1.2");
uc.DefineVariable("x = 3.2");

New(uCalc::Expression, MyExprA)
New(uCalc::Expression, MyExprB("x+4.25"))
New(uCalc::Expression, MyExprC("x+4.25", uCalc::@DefaultInstance().DataTypeOf("int")))
New(uCalc::Expression, MyExprD(uc, "x+4.25"))

MyExprA.Parse("x*100");

wl(MyExprA.Evaluate())
wl(MyExprB.Evaluate())
wl(MyExprC.Evaluate())
wl(MyExprD.Evaluate())

// Release expressions when no longer needed (see other example for auto-release)
MyExprA.Release();
MyExprB.Release();
MyExprC.Release();
MyExprD.Release();
```

**Output:**
```
120
5.45
5
7.45
```

---

---

## Clone - ID: 503
/doc/reference/classes/ucalc.expression/clone/

**Description:** Creates an identical, yet completely independent, copy of a parsed expression object.

**Syntax:** Clone()
**Return:** Expression - A new, independent `Expression` object that is a complete replica of the original.
**Remarks:**

The `Clone` method creates a deep, independent copy of a parsed `Expression` object. This is a highly efficient operation, as it duplicates the internal Abstract Syntax Tree (AST) directly in memory, which is significantly faster than re-parsing the original expression string.

### 🎯 Core Use Cases

Cloning a parsed expression is essential for several advanced scenarios:

*   **Performance Optimization**: The most common use case. Parsing a complex expression string can be computationally expensive. If you need to evaluate the same logic repeatedly (e.g., inside a loop or across different parts of your application), you should parse it once with [uCalc.Parse](/reference/ucalc/parse), and then `Clone` the resulting `Expression` object as needed. This avoids the high cost of repeated parsing.


*   **Preserving an Original Template**: You can treat a parsed expression as a master template. If you need to experiment with it (e.g., with potential future APIs that might modify the expression tree), you can work on a clone, leaving the original intact.

### `Expression.Clone()` vs. `uCalc.Clone()`

It is important to understand the distinction between cloning an expression and cloning the entire uCalc engine:

*   `Expression.Clone()`: Copies a **single parsed expression**. The clone still relies on the original `uCalc` instance to resolve variables and functions during evaluation.
*   [uCalc.Clone()](/reference/ucalc/clone): Copies the **entire engine**, including all variables, functions, operators, and settings. The cloned engine is a fully isolated sandbox.

### 💡 Best Practices for Memory Management

A cloned `Expression` object, like one created with `Parse`, holds onto memory and should be released when no longer needed. This can be done explicitly with [Release()](/reference/expression/release) or automatically using language-specific scoping constructs like `using` in C# or [Owned](/ucalc/expression/owned) in C++, as shown in the examples.

**Examples:**

---

## DataType = [DataType] - ID: 137
/doc/reference/classes/ucalc.expression/datatype-=-[datatype]/

**Description:** Retrieves the resulting data type of a parsed expression without needing to evaluate it.

**Remarks:**

### 🎯 Retrieving Expression Types

The `DataType` method is an introspection tool that returns the resulting [DataType](/reference/ucalc/datatype) of a parsed expression **without actually evaluating it**. This allows you to inspect the type of an expression *before* execution, enabling powerful features like static analysis, type validation, and conditional logic based on the expected output.

### ⚙️ How Type is Determined

When an expression is parsed, its final return type is determined by a clear hierarchy:

1.  **Explicit `ReturnType`**: If a `DataType` was provided in the [Parse()](/reference/ucalc/parse) call (e.g., [pseudocode]`uc.Parse("1+2", uc.DataTypeOf("String"))`), that type is used.
2.  **Inference from Expression**: uCalc analyzes the last operation in the expression. The return type of that function or operator becomes the return type of the entire expression. For example:
    *   `1 > 2` results in `Boolean`.
    *   `'a' + 'b'` results in `String`.
    *   `1 + 2 * #i` results in `Complex`.
    *   `1.5 * 2` results in `Double`.
3.  **Fallback to Default**: If the type cannot be inferred (e.g., a variable-only expression without an explicit type), the engine uses the instance's [DefaultDataType](/reference/ucalc/defaultdatatype), which is `Double` by default.

### 🤔 Why is this useful? (Comparative Analysis)

In statically typed languages like C#, `typeof(int)` gets a type at compile time, and `myObject.GetType()` gets an object's type at runtime *after* it has been created. uCalc's `DataType` method offers a different paradigm: it determines the type of a potential result from its **unevaluated definition**.

*   **Without uCalc**: You would have to parse the string yourself or evaluate it and then check the type of the result, which could be slow or trigger unwanted errors (like division by zero).

*   **With uCalc**: You can safely inspect the type first. This is crucial for:
    *   **Building a typed scripting language**: A host application can validate that a user's script will return a `Boolean` for an `if` condition before running it.
    *   **Dynamic UI**: A report generator can check if an expression returns a `String` or a `Number` and choose the appropriate display control (e.g., a label vs. a chart).
    *   **Preventing runtime errors**: Check the types of arguments being passed to a function *before* calling it.

**Examples:**

### Example ID: 41

**Description:** Displaying the data type of a parsed expression

**Code:**
```pseudocode
wl(uc.Parse(" 3 + 6 * 10 ").@DataType().@Name())
wl(uc.Parse(" 'This ' + 'is a string' ").@DataType().@Name())
wl(uc.Parse(" 2 + 8 * #i / 2").@DataType().@Name())
wl(uc.Parse(" 10 + 2 > 3").@DataType().@Name())
```

**Output:**
```
double
string
complex
bool
```

---

---

## Evaluate - ID: 138
/doc/reference/classes/ucalc.expression/evaluate/

**Description:** Evaluates a pre-parsed expression, returning a numeric result. This is the high-performance second step in the parse-evaluate workflow.

**Syntax:** Evaluate()
**Return:** double - The double-precision numeric result of the evaluated expression.
**Remarks:**

### 🚀 High-Performance Evaluation
The `Evaluate` method is the high-performance second step in uCalc's two-stage evaluation process. It executes a pre-compiled [Expression](/reference/ucalc/expression) object, making it exceptionally fast for repeated calculations.

### The Parse-Once, Evaluate-Many Pattern
For optimal performance, especially in loops or performance-critical scenarios, you should always follow this pattern:
1.  **Parse Once**: Call [uCalc.Parse()](/reference/ucalc/parse) outside your loop to convert the string expression into a compiled, reusable `Expression` object.
2.  **Evaluate Many**: Call `.Evaluate()` on that object inside your loop.

This avoids the expensive overhead of re-parsing the same string on every iteration.

```pseudocode
New(uCalc, uc)
// Define the variable to be used in the expression.
var variableX = uc.DefineVariable("x");

// 1. Parse the expression once, outside the loop.
var parsedExpr = uc.Parse("x * 2");
// or var parsedExr = new uCalc.Expression(uc, "x * 2");

// 2. Evaluate it many times inside the loop with changing variables.
for (var i = 1 to 5)
    VariableX.Value(i);
    wl(parsedExpr.Evaluate()); // Extremely fast
end for
[vb]End Using[/vb]
```

### ⚙️ Data Type Handling
This method is optimized for numeric results and always returns a `double`. It intelligently handles various input types:
*   If the expression's result is a `double`, it is returned directly.
*   If the result is another numeric type (e.g., `Int32`, `Single`, `Boolean`), it is automatically and safely converted to a `double`.
*   If the expression returns a non-numeric type (like a `String` or `Complex` number), the return value will be meaningless. For these cases, use [EvaluateStr()](/reference/ucalc/expression/evaluatestr) instead.

### 🆚 Comparative Analysis: Choosing the Right Evaluation Method
uCalc provides several ways to evaluate expressions. Choose the one that best fits your use case.

| Method | Return Type | Use Case | Performance |
| :--- | :--- | :--- | :--- |
| **[Expression.EvaluateDbl()](/ucalc/expresion/evaluatedbl)** | `double` | **Best for loops**. High-speed numeric calculations on a pre-parsed expression. | ⭐⭐⭐⭐⭐ |
| **`Expression.Evaluate()`** | `double` | **Best for loops**. High-speed numeric calculations on a pre-parsed expression. (may convert from another numeric type to Double) | ⭐⭐⭐⭐ |
| [Expression.EvaluateStr()](/reference/ucalc/expression/evaluatestr) | `string` | High-speed evaluation for **any data type** (including strings) on a pre-parsed expression. | ⭐⭐⭐ |
| [uCalc.Eval()](/reference/ucalc/eval) | `double` | **Convenience**. One-off numeric calculations where the expression is not reused. | ⭐⭐ |
| [uCalc.EvalStr()](/reference/ucalc/evalstr) | `string` | **Convenience**. One-off calculations for any data type, especially for displaying user output. | ⭐ |

### Why uCalc?
In many environments, evaluating expressions in a loop requires sub-optimal solutions.
*   **Native Code (e.g., `DataTable.Compute` in .NET)**: These solutions are often slow, lack features (like custom functions), and re-parse the expression on every call, making them unsuitable for performance-critical loops.
*   **Interpreted Languages (e.g., Python `eval`)**: While flexible, these also parse on each call and carry the overhead of a full scripting engine.

uCalc's `Parse` + `Evaluate` model provides the best of both worlds: the flexibility of runtime expressions combined with performance that approaches compiled code, because the expensive parsing work is done only once.

**Examples:**

### Example ID: 573

**Description:** A simple demonstration of parsing an expression once and then evaluating it.

**Code:**
```pseudocode
// 1. Parse the expression into a reusable object.
var parsedExpr = uc.Parse("100 / 4");

// 2. Evaluate the pre-parsed object.
wl("Result: ", parsedExpr.Evaluate())
```

**Output:**
```
Result: 25
```

---

### Example ID: 574

**Description:** Using the parse-evaluate pattern for high-performance calculations in a loop with a changing variable.

**Code:**
```pseudocode
// Define a variable 'x' that will be updated in the loop.
var variableX = uc.DefineVariable("x");

// Parse the expression just once before the loop begins.
var parsedExpr = uc.Parse("x^2 * 10");

wl("Evaluating 'x^2 * 10' for x = 1 to 5:")
for(double x = 1 to 5)
   variableX.Value(x);
   // Evaluate is very fast as the parsing work is already done.
   wl("x = ", x, ", Result = ", parsedExpr.Evaluate())
end for
```

**Output:**
```
Evaluating 'x^2 * 10' for x = 1 to 5:
x = 1, Result = 10
x = 2, Result = 40
x = 3, Result = 90
x = 4, Result = 160
x = 5, Result = 250
```

---

### Example ID: 1460

**Description:** Using the parse-evaluate pattern for high-performance calculations in a loop with a changing variable w/ stopwatch.

**Code:**
```pseudocode
var variableX = uc.DefineVariable("x");
var userExpression = "x * 2 + 5";
var Total = 0.0;
var UpperBound = 1000000; // One million

// Parse the expression just once before the loop begins.
var parsedExpr = uc.Parse(userExpression);

[NotCpp]var stopwatch = System.Diagnostics.Stopwatch.StartNew();[/NotCpp]
for(double x = 1 to UpperBound)
   variableX.Value(x);
   Total = Total + parsedExpr.Evaluate();
end for
[NotCpp]stopwatch.Stop();
//Uncomment the following line to reveal the actual speed:
//Console.WriteLine($"Elapsed Milliseconds: {stopwatch.ElapsedMilliseconds} ms");
[/NotCpp]
w("Sum(1, ", UpperBound, ", ", userExpression, ") = ", [cpp](long long)[/cpp]Total)
```

**Output:**
```
Sum(1, 1000000, x * 2 + 5) = 1000006000000
```

---

### Example ID: 31

**Description:** Illustrates the core relationship between the uCalc engine, an Item (variable), and a compiled Expression.

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");
var Expression = "x^2 * 10"; // Replace this with your expression

wl("--- Efficient: Parse() once, then Evaluate() in a loop ---")
var ParsedExpr = uc.Parse(Expression);
for(double x = 1 to 10)
   VariableX.Value(x);
   wl(ParsedExpr.Evaluate())
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
--- Efficient: Parse() once, then Evaluate() in a loop ---
10
40
90
160
250
360
490
640
810
1000
```

---

### Example ID: 96

**Description:** Evaluate() auto-conversion

**Code:**
```pseudocode
// The int return value type in MyExprB is converted to
// Double with .Evaluate(), but not with .EvaluateDbl()
var MyExprA = uc.Parse("3.2 + 5.2");
var MyExprB = uc.Parse("int(3.2 + 5.2)");

wl(MyExprA.Evaluate())
wl(bool(MyExprA.EvaluateDbl() == 8.4))
wl(MyExprB.Evaluate())
wl(bool(MyExprB.EvaluateDbl() == 8))
```

**Output:**
```
8.4
True
8
False
```

---

### Example ID: 1192

**Description:** A minimal example demonstrating the basic 'Parse once, Evaluate many' pattern.

**Code:**
```pseudocode
// 1. Parse the expression string once to create a reusable object.
//var expr = uc.Parse("5 * 10");
NewUsing(uCalc::Expression, expr("5 * 10"))

// 2. Evaluate the pre-parsed object as many times as needed.
wl(expr.Evaluate())
wl(expr.Evaluate())

End Using // The expression object is automatically released here.
```

**Output:**
```
50
50
```

---

### Example ID: 14

**Description:** Passing arg ByExpr (delayed lazy eval) and ByHandle

**Code:**
```pseudocode
[head]
[callback MySum]
   var Total = 0.0;
   var Expr = cb.ArgExpr(1);
   var Start = cb.Arg(2);
   var Finish = cb.Arg(3);
   var Variable = cb.ArgItem(4);

   for(double x = Start to Finish)
      Variable.Value(x);
      Total += Expr.Evaluate();
   end for
   cb.Return(Total);
[/callback]
[body]
uc.DefineVariable("x");
uc.DefineFunction("Sum(ByExpr Expr, Start, Finish, ByHandle Var)", MySum);
wl(uc.Eval("Sum(x ^ 2, 1, 10, x)"))

```

**Output:**
```
385
```

---

---

## EvaluateBool - ID: 139
/doc/reference/classes/ucalc.expression/evaluatebool/

**Description:** Evaluates a pre-parsed boolean expression, returning the native true or false result efficiently.

**Syntax:** EvaluateBool()
**Return:** bool - The result of the evaluated Boolean expression
**Remarks:**

The `EvaluateBool` method is the high-performance counterpart to [Evaluate](/reference/uCalcBase/Expression/Evaluate) for expressions that result in a boolean value. It executes a pre-compiled expression object, created by [Parse](/reference/uCalcBase/uCalc/Parse), and returns the native `true` or `false` result.

This method is ideal for performance-critical scenarios, such as evaluating conditions inside a loop, where the overhead of parsing the same string repeatedly would be prohibitive.

### ⚙️ How It Works

Expressions involving comparison operators (`<`, `>`, `==`, `<>`), logical operators (`And`, `Or`, `Not`), or functions that return a boolean will produce a boolean result. When you [Parse](/reference/uCalcBase/uCalc/Parse) such an expression, uCalc creates a compiled object typed to return a boolean. `EvaluateBool` is the most direct and efficient way to execute this object.

### `EvaluateBool` vs. `Evaluate`

While the generic [Evaluate](/reference/uCalcBase/Expression/Evaluate) method can also return a boolean result (which it casts to a `double` where `1.0` is true and `0.0` is false), `EvaluateBool` has distinct advantages:

| Feature | `EvaluateBool()` | `Evaluate()` | `EvaluateStr()` |
| :--- | :--- | :--- | :--- |
| **Return Type** | Native `bool` | `double` | `string` |
| **Type Safety** | 🟢 High. Fails predictably if expression is not boolean. | 🟡 Medium. Casts boolean to number. | 🟢 High. Converts boolean to text. |
| **Performance** | 🟢 Highest for boolean logic. | 🟡 High, but with a slight overhead for type casting. | 🔴 Lowest due to string allocation/formatting. |
| **Use Case** | Conditional logic, loops, validation rules. | General numeric calculations. | User-facing display, logging. |

### 💡 Comparative Analysis

In native languages, you might use compiled lambda expressions or function pointers for dynamic conditional logic.

*   **C# `Func<bool>`**: A `Func<bool>` delegate can be compiled from an expression tree for performance, but building that tree from a raw string is a complex, multi-step process.
*   **Standard C++**: Evaluating string-based boolean logic typically requires integrating a full-blown parsing library.

`uCalc` provides a much simpler workflow: `Parse` a string once, then call `EvaluateBool` in a tight loop. This delivers the performance of a compiled delegate with the flexibility of dynamic string input, offering a powerful middle ground between static code and heavy scripting engines.

**Examples:**

### Example ID: 93

**Description:** EvaluateBool, also ValueStr which converts numeric value to string

**Code:**
```pseudocode

var VariableX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse("x > 3"); // The > operation returns a Boolean instead of the default floating point

for (double x = 1 to 5)
   VariableX.Value(x);
   wl("x = ", VariableX.ValueStr(), "  x > 3 is ", bool(ParsedExpr.EvaluateBool()))
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  x > 3 is False
x = 2  x > 3 is False
x = 3  x > 3 is False
x = 4  x > 3 is True
x = 5  x > 3 is True
```

---

---

## EvaluateDbl - ID: 140
/doc/reference/classes/ucalc.expression/evaluatedbl/

**Description:** Rapidly evaluates a pre-parsed expression, optimized specifically for double-precision floating-point results.

**Syntax:** EvaluateDbl()
**Return:** double - The double-precision floating-point result of the expression. Returns an undefined value if the expression does not yield a double.
**Remarks:**

The `EvaluateDbl` method evaluates a pre-parsed expression, optimized specifically for performance-critical scenarios that return a **double-precision floating-point** value. It is the type-strict counterpart to the more flexible [Evaluate](/reference/ucalc/expression/evaluate) method.

This method is a key component of uCalc's two-step evaluation model:
1.  **Parse Once**: Call [uCalc.Parse()](/reference/ucalc/parse) to convert an expression string into a compiled [Expression](/reference/ucalc/expression) object.
2.  **Evaluate Many**: Call `EvaluateDbl()` repeatedly on the `Expression` object, which is significantly faster than re-parsing the string each time with [Eval()](/reference/ucalc/eval).

### 🎯 Strict Type Enforcement

`EvaluateDbl` is designed for speed and requires that the parsed expression's result is a `double`.
*   **Success**: Works correctly for expressions like `3.14 * r^2`.
*   **Failure**: Returns an **undefined or incorrect value** if the expression yields another numeric type (like `Int32` or `Boolean`) or a non-numeric type (`String`, `Complex`). No conversion is attempted, and no error is raised.

Use the general-purpose [Evaluate()](/reference/ucalc/expression/evaluate) method if your expression might return other numeric types, as it will handle the conversion to `double` automatically.

### `EvaluateDbl` vs. `Evaluate`

| Feature | `EvaluateDbl()` | `Evaluate()` |
| :--- | :--- | :--- |
| **Performance** | 🟢 **Highest**. Optimized for direct double evaluation. | 🟡 High. Slightly slower due to type-checking and potential conversion logic. |
| **Type Safety** | 🔴 **Strict**. Only works for expressions returning `double`. | 🟢 **Flexible**. Handles any numeric type by converting it to `double`. |
| **Use Case** | Ideal for high-speed loops in scientific or financial calculations where the return type is known to be `double`. | General-purpose numeric evaluation where flexibility is more important than maximum performance. |

---
### 💡 Comparative Analysis: Why Use a Two-Step Process?

In many programming environments, evaluating a string expression is a single, monolithic operation. uCalc separates parsing from evaluation, which mirrors how compilers work and offers significant performance advantages.

*   **vs. `eval()` in Scripting Languages**: Functions like JavaScript's `eval()` re-parse the string on every call, making them inefficient for loops.
*   **vs. C# `DataTable.Compute`**: This common .NET workaround is notoriously slow because it involves significant overhead for each calculation.
*   **vs. Compiled Code**: The [Parse](/reference/ucalc/parse) step is analogous to a just-in-time (JIT) compilation. Once the [Expression](/reference/ucalc/expression) object is created, calls to `EvaluateDbl` are nearly as fast as calling a native, compiled function, but with the full dynamic flexibility of a runtime engine.

This model allows uCalc to achieve performance levels suitable for real-time simulations and data processing tasks that would be too slow for traditional script evaluators.

**Examples:**

### Example ID: 96

**Description:** Evaluate() auto-conversion

**Code:**
```pseudocode
// The int return value type in MyExprB is converted to
// Double with .Evaluate(), but not with .EvaluateDbl()
var MyExprA = uc.Parse("3.2 + 5.2");
var MyExprB = uc.Parse("int(3.2 + 5.2)");

wl(MyExprA.Evaluate())
wl(bool(MyExprA.EvaluateDbl() == 8.4))
wl(MyExprB.Evaluate())
wl(bool(MyExprB.EvaluateDbl() == 8))
```

**Output:**
```
8.4
True
8
False
```

---

---

## EvaluateInt32 - ID: 141
/doc/reference/classes/ucalc.expression/evaluateint32/

**Description:** Evaluates a pre-parsed expression and returns the result as a 32-bit integer.

**Syntax:** EvaluateInt32()
**Return:** int32 - The 32-bit integer result of the evaluated expression.
**Remarks:**

The `EvaluateInt32` method executes a pre-compiled [Expression](/reference/ucalc/expression) and returns its result as a 32-bit signed integer. It is designed for high-performance scenarios where the same integer-based expression is evaluated multiple times.

### 🚀 The Parse/Evaluate Performance Pattern

For optimal performance, especially in loops, you should separate parsing from evaluation:

1.  **Parse Once**: Call [Parse()](/reference/ucalc/parse) outside the loop to convert the expression string into an efficient, executable object. When parsing, you must specify an integer type (e.g., `"Int32"`, `"Integer"`, or `"Int"`) to ensure the result is correctly typed.
2.  **Evaluate Many Times**: Call `EvaluateInt32()` inside the loop. This step is extremely fast as it bypasses the string parsing overhead.

### `EvaluateInt32` vs. `Evaluate` vs. `EvaluateDbl`

| Method | Return Type | Use Case |
| :--- | :--- | :--- |
| `EvaluateInt32()` | `int32_t` | For expressions explicitly parsed to an integer type. Offers the best performance and type safety for integer math. |
| [Evaluate()](/reference/ucalc/expression/evaluate) | `double` | A general-purpose method that can evaluate numeric types (including integers) but always returns them as a `double`, involving a potential conversion. |
| [EvaluateDbl()](/reference/ucalc/expression/evaluatedbl) | `double` | Strictly for expressions that return a `double`. Calling it on an integer-parsed expression may lead to incorrect results. |

**Best Practice**: Always match the `Evaluate<Type>()` method to the data type specified during the `Parse()` call.

### 💡 Comparative Analysis

*   **vs. Native Compilation (C++/C#)**: A compiled language resolves expressions at compile-time for maximum speed. uCalc's Parse/Evaluate pattern provides a runtime equivalent. The `Parse` step is analogous to compilation, creating a highly optimized intermediate representation. The `EvaluateInt32` step is the fast execution of that compiled code. This gives you the performance benefits of compilation with the flexibility of a dynamic, string-based input.

*   **vs. Scripting Engines (`eval`)**: A generic `eval()` function in languages like Python or JavaScript must parse and evaluate the string every time it's called. This is convenient but slow. uCalc's two-step process is orders of magnitude faster for repeated evaluations.

For convenience, `"Int"` and `"Integer"` are defined as synonyms for `"Int32"` when specifying a return type for a function or operator via [DefineFunction()](/reference/ucalc/definefunction) or [DefineOperator()](/reference/ucalc/defineoperator).

**Examples:**

### Example ID: 32

**Description:** Displaying Integer (Int32) results with Evaluate32

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");

var ParsedExpr = uc.Parse("x / 2", "Integer"); // Causes output of "x / 2" to convert to an integer

// NOTE: EvaluateInt32 should only be used when Parse() explicitly specifies Integer
// (Or Int, or Int32) as the second argument, or if the expression evaluates to an integer
// (such as evaluating a variable that was explicitly defined as integer;
// other arithmetic operators typically evaluate to Double floating point).

for (double x = 1 to 10)
   VariableX.Value(x);
   wl("x = " + VariableX.ValueStr() + "  Result = " + to_string(ParsedExpr.EvaluateInt32()))
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  Result = 0
x = 2  Result = 1
x = 3  Result = 1
x = 4  Result = 2
x = 5  Result = 2
x = 6  Result = 3
x = 7  Result = 3
x = 8  Result = 4
x = 9  Result = 4
x = 10  Result = 5
```

---

---

## EvaluateStr - ID: 142
/doc/reference/classes/ucalc.expression/evaluatestr/

**Description:** Evaluates a pre-parsed expression and returns the result of any data type as a string.

**Syntax:** EvaluateStr(bool)
**Parameters:**
returnFormatted - bool [default = true] - If true, the output string is processed by any custom formatters defined with uCalc.Format(). If false, the raw, unformatted string representation of the result is returned.
**Return:** string - A string containing the formatted or raw result of the evaluation. If an error occurs, the string contains the error message.
**Remarks:**

The `EvaluateStr` method executes a pre-compiled [Expression](/Reference/uCalcBase/Expression) object and returns the result as a string. It is the second step in the recommended two-step process for high-performance evaluation: `Parse` once, `EvaluateStr` many times.

This method is the most versatile way to get a display-ready result, as it correctly handles all data types and can apply custom formatting rules.

### 💡 `EvaluateStr` vs. `Evaluate`

While both methods execute a parsed expression, they serve different purposes. Use this table to decide which is appropriate for your use case:

| Feature | `EvaluateStr()` | [Evaluate()](/Reference/uCalcBase/Expression/Evaluate) |
| :--- | :--- | :--- |
| **Return Type** | `string` | `double` |
| **Supported Data Types** | All (Numeric, String, Complex, Bool, etc.) | Numeric types (or those convertible to `double`) |
| **Error Handling** | Safely returns the error message as a string. | Returns `NaN` or `Infinity`; requires checking [Error.Code](/Reference/uCalcBase/uCalc/Error.Code). |
| **Primary Use Case** | Displaying results to a user, handling any return type. | High-speed, numeric-only calculations in loops. |

### 🎨 Output Formatting

The `returnFormatted` parameter provides powerful control over the output string:

*   **`true` (Default)**: The result is processed through the formatting pipeline. Any rules defined with [uCalc.Format()](/Reference/uCalcBase/uCalc/Format) that match the result's data type will be applied. This is ideal for consistently styling output, such as adding currency symbols or normalizing date formats.
*   **`false`**: The formatting pipeline is bypassed, and the raw, default string representation of the result is returned.

This allows you to separate calculation logic from presentation logic cleanly.

### Comparative Analysis

*   **vs. Native `.ToString()`**: In languages like C#, every object has a `.ToString()` method. However, `EvaluateStr` is superior because it is context-aware. It leverages the formatting rules defined within its parent [uCalc](/Reference/uCalcBase/uCalc) instance, allowing for dynamic and centralized control over application-wide output styles that a simple `.ToString()` call cannot achieve.

*   **vs. `eval()` in Scripting Languages**: Unlike the `eval()` function in languages like JavaScript or Python, which can execute arbitrary code and pose a security risk, `EvaluateStr` operates within a secure sandbox. It can only execute functions and access variables that have been explicitly defined in its `uCalc` instance, preventing code injection vulnerabilities.

*   **vs. `uCalc.EvalStr()`**: It's important to distinguish between the two `EvalStr` methods. [uCalc.EvalStr()](/Reference/uCalcBase/uCalc/EvalStr) is a one-step convenience function that takes a raw string, parses it, and evaluates it. `Expression.EvaluateStr()` is the high-performance version that operates on an *already-parsed* object, avoiding the cost of re-parsing in loops.

**Examples:**

### Example ID: 42

**Description:** Displaying strings with EvaluateStr()

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x As Int32");
var MyStringVar = uc.DefineVariable("MyString = 'Hello world'");
var ParsedExpr = uc.Parse("SubStr(MyString, x, 1)");
var StrLength = uc.Eval("Length(MyString)");

for (int x = 0 to uc.Eval("Length(MyString) - 1"))
   VariableX.ValueInt32(x);
   w(ParsedExpr.EvaluateStr() + ".")
end for
```

**Output:**
```
H.e.l.l.o. .w.o.r.l.d.
```

---

### Example ID: 43

**Description:** Displaying complex number outputs with EvaluateStr()

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse("x * #i + 5", "Complex");

for (double x = 1 to 10)
   VariableX.Value(x);
   // Note: EvaluateStr works with any data type;
   wl(uc.EvalStr("$'x = {x}  Result = '") + ParsedExpr.EvaluateStr())   
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  Result = 5+1i
x = 2  Result = 5+2i
x = 3  Result = 5+3i
x = 4  Result = 5+4i
x = 5  Result = 5+5i
x = 6  Result = 5+6i
x = 7  Result = 5+7i
x = 8  Result = 5+8i
x = 9  Result = 5+9i
x = 10  Result = 5+10i
```

---

### Example ID: 17

**Description:** DefineVariable examples

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var MyInt = uc.DefineVariable("MyInt As Int");
var MyStr = uc.DefineVariable("MyStr As String");
uc.DefineVariable("OtherStr = 'string type inferred'");
uc.DefineVariable("MyInt16 = Int16(100/3)"); // type inferred
uc.DefineVariable("MyBool = True"); // type inferred
uc.DefineVariable("MyComplex = 3 + 4*#i"); // type inferred

MyVar.Value(123);
MyInt.ValueInt32(456);
MyStr.ValueStr("This is a test");

wl("MyVar = " + uc.EvalStr("MyVar"))
wl("MyInt = " + uc.EvalStr("MyInt"))
wl("MyStr = " + uc.EvalStr("MyStr"))
wl("OtherStr = " + uc.EvalStr("OtherStr"))
wl("MyInt16 = " + uc.EvalStr("MyInt16"))
wl("MyBool = " + uc.EvalStr("MyBool"))
wl("MyComplex = " + uc.EvalStr("MyComplex"))
wl("---")
wl(MyVar.Value())
wl(MyInt.ValueInt32())
wl(MyStr.ValueStr())
wl("---")
wl(uc.ItemOf("MyVar").@DataType().@Name())
wl(uc.ItemOf("MyInt").@DataType().@Name())
wl(uc.ItemOf("MyStr").@DataType().@Name())
wl(uc.ItemOf("OtherStr").@DataType().@Name())
wl(uc.ItemOf("MyInt16").@DataType().@Name())
wl(uc.ItemOf("MyBool").@DataType().@Name())
wl("---")

var Expression = "x^2 * 10";
var VarX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse(Expression);

w("Expression = ")
wl(Expression)
for (int x = 1 to 10)
   VarX.Value(x); // In C++ you can skip this by passing &x to DefineVariable
   wl("x = " + VarX.ValueStr() + "  Result = " + ParsedExpr.EvaluateStr())
end for

ParsedExpr.Release();
VarX.Release();
```

**Output:**
```
MyVar = 123
MyInt = 456
MyStr = This is a test
OtherStr = string type inferred
MyInt16 = 33
MyBool = true
MyComplex = 3+4i
---
123
456
This is a test
---
double
int
string
string
int16
bool
---
Expression = x^2 * 10
x = 1  Result = 10
x = 2  Result = 40
x = 3  Result = 90
x = 4  Result = 160
x = 5  Result = 250
x = 6  Result = 360
x = 7  Result = 490
x = 8  Result = 640
x = 9  Result = 810
x = 10  Result = 1000
```

---

---

## EvaluateVoid - ID: 143
/doc/reference/classes/ucalc.expression/evaluatevoid/

**Description:** Evaluates the expression and returns a native pointer to the result's memory location.

**Syntax:** EvaluateVoid()
**Return:** IntPtr - An `IntPtr` representing the memory address of the evaluation result. The data at this address is valid only until the next evaluation within the same uCalc instance.
**Remarks:**

This method is an advanced alternative to `Evaluate`. Instead of returning a copy of the result, it returns a direct native pointer to the internal memory where the result is stored.

### 🎯 Primary Use Case

**🔧 Type Punning**: It allows you to interpret the raw memory of a result as a different data type, without any conversion. This is useful for low-level tasks, such as treating the bits of an unsigned integer as a signed integer (as shown in the examples), or reinterpreting a floating-point number as an integer to examine its bit pattern. This is accomplished by passing the returned pointer to the [ValueAt](/uCalc/uCalc/ValueAt) method with the desired target type.

### ⚠️ Pointer Validity and Lifetime

The returned pointer is **ephemeral**. It is only guaranteed to be valid until the next evaluation is performed on **any expression** within the same `uCalc` instance. uCalc reuses internal memory buffers for efficiency, so the memory location pointed to by the result of one evaluation will be overwritten by the result of the next.

**Correct Usage:**
```pseudocode
New(uCalc, uc);
// Get pointer and use it immediately.
var resultPtr = myExpr.EvaluateVoid();
var value = uc.ValueAt(resultPtr, "Int32"); 
// The value is now safely stored in a managed variable.
```

**Incorrect Usage:**
```pseudocode
New(uCalc, uc);
// Get pointer A.
var ptrA = expr1.EvaluateVoid();

// Another evaluation happens, invalidating ptrA.
var ptrB = expr2.EvaluateVoid(); 

// This line is unsafe! ptrA may now point to the result of expr2.
var value = uc.ValueAt(ptrA, "Int32"); 
```

### Comparison to Native Languages

In C#, performing similar operations would typically require an `unsafe` code context. In C++, it would involve direct pointer manipulation. The `EvaluateVoid` and `ValueAt` combination provides a safer, cross-platform abstraction for these powerful low-level memory operations without leaving the managed environment.

**Examples:**

### Example ID: 44

**Description:** Displaying an expression of unsigned byte as a signed byte by using a Pointer

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x As Int");
var ParsedExpr = uc.Parse("x + 125", "Int8u");

for (int x = 1 to 10)
   VariableX.ValueInt32(x);
   wl("x = ", x, "  Int8 result = ", uc.ValueAt(ParsedExpr.EvaluateVoid(), "Int8"))
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  Int8 result = 126
x = 2  Int8 result = 127
x = 3  Int8 result = -128
x = 4  Int8 result = -127
x = 5  Int8 result = -126
x = 6  Int8 result = -125
x = 7  Int8 result = -124
x = 8  Int8 result = -123
x = 9  Int8 result = -122
x = 10  Int8 result = -121
```

---

---

## Execute - ID: 144
/doc/reference/classes/ucalc.expression/execute/

**Description:** Executes a pre-parsed expression without returning a value, optimized for operations valued for their side effects rather than their result.

**Syntax:** Execute()
**Return:** void - This method does not return a value.
**Remarks:**

The `Execute` method evaluates a pre-parsed [Expression](/reference/expression/constructor/) for its **side effects**, discarding any potential return value. It is the ideal choice for performance-critical loops or for running expressions that behave like imperative statements (e.g., variable assignments, increments) rather than mathematical calculations.

### `Execute` vs. `Evaluate`

Choosing between `Execute` and `Evaluate` is a key architectural decision. `Execute` signals an intent to modify state, while `Evaluate` signals an intent to compute a value.

| Feature | `Execute()` | `Evaluate()` / `EvaluateStr()` |
| :--- | :--- | :--- |
| **Return Value** | `void` (None) | A value (`double`, `string`, etc.) |
| **Purpose** | For side effects: changing variables, calling stateful functions. | For computation: calculating a result. |
| **Performance** | Higher. Bypasses the overhead of packaging and returning a value. | Slightly lower. Incurs cost to prepare and return the result. |
| **Analogy** | A `void` function in C# or a statement ending in a semicolon. | A function that returns a value. |

### ⚖️ Comparative Analysis: Why uCalc?

In most programming languages, there is a clear distinction between an **expression** (which evaluates to a value, e.g., `2 + 2`) and a **statement** (which performs an action, e.g., `x = 5;`). uCalc is primarily an *expression* engine.

The `Execute()` method provides a bridge, allowing you to treat a parsed expression as a *statement*. This is powerful because it lets you build script-like, imperative logic that runs within the high-performance, sandboxed uCalc environment.

*   **Without `Execute`**: To increment a variable in a loop, you would need to constantly read its value from the engine, perform the calculation in your host language (C#/C++), and write it back. This involves significant overhead from crossing the boundary between your code and the uCalc engine.
*   **With `Execute`**: You can define the entire operation (e.g., `"x = x + 1"`) within a single parsed expression and call `Execute()` repeatedly. The entire loop runs inside the highly optimized engine, resulting in better performance.

**Examples:**

### Example ID: 22

**Description:** How to perform a summation in a loop efficiently using Execute() instead of Evaluate().

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x = 0");
var Total = uc.DefineVariable("Total");
var(string, Expression) = "x++; Total = Total + x^2 + 5";

var ParsedExpr = uc.Parse(Expression);

for(double x = 1 to 10)
   // Execute() runs the parsed expression without the overhead of returning a value.
   // This provides near-native performance for loops across C#, VB, and C++.
   ParsedExpr.Execute();

   // Evaluate string interpolation to output the final calculated total
   wl(uc.EvalStr("$'{x}   Sub total = {Total}'"))
end for

wl(uc.EvalStr("$'Total = {Total}'"))

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
1   Sub total = 6
2   Sub total = 15
3   Sub total = 29
4   Sub total = 50
5   Sub total = 80
6   Sub total = 121
7   Sub total = 175
8   Sub total = 244
9   Sub total = 330
10   Sub total = 435
Total = 435
```

---

---

## Handle - ID: 145
/doc/reference/classes/ucalc.expression/handle/

**Description:** Returns the internal handle of the Expression object, a unique identifier used by the library for low-level operations.

**Syntax:** Handle()
**Return:** ADDR - The internal handle of the current Expression instance. While typed as an Expression object for convenience, it represents an opaque pointer whose numeric value is not guaranteed to be consistent across application runs.
**Remarks:**

This method retrieves the internal handle of an `Expression` object. Handles are opaque, pointer-like identifiers used by the uCalc library to manage instances. This is primarily intended for advanced debugging and internal diagnostics.

### What is a Handle?
A handle is a unique, low-level identifier for a specific `Expression` instance in memory. Its actual numeric value is unpredictable and can change every time the application runs. It should not be stored or used for serialization.

For a stable and predictable identifier, use [MemoryIndex](/reference/ucalc/expression/memoryindex) instead.

--- 

### ⚖️ `Handle` vs. `MemoryIndex`

| Feature | Handle | MemoryIndex |
| :--- | :--- | :--- |
| **Stability** | **Volatile**. Changes between application runs. | **Stable**. Predictable and sequential. |
| **Uniqueness** | Guaranteed unique for the object's lifetime. | Can be **recycled** after an object is released. |
| **Purpose** | Low-level object identification for the C++ core. | High-level diagnostics and tracking object lifetime. |
| **Use Case** | Advanced debugging. | Identifying specific instances for logging or in diagnostic tools. |

--- 

### Comparative Analysis

In C# or C++, you might think of a handle as being similar to an `IntPtr` or a raw pointer (`void*`). It refers to a specific memory location managed by the uCalc engine. However, unlike raw pointers, the uCalc handle is managed within the uCalc ecosystem. The key takeaway for developers is to use [MemoryIndex](/reference/ucalc/expression/memoryindex) for any form of stable identification and to treat the `Handle` as a transient, internal-only value.

**Examples:**

---

## MemoryIndex = [int] - ID: 606
/doc/reference/classes/ucalc.expression/memoryindex-=-[int]/

**Description:** Returns a stable, predictable integer index for the expression object, useful for diagnostics and tracking object lifetime.

**Remarks:**

The `MemoryIndex` method returns a stable, predictable integer identifier for a specific `Expression` object. While primarily intended for diagnostics and internal use, it provides a reliable way to track individual objects throughout their lifecycle.

### ⚖️ `MemoryIndex` vs. `Handle`

It's crucial to distinguish `MemoryIndex` from an object's `Handle`:

| Feature | `MemoryIndex` | `Handle` |
| :--- | :--- | :--- |
| **Stability** | **Stable & Predictable**. The first object gets index 1, the second gets 2, etc. | **Volatile**. An internal pointer-like value that changes between application runs. |
| **Uniqueness** | Unique for the object's lifetime, but **can be recycled** after release. | Guaranteed unique for the object's lifetime. |
| **Purpose** | High-level diagnostics, logging, and tracking object lifetimes. | Low-level internal operations. |

### ♻️ Index Recycling

When an `Expression` object is released using [Release](/reference/uCalc/Expression/Release), its `MemoryIndex` is returned to a pool. The next `Expression` object created will reuse that index. This is an efficient memory management strategy, but it means you cannot assume that a given index refers to the same logical expression for the entire duration of your application's run. If you need to track objects, you must also track their creation and destruction.

### 💡 Comparative Analysis

In standard C# or C++, developers often rely on object references or pointers to identify objects. If you need a stable integer ID, you typically have to add it yourself, often with a static counter.

```csharp
// Manual C# approach
public class MyObject {
    private static int nextId = 0;
    public int Id { get; private set; }
    public MyObject() {
        this.Id = System.Threading.Interlocked.Increment(ref nextId);
    }
}
```

uCalc provides this functionality out-of-the-box with `MemoryIndex`. Its built-in recycling mechanism is a performance optimization that manual implementations often overlook. This makes `MemoryIndex` a valuable tool for advanced users building performance-sensitive applications or debugging complex object interactions.

**Examples:**

---

## Owned - ID: 741
/doc/reference/classes/ucalc.expression/owned/

**Syntax:** Owned()
**Return:** Expression - 
**Remarks:**

[Revisit]

---

## Parse - ID: 464
/doc/reference/classes/ucalc.expression/parse/

**Description:** Parses a new expression

**Syntax:** Parse(string, DataType)
**Parameters:**
Expr - string - Expression to be parsed
ReturnType - DataType [default = Empty] - Data type of return value
**Return:** Expression - The current expression object
**Remarks:**

This allows you to associate a different expression with the same object.  The previous expression is released internally first.

---

## Release - ID: 146
/doc/reference/classes/ucalc.expression/release/

**Description:** Frees the memory and resources associated with a compiled expression object, making it invalid for future use.

**Syntax:** Release()
**Return:** void - This method does not return a value.
**Remarks:**

When you parse an expression with [Parse](/Reference/uCalc/uCalc/Parse), uCalc compiles the string into an efficient, executable object (an Abstract Syntax Tree or AST). This process allocates memory that is managed by the uCalc engine. The `Release` method is the explicit command to deallocate this memory and destroy the expression object.

Once an expression is released, its handle becomes invalid, and any attempt to use it will result in undefined behavior.

# 🗑️ Why Release?

uCalc's core is written in C++, and it manages its own memory for performance. Parsed expressions are not automatically garbage-collected by managed runtimes like .NET. Therefore, failing to release an expression object that you no longer need will cause a **memory leak**. It is crucial to have a clear strategy for releasing expressions, especially those created inside loops or in long-running applications.

# 🔧 Release Mechanisms

There are three primary ways an expression is released:

### 1. Manual Release
This is the most direct approach. You explicitly call the `Release()` method on the expression object.

```pseudocode
var expr = uc.Parse("1 + 2");
// ... use the expression ...
expr.Release(); // Manually free the memory.
```

### 2. Automatic (Scoped) Release - Best Practice

The recommended approach is to use language features that guarantee resource cleanup. This pattern, known as RAII (Resource Acquisition Is Initialization) in C++, ensures that `Release()` is called automatically when the object goes out of scope.

*   **C# / VB.NET**: Use a `using` block. The `new` statement in the examples below translates to this.
*   **C++**: Call [Owned](/ucalc/expression/owned).

This is the safest way to prevent memory leaks.

```pseudocode
// The expression is automatically released at the end of the scope.
NewUsing(uCalc::Expression, expr("5 * 10"))
wl(expr.Evaluate());
End Using
```

### 3. Implicit Release
When you release a parent [uCalc](/Reference/uCalcBase/uCalc) instance, all objects it owns—including all parsed expressions, variables, functions, etc.—are automatically released.

# ⚖️ Comparative Analysis

*   **vs. Managed Garbage Collection (C#)**: Standard .NET objects are tracked by the garbage collector. uCalc's `Expression` objects, however, are wrappers around native C++ resources. `Release()` is the bridge that allows your managed code to correctly signal to the unmanaged core that the memory can be freed. The `using` statement (`IDisposable`) is the standard C# pattern for this.

*   **vs. Manual `new`/`delete` (C++)**: While `Release()` is conceptually similar to `delete`, uCalc's scoped constructors and the `Owned` pattern provide a much safer, RAII-compliant model that helps prevent common C++ pitfalls like forgetting to call `delete`.

**Examples:**

### Example ID: 601

**Description:** A simple demonstration of parsing an expression and then manually releasing it.

**Code:**
```pseudocode
var expr = uc.Parse("1 + 2");
wl(expr.EvaluateStr())

// Manually release the expression when it's no longer needed.
expr.Release();
```

**Output:**
```
3
```

---

### Example ID: 602

**Description:** Demonstrates the recommended practice of using a scoped block for automatic resource management, preventing memory leaks.

**Code:**
```pseudocode
// A 'NewUsing' block ensures the expression is automatically released at the end of the scope.
// This is the safest pattern to prevent memory leaks.
NewUsing(uCalc::Expression, expr("5 * 10"))
  wl("Result within scope: ", expr.Evaluate())
End Using

// The 'expr' object is now released and its handle is invalid.
wl("Expression has been automatically released.")
```

**Output:**
```
Result within scope: 50
Expression has been automatically released.
```

---

### Example ID: 31

**Description:** Illustrates the core relationship between the uCalc engine, an Item (variable), and a compiled Expression.

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");
var Expression = "x^2 * 10"; // Replace this with your expression

wl("--- Efficient: Parse() once, then Evaluate() in a loop ---")
var ParsedExpr = uc.Parse(Expression);
for(double x = 1 to 10)
   VariableX.Value(x);
   wl(ParsedExpr.Evaluate())
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
--- Efficient: Parse() once, then Evaluate() in a loop ---
10
40
90
160
250
360
490
640
810
1000
```

---

### Example ID: 94

**Description:** Expression constructor

**Code:**
```pseudocode
uCalc::@DefaultInstance().DefineVariable("x = 1.2");
uc.DefineVariable("x = 3.2");

New(uCalc::Expression, MyExprA)
New(uCalc::Expression, MyExprB("x+4.25"))
New(uCalc::Expression, MyExprC("x+4.25", uCalc::@DefaultInstance().DataTypeOf("int")))
New(uCalc::Expression, MyExprD(uc, "x+4.25"))

MyExprA.Parse("x*100");

wl(MyExprA.Evaluate())
wl(MyExprB.Evaluate())
wl(MyExprC.Evaluate())
wl(MyExprD.Evaluate())

// Release expressions when no longer needed (see other example for auto-release)
MyExprA.Release();
MyExprB.Release();
MyExprC.Release();
MyExprD.Release();
```

**Output:**
```
120
5.45
5
7.45
```

---

---

## uCalc = [uCalc] - ID: 463
/doc/reference/classes/ucalc.expression/ucalc-=-[ucalc]/

**Description:** Returns the parent uCalc instance that owns this expression, providing access to its evaluation context.

**Remarks:**

Every parsed [Expression](/reference/ucalc/expression) object is intrinsically linked to the [uCalc](/reference/ucalcbase) instance that created it. This parent instance holds the complete context—variables, functions, operators, and settings—required to evaluate the expression. The `uCalc()` method provides a way to retrieve this parent instance, enabling you to inspect or modify the evaluation environment dynamically.

### 🎯 Core Use Cases

1.  **Contextual Modification**: You can parse an expression and then, before evaluating it, use its `uCalc()` method to modify the environment. This is useful for dynamically adding a function or variable that the expression requires.

2.  **Multi-Instance Management**: In applications that use multiple `uCalc` instances (e.g., for sandboxing or different configurations), an `Expression` object might be passed between different parts of your code. This method allows you to reliably determine which engine an expression belongs to, which is crucial for debugging and ensuring correct evaluation.

3.  **Introspection**: It serves as a key tool for introspection, allowing you to query the state of the engine that will ultimately be used to evaluate the expression.

### 💡 Comparative Analysis

*   **vs. C# LINQ Expressions**: A LINQ `Expression` tree is a pure data structure representing code. It has no inherent evaluation context. You provide the context later when you compile it into a delegate. In contrast, a uCalc `Expression` is pre-bound to its context. This makes evaluation simpler as the context is implicit, and the `uCalc()` method makes that context explicitly retrievable.

*   **vs. Global Evaluators**: Many simple math evaluators operate with a single, global context. uCalc's multi-instance design provides superior encapsulation and safety. The `uCalc()` method is the bridge that connects a specific expression back to its sandboxed environment, a feature not present in globally-scoped evaluators.

**Examples:**

### Example ID: 604

**Description:** Demonstrating that each parsed expression is owned by the uCalc instance that created it.

**Code:**
```pseudocode
// Create two separate uCalc instances
New(uCalc, uc1)
New(uCalc, uc2)

// Parse the same expression string in both instances
var expr1 = uc1.Parse("1 + 1");
var expr2 = uc2.Parse("1 + 1");

// Use the .uCalc() method and MemoryIndex to verify ownership
wl("expr1 belongs to uc1: ", bool(expr1.@uCalc().@MemoryIndex() == uc1.@MemoryIndex()))
wl("expr2 belongs to uc2: ", bool(expr2.@uCalc().@MemoryIndex() == uc2.@MemoryIndex()))
wl("expr1 does not belong to uc2: ", bool(expr1.@uCalc().@MemoryIndex() != uc2.@MemoryIndex()))
```

**Output:**
```
expr1 belongs to uc1: True
expr2 belongs to uc2: True
expr1 does not belong to uc2: True
```

---

### Example ID: 605

**Description:** A practical example of retrieving an expression's parent uCalc instance to dynamically add a formatting rule before evaluation.

**Code:**
```pseudocode
// Practical (Real World)
// Parse an expression
var myExpr = uc.Parse("5 + 4");
wl("Initial evaluation: ", myExpr.Evaluate())

// Retrieve the parent uCalc instance from the expression object
var parentUc = myExpr.@uCalc();

// Use the parent instance to add a new formatting rule
parentUc.Format("Result = 'Answer = ' + Result");

// The new format is now active for this expression's context
wl("Formatted evaluation: ", myExpr.EvaluateStr())
```

**Output:**
```
Initial evaluation: 9
Formatted evaluation: Answer = 9
```

---

### Example ID: 606

**Description:** An internal test verifying that an expression remains tied to its original context, even after the context has been cloned and modified.

**Code:**
```pseudocode
// Internal Test: Context integrity after cloning
New(uCalc, baseUc)
baseUc.DefineVariable("x = 100");

// Clone the base instance and modify the variable in the clone
var clonedUc = baseUc.Clone();
clonedUc.Eval("x = 200");

// Parse an expression in the original base context
var baseExpr = baseUc.Parse("x");

// 1. Verify the expression evaluates using its original context's value
wl("Base expression evaluates to: ", baseExpr.Evaluate())

// 2. Get the parent and verify it is not the cloned instance
wl("Parent is not the clone: ", bool(baseExpr.@uCalc().@MemoryIndex() != clonedUc.M@emoryIndex()))
```

**Output:**
```
Base expression evaluates to: 100
Parent is not the clone: True
```

---

### Example ID: 97

**Description:** Gets uCalc object associated with an expression

**Code:**
```pseudocode
var MyExpr = uc.Parse("5+4");

wl(MyExpr.Evaluate())

MyExpr.@uCalc().Format("Result = 'Answer = ' + Result");

wl(MyExpr.EvaluateStr())
```

**Output:**
```
9
Answer = 9
```

---

---

## uCalc.Item - ID: 147
/doc/reference/classes/ucalc.item/

**Description:** Class for handling uCalc items

---

## Introduction - ID: 963
/doc/reference/classes/ucalc.item/introduction/

**Description:** The universal, polymorphic object representing any symbol defined within a uCalc instance, such as a function, variable, or operator.

**Remarks:**

# 🔬 uCalc.Item: The Polymorphic Symbol Object

The `uCalc.Item` class is the common currency of the uCalc engine. It is a versatile, polymorphic handle that represents *any* symbol defined within a [`uCalc`](/Reference/uCalcBase/uCalc/Constructor) instance, from a simple variable to a complex function, operator, or transformer rule.

Think of it as a super-charged version of .NET's `System.Object` or C++'s `std::any`, but with a rich, built-in API for introspection and dynamic manipulation tailored for a parsing environment.

--- 

## ✨ `Item` vs. Native Reflection

In languages like C# or Java, runtime introspection is handled by a reflection API with distinct classes for different symbol types (e.g., `MethodInfo`, `FieldInfo`, `PropertyInfo`). uCalc simplifies this with a unified model.

*   **Unified Handle**: The `Item` class provides a single, consistent interface for all symbol types. You don't need to cast to different `*Info` objects.
*   **Dynamic Nature**: `Item` objects represent symbols created at runtime, often from user input, a capability that goes beyond compile-time reflection.
*   **Performance**: As an integrated feature, interacting with `Item` objects is highly optimized for the uCalc engine's internal data structures.

--- 

## 📖 Class Members Overview

This section provides a summary of the properties and methods available on an `Item` object.

### 🧐 Core Introspection
These properties provide access to the fundamental metadata of a symbol.

| Member | Description |
| :--- | :--- |
| [`Name`](/Reference/uCalcBase/Item/Name) | Retrieves the programmatic name of the symbol (e.g., "MyVar", "Cos"). |
| [`Description`](/Reference/uCalcBase/Item/Description) | Gets or sets a user-defined text description for attaching metadata. |
| [`DataType`](/Reference/uCalcBase/Item/DataType) | Retrieves the [`DataType`](/Reference/uCalcBase/DataType/Constructor) object representing the item's type. |
| [`Text`](/Reference/uCalcBase/Item/Text) | Retrieves the original definition string ("source code") used to create the item. |

### 🔎 Behavior & Type Checking
These members allow you to query the characteristics and behavior of a symbol.

| Member | Description |
| :--- | :--- |
| [`IsProperty`](/Reference/uCalcBase/Item/IsProperty) | Checks if the item possesses a specific characteristic (e.g., `Function`, `Operator`, `Locked`). |
| [`Count`](/Reference/uCalcBase/Item/Count) | Gets the number of sub-elements, such as function parameters or array elements. |
| [`Precedence`](/Reference/uCalcBase/Item/Precedence) | Gets or sets the precedence level for an operator, which determines its order of operations. |
| [`TypeOfToken`](/Reference/uCalcBase/Item/TypeOfToken) | Gets or sets the lexical category for an item that is a token definition. |

### 💾 Value Management
These methods provide a bridge for moving data between the host application and the uCalc engine.

| Member | Description |
| :--- | :--- |
| [`Value`](/Reference/uCalcBase/Item/Value) | A versatile method to get or set a variable's value, with overloads for `double` and `string` expressions. |
| `Value<Type>` | A family of type-safe accessors for specific data types (e.g., [`ValueInt32`](/Reference/uCalcBase/Item/ValueInt32), [`ValueBool`](/Reference/uCalcBase/Item/ValueBool), [`ValueStr`](/Reference/uCalcBase/Item/ValueStr)). |
| [`ValueAddr`](/Reference/uCalcBase/Item/ValueAddr) | Gets a direct memory pointer to the item's value for high-performance interoperability. |

### ⛓️ Symbol Table & Lifecycle Management
These methods allow you to manage the symbol itself within the uCalc instance.

| Member | Description |
| :--- | :--- |
| [`Release`](/Reference/uCalcBase/Item/Release) | Permanently removes the symbol from the uCalc instance and frees its resources. |
| [`Rename`](/Reference/uCalcBase/Item/Rename) | Changes the programmatic name of the symbol at runtime. |
| [`NextOverload`](/Reference/uCalcBase/Item/NextOverload) | Retrieves the next item in a sequence of overloaded or shadowed symbols that share the same name. |
| [`Owned`](/Reference/uCalcBase/Item/Owned) | Enables RAII-style automatic memory release for an object, primarily for C++. |
| [`uCalc`](/Reference/uCalcBase/Item/uCalc) | Retrieves the parent [`uCalc`](/Reference/uCalcBase/uCalc/Constructor) instance that owns this item. |

### 🔧 Advanced & Low-Level

| Member | Description |
| :--- | :--- |
| [`FunctionAddress`](/Reference/uCalcBase/Item/FunctionAddress) | Gets or sets the memory address of a native callback function associated with the item. |
| [`Regex`](/Reference/uCalcBase/Item/Regex) | Gets or sets the regular expression pattern for an item that represents a token. |
| [`Handle`](/Reference/uCalcBase/Item/Handle) | Retrieves the internal, low-level identifier for the item (for diagnostics). |
| [`MemoryIndex`](/Reference/uCalcBase/Item/MemoryIndex) | Returns a stable, session-unique integer that identifies the item (for diagnostics). |

**Examples:**

### Example ID: 607

**Description:** Creating a variable in the default instance and retrieving its value.

**Code:**
```pseudocode
NewUsing(uCalc::Item, myVar("Variable: x = 42"))
wl("Created variable '", myVar.@Name(), "' with value: ", myVar.Value())
End Using
```

**Output:**
```
Created variable 'x' with value: 42
```

---

### Example ID: 98

**Description:** uCalc.Item constructor

**Code:**
```pseudocode

// Note that x is defined in the default instance
// while f(x) is defined in the uc instance.
New(uCalc::Item, MyVar("Variable: x = 123"))
New(uCalc::Item, MyFunc(uc, "Function: f(x) = x^2"))

wl(uCalc::@DefaultInstance().Eval("x"))
wl(uc.Eval("f(5)"))

MyVar.Release();
MyFunc.Release();
  
```

**Output:**
```
123
25
```

---

---

## (Constructor) - ID: 652
/doc/reference/classes/ucalc.item/-constructor/

**Description:** Creates a uCalc item, the fundamental object representing any symbol like a function, variable, or operator.

**Remarks:**

The `uCalc.Item` constructor provides a low-level, direct way to create symbols within a uCalc engine instance. An `Item` is the fundamental building block for all named entities in uCalc, acting as a unified handle for functions, variables, operators, data types, and more.

While you can create items directly with this constructor, the recommended approach for most use cases is to use the specialized, more readable methods on the `uCalc` object, such as:
*   [DefineFunction](/uCalc-Documentation/Reference/uCalcBase/uCalc/DefineFunction)
*   [DefineVariable](/uCalc-Documentation/Reference/uCalcBase/uCalc/DefineVariable)
*   [DefineOperator](/uCalc-Documentation/Reference/uCalcBase/uCalc/DefineOperator)

The constructor is functionally equivalent to calling [uCalc.Define](/uCalc-Documentation/Reference/uCalcBase/uCalc/Define) and is primarily useful when you need to construct an `Item` object in a context where you don't have an explicit `uCalc` instance readily available (in which case it uses the default instance).

### ⚙️ Constructor Overloads

1.  **`Item(string definition, ADDR address = 0)`**
    Creates an item in the **default uCalc instance** ([uCalc.Default](/uCalc-Documentation/Reference/uCalcBase/uCalc/Default)).
    *   `definition`: A string containing the full definition, e.g., `"Variable: x = 10"` or `"Function: f(x) = x*2"`.
    *   `address`: (Optional) A memory address for binding the item to a native variable or function.

2.  **`Item(uCalc uc, string definition, ADDR address = 0)`**
    Creates an item within a **specific uCalc instance**.
    *   `uc`: The target `uCalc` engine instance.
    *   The other parameters are the same as above.

3.  **`Item(Item.Empty)`**
    Creates an empty placeholder `Item` object. This is a lightweight handle that does not allocate any significant engine resources. It can be assigned a real item later.

### 💡 Lifetime Management

In C++, an `Item` object can be made to auto-release its resources when it goes out of scope by calling [Owned](/ucalc/item/owned) after it is created. In C#, the standard `using` statement should be used to achieve the same result.

### 🆚 Comparative Analysis: `uCalc.Item` vs. Native Reflection

In languages like C# (.NET), reflection is handled by a family of distinct classes (`MethodInfo`, `FieldInfo`, `PropertyInfo`, etc.). In uCalc, the `Item` class serves as a **unified introspection object** for *all* engine symbols.

| Aspect | .NET Reflection | `uCalc.Item` |
| :--- | :--- | :--- |
| **Object Model** | Separate classes for each symbol type. | A single, unified `Item` class. |
| **Introspection**| Use `is` or `GetType()` checks. | Use `IsProperty()` to check type (e.g., `IsProperty(ItemIs::Function)`). |
| **Creation** | Symbols are defined at compile time. | Symbols are created dynamically at runtime. |
| **Extensibility**| Limited to what the language supports. | Fully extensible with custom functions, operators, and types. |

This unified model simplifies working with the uCalc engine, as you only need to learn one object model (`Item`) to inspect, modify, or release any symbol.

**Examples:**

### Example ID: 607

**Description:** Creating a variable in the default instance and retrieving its value.

**Code:**
```pseudocode
NewUsing(uCalc::Item, myVar("Variable: x = 42"))
wl("Created variable '", myVar.@Name(), "' with value: ", myVar.Value())
End Using
```

**Output:**
```
Created variable 'x' with value: 42
```

---

### Example ID: 98

**Description:** uCalc.Item constructor

**Code:**
```pseudocode

// Note that x is defined in the default instance
// while f(x) is defined in the uc instance.
New(uCalc::Item, MyVar("Variable: x = 123"))
New(uCalc::Item, MyFunc(uc, "Function: f(x) = x^2"))

wl(uCalc::@DefaultInstance().Eval("x"))
wl(uc.Eval("f(5)"))

MyVar.Release();
MyFunc.Release();
  
```

**Output:**
```
123
25
```

---

### Example ID: 99

**Description:** Language-specific auto-releasing of Item object

**Code:**
```pseudocode
// Language specific - auto-releasing Item object
wl("auto-releasing Item (language-specific)")
[vb]#If False[/vb]
{ // MyVar resources will NOT be released when MyVar goes out of scope
   var MyVar = new uCalc::Item("Variable: x = 123");
   // Call MyVar.Release() explicitly if want to release it here
}

{ // MyVar resouces will be released automatically when MyVar goes of scope
   [cs]using var MyVar = new uCalc.Item("Variable: x = 123");[/cs]
   [cpp]uCalc::Item MyVar("Variable: x = 123");[/cpp]
   // No need for MyVar.Release(), it will automatically be released
}
[vb]#End If[/vb]
```

**Output:**
```
auto-releasing Item (language-specific)
```

---

---

## Count = [Int64] - ID: 151
/doc/reference/classes/ucalc.item/count-=-[int64]/

**Description:** Gets the number of sub-elements for an item, such as function parameters, array elements, or operator operands.

**Remarks:**

The `Count()` method is a versatile introspection tool that returns the number of constituent parts for a given [uCalc.Item](/reference/ucalc/item/). Its meaning is context-dependent and changes based on the type of the item being queried.

This is essential for runtime logic that needs to understand the structure of functions, arrays, and other defined symbols.

--- 

## Behavior by Item Type

The value returned by `Count()` corresponds to a different concept for each item type:

| Item Type | `Count()` Returns | Example |
| :--- | :--- | :--- |
| Array | The number of elements. | An array defined as `MyArray[10]` returns `10`. |
| Function | The number of declared parameters. | A function `f(x, y, z=5)` returns `3`. |
| Operator | The number of operands. | An infix operator like `+` returns `2`; a prefix operator like `-` returns `1`. |
| Transformer `Rule` | The number of distinct parts in its pattern. | A rule for `Start {a} {b} End` returns `4`. |
| Token | The number of sub-tokens in a compound token. | A custom token composed of multiple parts. |

--- 

## ⚠️ Special Cases

*   **Variadic Functions**: For functions that accept a variable number of arguments (defined with `...`), `Count()` returns **-1** (or the maximum value for an unsigned integer, like `SIZE_MAX`). This indicates an indeterminate number of parameters. You should check for this special value in your code.

*   **Complex Rules**: For a [Transformer](/reference/transformer) [Rule](/reference/patterns/rules), the count can be non-obvious, especially with nested optional (`[]`) or alternative (`|`) parts. The count generally reflects the number of top-level components in the pattern definition string.

--- 

## 💡 Comparative Analysis

`Item.Count()` provides a unified interface for functionality that is often spread across different properties or methods in other languages.

*   **vs. C#**: In C#, you would use `.Length` for arrays, `.GetParameters().Length` for method reflection, and `.Count()` for collections. uCalc consolidates these concepts into a single `.Count()` method on the versatile `Item` object.

*   **vs. C++**: In C++, you might use `std::size()` for containers or template metaprogramming to get function arity. uCalc's method is a dynamic, runtime equivalent that operates on symbols defined within its engine, providing a simpler and more consistent approach to introspection.

**Examples:**

### Example ID: 610

**Description:** Retrieving the element count of an array and the parameter count of a function.

**Code:**
```pseudocode
var MyArray = uc.DefineVariable("MyArray[10] As Int");
var MyFunc = uc.DefineFunction("MyFunc(a, b, c) = a+b+c");

wl("Array element count: ", MyArray.@Count())
wl("Function parameter count: ", MyFunc.@Count())
```

**Output:**
```
Array element count: 10
Function parameter count: 3
```

---

### Example ID: 611

**Description:** Comprehensive demonstration of Count() across arrays, functions with different parameter types, and operators.

**Code:**
```pseudocode
[head]
[callback MyAverage]
var(double, Total) = 0;
for(int x = 1 to cb.ArgCount())
   Total = Total + cb.Arg(x);
end for
cb.Return(Total / cb.ArgCount());
[/callback]
[body]
var MyArrayA = uc.DefineVariable("MyArrayA[] = {10, 20, 30, 40, 50}");
var MyArrayB = uc.DefineVariable("MyArrayB[15]");
var FunctionA = uc.DefineFunction("FuncA(x, y, z) = x + y + z");
var FunctionB = uc.DefineFunction("FuncB(x, y, a = 12, b = 34) = x+y+a+b");
var FunctionC = uc.DefineFunction("FuncC(x, y ...)", MyAverage);
var FunctionD = uc.DefineFunction("FuncD() = 1+1");

wl("Elements in array (from initializer): ", MyArrayA.@Count())
wl("Elements in array (from size): ", MyArrayB.@Count())
wl("Parameters in FuncA() (fixed): ", FunctionA.@Count())
wl("Parameters in FuncB() (with optional): ", FunctionB.@Count())
wl("Parameters in FuncC() (variadic): ", FunctionC.@Count())
wl("Parameters in FuncD() (none): ", FunctionD.@Count())
wl("Operands in '!' operator (postfix): ", uc.ItemOf("!").@Count())
wl("Operands in '>' operator (infix): ", uc.ItemOf(">").@Count())
```

**Output:**
```
Elements in array (from initializer): 5
Elements in array (from size): 15
Parameters in FuncA() (fixed): 3
Parameters in FuncB() (with optional): 4
Parameters in FuncC() (variadic): -1
Parameters in FuncD() (none): 0
Operands in '!' operator (postfix): 1
Operands in '>' operator (infix): 2
```

---

### Example ID: 613

**Description:** Using Properties with ItemOf to disambiguate between the infix and prefix versions of the '-' operator.

**Code:**
```pseudocode
var infix_minus = uc.ItemOf("-", uCalc::Properties(ItemIs::Infix));
var prefix_minus = uc.ItemOf("-", uCalc::Properties(ItemIs::Prefix));

wl("Operands for infix '-': ", infix_minus.@Count())
wl("Operands for prefix '-': ", prefix_minus.@Count())
```

**Output:**
```
Operands for infix '-': 2
Operands for prefix '-': 1
```

---

### Example ID: 614

**Description:** Demonstrates introspection within a callback, retrieving the parameter count of the calling function.

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   wl("Function '", cb.@Item().@Name(), "' was called.")
   wl("It is defined with ", cb.@Item().@Count(), " parameters.")
[/callback]
[body]
uc.DefineFunction("MyFunc(x, y) As Double", ItemCallback);
uc.EvalStr("MyFunc(1, 2)");
```

**Output:**
```
Function 'myfunc' was called.
It is defined with 2 parameters.
```

---

### Example ID: 45

**Description:** ItemOf selection between infix version of - (minus) operator and unary prefix version with Properties

**Code:**
```pseudocode

// Returns number of operands for the given operators
wl(uc.ItemOf("-", uCalc::Properties(ItemIs::Infix)).@Count())
wl(uc.ItemOf("-", uCalc::Properties(ItemIs::Prefix)).@Count())

[C]// You can pass one property directly in C++ and C#, but not VB
wl(uc.ItemOf("-", ItemIs::Infix).@Count())
wl(uc.ItemOf("-", ItemIs::Prefix).@Count())[/C]
[VB]
// You can pass one property directly in C++ and C#, but not VB
wl(2) // C++ and C# only: uc.ItemOf("-", ItemIs::Infix).@Count();
wl(1) // C++ and C# only: uc.ItemOf("-", ItemIs::Prefix).@Count();[/VB]
```

**Output:**
```
2
1
2
1
```

---

### Example ID: 46

**Description:** Dispaying the number of elements in an array

**Code:**
```pseudocode
[head]
[callback MyAverage]
var(double, Total) = 0;
for(int x = 1 to cb.ArgCount())
   Total = Total + cb.Arg(x);
end for
cb.Return(Total / cb.ArgCount());
[/callback]
[body]
var MyArrayA = uc.DefineVariable("MyArrayA[] = {10, 20, 30, 40, 50}");
var MyArrayB = uc.DefineVariable("MyArrayB[15]");
var FunctionA = uc.DefineFunction("FuncA(x, y, z) = x + y + z");
var FunctionB = uc.DefineFunction("FuncB(x, y, a = 12, b = 34) = x+y+a+b");
var FunctionC = uc.DefineFunction("FuncC(x, y ...)", MyAverage);
var FunctionD = uc.DefineFunction("FuncD() = 1+1");

wl("Elements in MyArrayA: ", MyArrayA.@Count())
wl("Elements in MyArrayB: ", MyArrayB.@Count())
wl("Params in FuncA(): ", FunctionA.@Count())
wl("Params in FuncB(): ", FunctionB.@Count())
wl("Params in FuncC(): ", FunctionC.@Count()) // -1 or 2^n-1 (n=32 or 64)
wl("Params in FuncD(): ", FunctionD.@Count())
wl("Operands in ! operator: ", uc.ItemOf("!").@Count())
wl("Operands in > operator: ", uc.ItemOf(">").@Count())
```

**Output:**
```
Elements in MyArrayA: 5
Elements in MyArrayB: 15
Params in FuncA(): 3
Params in FuncB(): 4
Params in FuncC(): -1
Params in FuncD(): 0
Operands in ! operator: 1
Operands in > operator: 2
```

---

### Example ID: 40

**Description:** Determining properties of an expression part

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   wl("Name: ", cb.@Item().@Name())
   wl("Data type: ", cb.@Item().@DataType().@Name())
   wl("Param count: ", cb.@Item().@Count())
   w("Procedure type: ")
   if (cb.@Item().IsProperty(ItemIs::Operator))
      wl("Operator")
   else if (cb.@Item().IsProperty(ItemIs::Function))
      wl("Function")
   end if
   wl(cb.@Item().@Text())
   wl(cb.@Item().@Description())
   wl("---")
[/callback]
[body]

uc.DefineFunction("AAA() As Double", ItemCallback).@Description("Does this and that");
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).@Description("Does something else");
uc.DefineOperator("{x} CCC {y} As Int32", 0, Associativity::LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");

```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Function: AAA() As Double
Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Function: BBB(x, y, z) As String
Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Operator: {x} CCC {y} As Int32

---
```

---

---

## DataType = [DataType] - ID: 524
/doc/reference/classes/ucalc.item/datatype-=-[datatype]/

**Description:** Gets/sets the DataType object that defines the type characteristics of the Item.

**Remarks:**

The `DataType()` method is a core introspection tool that returns the [DataType](/Reference/uCalcBase/DataType) object associated with any given [Item](/Reference/uCalcBase/Item). This allows you to programmatically inspect the type of a variable, function, or operator at runtime.

### 🎯 Purpose and Usage

Every symbol defined in uCalc (e.g., via [DefineVariable()](/Reference/uCalcBase/uCalc/DefineVariable) or [DefineFunction()](/Reference/uCalcBase/uCalc/DefineFunction)) is represented by an `Item` object. This method allows you to query that `Item` to understand its underlying data type. The returned `DataType` object provides access to key metadata, including:

*   **[Name()](/Reference/uCalcBase/DataType/Name)**: The string name of the type (e.g., `"double"`, `"string"`).
*   **[ByteSize()](/Reference/uCalcBase/DataType/ByteSize)**: The size of the type in bytes.
*   **[IsCompound()](/Reference/uCalcBase/DataType/IsCompound)**: Whether the type is a simple value (like an `int`) or a complex structure (like a `string` or `complex` number).

This is essential for building dynamic systems, such as a custom script editor or a data validation layer, where you need to check the type of a variable before performing an operation.

### 💡 Comparative Analysis: uCalc Introspection vs. Native Reflection

In statically-typed languages, reflection is used to inspect types at runtime.

*   **In C#**: You would use an object's `.GetType()` method.
*   **In C++**: You might use `typeid` or template metaprogramming.

While powerful, these native mechanisms operate on host-language types. uCalc's `Item.DataType()` is different because it operates on the **symbolic types defined within the uCalc engine itself**. This provides a consistent and unified way to inspect the type of a `uCalc` variable, a `uCalc` function's return value, or a parameter, all through the same simple API. It abstracts away the underlying host language, allowing you to reason about your defined symbols in a platform-agnostic way.


### Setter
The `DataType` method assigns a specific data type to an existing [Item](/Reference/uCalcBase/uCalc/Item), giving it semantic meaning within the uCalc engine. While it can be used on any item, its most critical role is to elevate a custom token from a simple text match into a usable **literal value** for the expression parser.

### 🎯 Primary Use Case: Defining Custom Literals

When you define a new token with [uCalc.Tokens.Add](/Reference/uCalcBase/uCalc/ExpressionTokens), you are essentially just defining a regular expression. To make the text captured by that regex usable in an expression (e.g., in a math calculation), you must complete two steps:

1.  Categorize the token as a [Literal](/Reference/Enums/TokenType) using `TokenType::Literal`.
2.  Use this `DataType()` method on the returned token [Item](/Reference/uCalcBase/uCalc/Item) to tell the parser *how* to interpret that literal's value (e.g., as a `String`, `Double`, `Int32`, etc.).

Without this step, the parser would treat the matched text as an unrecognized symbol. By assigning a data type, you integrate your custom syntax directly into the evaluation engine.

### 💡 Other Use Cases

While less common, you can also use this method to change the data type of an existing variable. This is a powerful but potentially unsafe operation, as it can affect expressions that were previously parsed and may rely on the variable's original type.

### 🆚 Why uCalc? (Comparative Analysis)

In traditional compiler development, defining literals is part of a static grammar file processed by a tool like ANTLR or Lex/Flex. The logic to convert the matched text (e.g., `"0xFF"`) into a numeric value is written in a separate, compiled source file.

uCalc's approach is entirely programmatic and dynamic. You can add new literal formats at runtime. `Item.DataType()` is the bridge that connects your dynamically defined regex pattern to the engine's type system, all without external tools or recompilation. This provides superior flexibility for creating adaptable, user-extendable languages.

**Examples:**

### Example ID: 616

**Description:** A simple demonstration of retrieving the data type name from a defined variable.

**Code:**
```pseudocode
var myInt = uc.DefineVariable("myInt As Int");
var myIntType = myInt.@DataType();
wl("Variable 'myInt' has type: ", myIntType.@Name())
```

**Output:**
```
Variable 'myInt' has type: int
```

---

### Example ID: 617

**Description:** A practical example showing how to inspect multiple items and display their type properties, distinguishing between simple and compound types.

**Code:**
```pseudocode
var x = uc.DefineVariable("x = 10.5"); // double
var y = uc.DefineVariable("y = 'hello'"); // string
var z = uc.DefineVariable("z As Complex = 1+2*#i"); // complex

wl("Item: ", x.@Name(), ", Type: ", x.@DataType().@Name(), ", Compound: ", bool(x.@DataType().@IsCompound()))
wl("Item: ", y.@Name(), ", Type: ", y.@DataType().@Name(), ", Compound: ", bool(y.@DataType().@IsCompound()))
wl("Item: ", z.@Name(), ", Type: ", z.@DataType().@Name(), ", Compound: ", bool(z.@DataType().@IsCompound()))
```

**Output:**
```
Item: x, Type: double, Compound: False
Item: y, Type: string, Compound: True
Item: z, Type: complex, Compound: True

```

---

### Example ID: 50

**Description:** Displaying the data type name and size of a variable

**Code:**
```pseudocode
var MyVariable = uc.DefineVariable("MyVariable");
wl("MyVariable type: " + MyVariable.@DataType().@Name())
wl("MyVariable size: ", MyVariable.@DataType().@ByteSize())
```

**Output:**
```
MyVariable type: double
MyVariable size: 8
```

---

### Example ID: 13

**Description:** Passing arg ByHandle to retrieve meta data such as arg data type; and AnyType

**Code:**
```pseudocode
[head]
[callback DisplayArgs]
for(int x = 1 to cb.ArgCount())
   wl(cb.ArgItem(x).ValueStr() + "  Type: " + cb.ArgItem(x).@DataType().@Name())
end for
[/callback]
[body]
uc.DefineFunction("DisplayArgs(ByHandle Arg As AnyType ...)", DisplayArgs);
uc.Eval("DisplayArgs(5, 3+2*#i, 'Hello', True, False, Int16(5+4.1))");
```

**Output:**
```
5  Type: double
3+2i  Type: complex
Hello  Type: string
true  Type: bool
false  Type: bool
9  Type: int16
```

---

### Example ID: 40

**Description:** Determining properties of an expression part

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   wl("Name: ", cb.@Item().@Name())
   wl("Data type: ", cb.@Item().@DataType().@Name())
   wl("Param count: ", cb.@Item().@Count())
   w("Procedure type: ")
   if (cb.@Item().IsProperty(ItemIs::Operator))
      wl("Operator")
   else if (cb.@Item().IsProperty(ItemIs::Function))
      wl("Function")
   end if
   wl(cb.@Item().@Text())
   wl(cb.@Item().@Description())
   wl("---")
[/callback]
[body]

uc.DefineFunction("AAA() As Double", ItemCallback).@Description("Does this and that");
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).@Description("Does something else");
uc.DefineOperator("{x} CCC {y} As Int32", 0, Associativity::LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");

```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Function: AAA() As Double
Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Function: BBB(x, y, z) As String
Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Operator: {x} CCC {y} As Int32

---
```

---

### Example ID: 17

**Description:** DefineVariable examples

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var MyInt = uc.DefineVariable("MyInt As Int");
var MyStr = uc.DefineVariable("MyStr As String");
uc.DefineVariable("OtherStr = 'string type inferred'");
uc.DefineVariable("MyInt16 = Int16(100/3)"); // type inferred
uc.DefineVariable("MyBool = True"); // type inferred
uc.DefineVariable("MyComplex = 3 + 4*#i"); // type inferred

MyVar.Value(123);
MyInt.ValueInt32(456);
MyStr.ValueStr("This is a test");

wl("MyVar = " + uc.EvalStr("MyVar"))
wl("MyInt = " + uc.EvalStr("MyInt"))
wl("MyStr = " + uc.EvalStr("MyStr"))
wl("OtherStr = " + uc.EvalStr("OtherStr"))
wl("MyInt16 = " + uc.EvalStr("MyInt16"))
wl("MyBool = " + uc.EvalStr("MyBool"))
wl("MyComplex = " + uc.EvalStr("MyComplex"))
wl("---")
wl(MyVar.Value())
wl(MyInt.ValueInt32())
wl(MyStr.ValueStr())
wl("---")
wl(uc.ItemOf("MyVar").@DataType().@Name())
wl(uc.ItemOf("MyInt").@DataType().@Name())
wl(uc.ItemOf("MyStr").@DataType().@Name())
wl(uc.ItemOf("OtherStr").@DataType().@Name())
wl(uc.ItemOf("MyInt16").@DataType().@Name())
wl(uc.ItemOf("MyBool").@DataType().@Name())
wl("---")

var Expression = "x^2 * 10";
var VarX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse(Expression);

w("Expression = ")
wl(Expression)
for (int x = 1 to 10)
   VarX.Value(x); // In C++ you can skip this by passing &x to DefineVariable
   wl("x = " + VarX.ValueStr() + "  Result = " + ParsedExpr.EvaluateStr())
end for

ParsedExpr.Release();
VarX.Release();
```

**Output:**
```
MyVar = 123
MyInt = 456
MyStr = This is a test
OtherStr = string type inferred
MyInt16 = 33
MyBool = true
MyComplex = 3+4i
---
123
456
This is a test
---
double
int
string
string
int16
bool
---
Expression = x^2 * 10
x = 1  Result = 10
x = 2  Result = 40
x = 3  Result = 90
x = 4  Result = 160
x = 5  Result = 250
x = 6  Result = 360
x = 7  Result = 490
x = 8  Result = 640
x = 9  Result = 810
x = 10  Result = 1000
```

---

### Example ID: 100

**Description:** Setting a token data type

**Code:**
```pseudocode

// This example makes the # character behave the same way as quotes
uc.@ExpressionTokens().Add("#([^#]*)#", TokenType::Literal, "", 1).@DataType(uc.DataTypeOf("String"));
wl(uc.EvalStr("#Hello # + #World#"))
```

**Output:**
```
Hello World
```

---

---

## Description = [string] - ID: 520
/doc/reference/classes/ucalc.item/description-=-[string]/

**Description:** Gets or sets a user-defined text description for a uCalc symbol, useful for attaching metadata and for debugging.

**Remarks:**

# 🏷️ Attaching Metadata with Description

The `Description` property provides a powerful way to attach arbitrary string metadata to any [Item](/Reference/uCalcBase/Item/Constructor). This is invaluable for debugging, creating self-documenting configurations, and identifying specific components at runtime.

---

## ⚙️ Getter and Setter Behavior

This property functions as both a getter and a setter, accessed using the uCalc property syntax.

*   **Getter**: Retrieves the current description. If no description has been set, it returns an empty string.
    [pseudocode]`var desc = myItem.@Description();`

*   **Setter**: Assigns a new description string to the item.
    [pseudocode]`myItem.@Description("This is a test variable");`

### ✨ Fluent Interface

The setter supports a **fluent interface** by returning the `Item` object itself. This allows you to chain multiple configuration calls together in a single, readable statement.

```pseudocode
// Chaining .Description() with .Rename()
var myItem = uc.DefineFunction("f() = 1").@Description("My Function").Rename("my_func");
```

---

## 🎯 Core Use Cases

*   **💡 Debugging**: When working with a [Transformer](/Reference/uCalcBase/uCalc/NewTransformer), you can assign a unique description to each [Rule](/Reference/Patterns/Introduction/Rules). During processing, you can query the rule that generated a match to understand exactly why a transformation occurred.

*   **📦 Runtime Metadata**: Attach contextual information directly to functions, variables, or operators. This allows you to build introspection tools that can inspect a `uCalc` instance and generate documentation or build a dynamic user interface.

## ✨ Special Behavior: Tokens

When a token is defined (e.g., via [uCalc.Tokens.Add()](/Reference/uCalcBase/Tokens/Add)), its `Description` is automatically populated with the string name of its assigned [TokenType](/Reference/Enums/TokenType) (e.g., "Whitespace", "Literal"). This provides immediate, built-in metadata for lexical components.

## ⚖️ Comparative Analysis

Without an integrated `Description` property, developers often resort to less ideal solutions for tracking metadata:

*   **vs. External Dictionaries**: Managing a `Dictionary<Item, string>` is cumbersome. It requires manual synchronization, and if an `Item` is released, the dictionary entry can become a memory leak.
*   **vs. Wrapper Classes**: Creating a custom class just to add a description field adds significant boilerplate code.
*   **vs. Code Comments**: Standard code comments are static and cannot be accessed by the program at runtime. An `Item`'s description is dynamic data that can be queried and displayed by your application.

uCalc's integrated approach is superior because the metadata is tightly coupled with the object itself and is consistently available across the object model. This creates a unified, easy-to-use system for runtime introspection.

**Examples:**

### Example ID: 622

**Description:** Attaches and retrieves a simple metadata description from a variable.

**Code:**
```pseudocode
var myVar = uc.DefineVariable("x = 10");
myVar.@Description("Represents the user's current score.");

wl("Variable Name: ", myVar.@Name())
wl("Description: ", myVar.@Description())
```

**Output:**
```
Variable Name: x
Description: Represents the user's current score.
```

---

### Example ID: 40

**Description:** Determining properties of an expression part

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   wl("Name: ", cb.@Item().@Name())
   wl("Data type: ", cb.@Item().@DataType().@Name())
   wl("Param count: ", cb.@Item().@Count())
   w("Procedure type: ")
   if (cb.@Item().IsProperty(ItemIs::Operator))
      wl("Operator")
   else if (cb.@Item().IsProperty(ItemIs::Function))
      wl("Function")
   end if
   wl(cb.@Item().@Text())
   wl(cb.@Item().@Description())
   wl("---")
[/callback]
[body]

uc.DefineFunction("AAA() As Double", ItemCallback).@Description("Does this and that");
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).@Description("Does something else");
uc.DefineOperator("{x} CCC {y} As Int32", 0, Associativity::LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");

```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Function: AAA() As Double
Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Function: BBB(x, y, z) As String
Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Operator: {x} CCC {y} As Int32

---
```

---

### Example ID: 625

**Description:** Setting and retrieving a description for a single variable Item.

**Code:**
```pseudocode
var myVar = uc.DefineVariable("x = 10");
myVar.@Description("This is a test variable");

wl("Name: ", myVar.@Name())
wl("Description: ", myVar.@Description())
```

**Output:**
```
Name: x
Description: This is a test variable
```

---

---

## FunctionAddress = [OpCallback] - ID: 153
/doc/reference/classes/ucalc.item/functionaddress-=-[opcallback]/

**Description:** Gets or sets the memory address of a native callback function associated with a uCalc symbol, enabling implementation sharing and runtime hot-swapping.

**Remarks:**

# 🔗 FunctionAddress Property

The `FunctionAddress` property gets or sets the memory address of the native callback function associated with a uCalc [Item](/Reference/uCalcBase/Item/Constructor). This provides a powerful link between a symbol defined in the uCalc engine (like a function or operator) and a function in the host application's native code (C#, C++, VB).

It is a key feature for advanced scenarios involving dynamic behavior, performance optimization, and code reuse.

---
## 📖 Getter: Reusing Implementations

When used as a getter, `FunctionAddress` retrieves the address of the native callback implementing a function's logic.

[pseudocode]`var floorAddr = uc.ItemOf("Floor").@FunctionAddress();`

The most common use case is to create a new function or operator that reuses the logic of an existing native-bound function. This allows you to define a new symbol with a different name or properties while pointing it to the same high-performance native code.

### `FunctionAddress` vs. `CreateAlias`
It is crucial to understand the difference between sharing a function address and creating an alias with [CreateAlias](/Reference/uCalcBase/uCalc/CreateAlias).

*   **`CreateAlias("New", "Old")`**: Creates a new name that points to the *exact same* [Item](/Reference/uCalcBase/Item/Constructor). It is a simple synonym.
*   **Using `FunctionAddress`**: You can have a *completely new and independent* [Item](/Reference/uCalcBase/Item/Constructor) that just happens to point to the same native callback address. This new item can have its own distinct properties.

---
## ✍️ Setter: Hot-Swapping Implementations

When used as a setter, `FunctionAddress` provides a powerful mechanism to hot-swap the native code implementation of an `Item` at runtime.

[pseudocode]`uc.ItemOf("MyRound").@FunctionAddress(ceilAddr);`

This decouples a symbol's name from its concrete implementation, enabling advanced dynamic behaviors:

*   **Dynamic Aliasing**: Redirect one function to another. The practical example demonstrates making a custom `MyRound` function point first to `Floor` and then to `Ceil`.
*   **Mode Switching**: Switch between different implementations of a function based on context (e.g., a fast, unsafe calculation in performance mode vs. a slower, bounds-checked version in debug mode).
*   **Runtime Plugin Systems**: Load functions from external libraries (DLLs/shared objects) at runtime and bind them to existing function names within the uCalc engine.

---
## 💡 Why uCalc? (Comparative Analysis)

uCalc abstracts the platform-specific details of function pointers (C++) and delegates (C#) into a consistent API. This property allows you to manipulate these bindings programmatically at runtime, a task that is typically static and compile-time-dependent in native languages. While delegates and function pointers can be reassigned, uCalc provides a high-level, symbolic way to manage these bindings. You can retrieve an `Item` by its string name using [ItemOf](/Reference/uCalcBase/uCalc/ItemOf) and then change its implementation, a level of dynamism not typically available for compiled functions.

**Examples:**

### Example ID: 5

**Description:** Defining another function using the same callback address of existing one

**Code:**
```pseudocode
uc.DefineFunction("MyRound(x)", uc.ItemOf("Floor").@FunctionAddress());
wl(uc.Eval("MyRound(2.5)"))

uc.ItemOf("MyRound").SetFunctionAddress(uc.ItemOf("Ceil").@FunctionAddress());
wl(uc.Eval("MyRound(2.5)"))
```

**Output:**
```
2
3
```

---

---

## Handle - ID: 154
/doc/reference/classes/ucalc.item/handle/

**Description:** Retrieves the internal, low-level identifier for the uCalc item.

**Syntax:** Handle()
**Return:** ADDR - Returns the internal handle of the current `Item`. While typed as an `Item` for convenience, it represents an opaque identifier whose numeric value is not guaranteed to be consistent across application runs.
**Remarks:**

This method retrieves the internal handle of an `Item` object. Handles are opaque, pointer-like identifiers used by the uCalc library to manage objects. This method is primarily intended for advanced debugging and internal diagnostics.

### What is a Handle?
A handle is a unique, low-level identifier for a specific uCalc `Item` in memory. Its actual numeric value is unpredictable and can change every time the application runs. It should not be stored or used for serialization.

For a stable and predictable identifier, use [MemoryIndex](/reference/ucalcbase/item/memoryindex) instead.

--- 

### ⚖️ `Handle` vs. `MemoryIndex`

It is crucial to understand the difference between these two identifiers:

| Feature | `Handle` | `MemoryIndex` |
| :--- | :--- | :--- |
| **Stability** | **Volatile**. Changes between application runs. | **Stable**. Predictable and sequential. |
| **Uniqueness** | Guaranteed unique for the object's lifetime. | Can be **recycled** after an object is released. |
| **Purpose** | Low-level object identification for the C++ core. | High-level diagnostics and tracking object lifetime. |
| **Use Case** | Advanced debugging. | Identifying specific instances for logging or in diagnostic tools. |

--- 

### Comparative Analysis

In C# or C++, you can think of a handle as being similar to an `IntPtr` or a raw pointer (`void*`). It refers to a specific memory location managed by the uCalc engine. However, unlike raw pointers, the uCalc handle is managed within the uCalc ecosystem. The key takeaway for developers is to use `MemoryIndex` for any form of stable identification and to treat the `Handle` as a transient, internal-only value.

**Examples:**

---

## IsProperty - ID: 155
/doc/reference/classes/ucalc.item/isproperty/

---

## IsProperty(ItemIs) - ID: 156
/doc/reference/classes/ucalc.item/isproperty/isproperty-itemis/

**Description:** Checks if a uCalc item possesses a specific characteristic, such as being a function, variable, or read-only.

**Syntax:** IsProperty(ItemIs)
**Parameters:**
itemProperty - ItemIs - The property to check for, specified as a member of the `ItemIs` enumeration.
**Return:** bool - Returns `true` if the item has the specified property; otherwise, `false`.
**Remarks:**

### 🧐 Introspection with IsProperty

The `IsProperty` method is the primary tool for runtime introspection of a uCalc [Item](/reference/ucalc/item). It allows you to check if an item possesses a specific characteristic or "flag," enabling you to write code that adapts to the type and state of any defined symbol.

This is more granular than a simple type check. An [Item](/reference/ucalc/item) can have multiple properties simultaneously. For instance, an infix operator will have the `Operator`, `Infix`, and `FunctionOrOperator` properties, all of which will return `true` when checked.

### ⚙️ Common Properties

Use this function with members of the [ItemIs](/reference/enums/itemis) enum to check for common characteristics:

| Property | `IsProperty(ItemIs::...)` | Returns `true` for... |
| :--- | :--- | :--- |
| **Function** | `Function` | Items created with [DefineFunction](/reference/ucalc/ucalc/definefunction). |
| **Variable** | `Variable` | Items created with [DefineVariable](/reference/ucalc/ucalc/definevariable). |
| **Operator** | `Operator` | Items created with [DefineOperator](/reference/ucalc/ucalc/defineoperator). |
| **Read-Only** | `Locked` | Constants or items that cannot be modified. |
| **Non-Existent**| `NotFound` | An empty item handle returned by [ItemOf](/reference/ucalc/ucalc/itemof) when a search fails. |
| **Infix** | `Infix` | An operator that appears between two operands (e.g., `*` in `3*4`). |
| **Prefix** | `Prefix` | An operator that appears before an operand (e.g., `-` in `-5`). |
| **Postfix** | `Postfix` | An operator that appears between two operands (e.g., `++` in `x++`). |
| **Data type** | `DataType` | A data type. |
| **Array** | `Array` | An array. |
| **Error handler** | `ErrorHandler` | An error handler. |
| **Transformer** | `Transformer` | A transformer. |
| **Formatter** | `Format` | A string formatter. |
| **Function or Operator** | `FunctionOrOperator` | Either a function or a operator. |
| **Right to left associative** | `RightToLeft` | An operator that is right-to-left-associative. |
| **Address owner** | `AddressOwner` | False when the address is owned by the host program. |
| **Alias** | `Alias` | An alias for another item. |
| **Search** | `Search` | A search item. |
| **Case-sensitive** | `CaseSensitive` | A case-sensitive item. |
| **Quoted text** | `QuotedText` | Quoted text. |

### 💡 Why uCalc? (Comparative Analysis)

This method provides a more detailed level of introspection than typical type-checking systems.

*   **vs. C#/.NET Reflection**: In .NET, you might check `MethodInfo.IsStatic` or `typeof(MyClass).IsInterface`. uCalc's `IsProperty` is analogous but tailored to its own, more dynamic object model. The key difference is that uCalc's properties describe an item's role and state within the parser (`Infix`, `Locked`) rather than just its underlying class.

*   **vs. Dynamic Languages (Python/JavaScript)**: Functions like Python's `isinstance()` or JavaScript's `typeof` check an object's class or primitive type. `IsProperty` is fundamentally different because it checks for *features* or *flags*. An `Item` is always an `Item`, but its properties define what it *does*. This allows for a more flexible and powerful system where characteristics are not rigidly tied to a class hierarchy.

This feature-based introspection makes it easy to build powerful tools like custom debuggers, expression visualizers, or intelligent autocompletion engines on top of the uCalc engine.

**Examples:**

### Example ID: 47

**Description:** Determining whether items are functions, or arrays, etc.

**Code:**
```pseudocode
uc.DefineVariable("MyVar");

wl(uc.EvalStr("'Cos is a function? '"), bool(uc.ItemOf("Cos").IsProperty(ItemIs::Function)))
wl(uc.EvalStr("'Cos is a variable? '"), bool(uc.ItemOf("Cos").IsProperty(ItemIs::Variable)))
wl(uc.EvalStr("'Cos is an operator? '"), bool(uc.ItemOf("Cos").IsProperty(ItemIs::Operator)))
wl(uc.EvalStr("'MyVar is a function? '"), bool(uc.ItemOf("MyVar").IsProperty(ItemIs::Function)))
wl(uc.EvalStr("'MyVar is a variable? '"), bool(uc.ItemOf("MyVar").IsProperty(ItemIs::Variable)))
wl(uc.EvalStr("'MyVar is an operator? '"), bool(uc.ItemOf("MyVar").IsProperty(ItemIs::Operator)))
wl(uc.EvalStr("'+ is a function? '"), bool(uc.ItemOf("+").IsProperty(ItemIs::Function)))
wl(uc.EvalStr("'+ is a variable? '"), bool(uc.ItemOf("+").IsProperty(ItemIs::Variable)))
wl(uc.EvalStr("'+ is an operator? '"), bool(uc.ItemOf("+").IsProperty(ItemIs::Operator)))
wl(uc.EvalStr("'Cos not found? '"), bool(uc.ItemOf("Cos").IsProperty(ItemIs::NotFound)))
wl(uc.EvalStr("'XYZABC not found? '"), bool(uc.ItemOf("XYZABC").IsProperty(ItemIs::NotFound)))
```

**Output:**
```
Cos is a function? True
Cos is a variable? False
Cos is an operator? False
MyVar is a function? False
MyVar is a variable? True
MyVar is an operator? False
+ is a function? False
+ is a variable? False
+ is an operator? True
Cos not found? False
XYZABC not found? True
```

---

### Example ID: 40

**Description:** Determining properties of an expression part

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   wl("Name: ", cb.@Item().@Name())
   wl("Data type: ", cb.@Item().@DataType().@Name())
   wl("Param count: ", cb.@Item().@Count())
   w("Procedure type: ")
   if (cb.@Item().IsProperty(ItemIs::Operator))
      wl("Operator")
   else if (cb.@Item().IsProperty(ItemIs::Function))
      wl("Function")
   end if
   wl(cb.@Item().@Text())
   wl(cb.@Item().@Description())
   wl("---")
[/callback]
[body]

uc.DefineFunction("AAA() As Double", ItemCallback).@Description("Does this and that");
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).@Description("Does something else");
uc.DefineOperator("{x} CCC {y} As Int32", 0, Associativity::LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");

```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Function: AAA() As Double
Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Function: BBB(x, y, z) As String
Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Operator: {x} CCC {y} As Int32

---
```

---

---

## IsProperty(ItemIs, bool) - ID: 157
/doc/reference/classes/ucalc.item/isproperty/isproperty-itemis,-bool/

**Description:** Dynamically enables or disables a behavioral property for a uCalc item, such as making it read-only or toggling its active state.

**Syntax:** IsProperty(ItemIs, bool)
**Parameters:**
itemProperty - ItemIs - The property to set, specified as a member of the [ItemIs](/Reference/Enums/ItemIs) enumeration.
value - bool - A boolean indicating whether to enable (`true`) or disable (`false`) the property.
**Return:** Item - Returns the current [Item](/Reference/uCalcBase/uCalc/Item) object to allow for a fluent interface and method chaining.
**Remarks:**

The `IsProperty` method acts as a setter for the boolean flags that control an [Item's](/Reference/uCalcBase/uCalc/Item) behavior. It allows you to dynamically modify an item's characteristics at runtime after it has been defined.

This is the setter overload; for checking a property's status, see the getter overload: `IsProperty(ItemIs)`.

### ⚙️ How It Works

Properties are like switches that can be turned on (`true`) or off (`false`). By setting a property, you can alter how uCalc treats an item during parsing, evaluation, or transformation.

### ✨ Common Use Cases

*   **Creating Constants**: Make a variable read-only by setting the `ItemIs::Locked` property. This is a more programmatic way to achieve what [DefineConstant()](/Reference/uCalcBase/uCalc/DefineConstant) does.
*   **Controlling Transformer Rules**: Dynamically enable or disable a `Transformer` rule by toggling its `ItemIs::Active` property.
*   **Configuring Behavior**: Change a rule's matching logic at runtime by setting properties like `ItemIs::CaseSensitive` or `ItemIs::RewindOnChange`.

### Fluent Interface

This method returns the `Item` object itself, which allows for a **fluent interface** or **method chaining**. You can define an item and immediately set a property on it in a single, readable line of code.

```pseudocode
// Define a variable and immediately lock it
var pi = uc.DefineVariable("pi = 3.14159").IsProperty(ItemIs::Locked, true);
```

### 🆚 Comparative Analysis

In statically-typed languages like C#, an object's behavior is often fixed at compile time (e.g., using the `readonly` keyword). While reflection can be used to modify properties, it is often complex and slow.

In dynamic languages like Python, you can change object attributes freely (`my_obj.is_active = False`), but this lacks the structured, enumerated property system of uCalc.

uCalc's `IsProperty` method provides the best of both worlds: the flexibility of a dynamic language with the clarity and safety of an enumerated property system ([ItemIs](/Reference/Enums/ItemIs)), all accessible at runtime.

**Examples:**

### Example ID: 101

**Description:** Changing an item's property

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("x = 100");
wl(uc.EvalStr("x"))

uc.EvalStr("x = 200");
wl(uc.EvalStr("x")) // x can change here

// Locking an item prevents it from being changed
MyVar.IsProperty(ItemIs::Locked, true);

uc.EvalStr("x = 300"); // x cannot change here
wl(uc.EvalStr("x")) // x retains the previous value




```

**Output:**
```
100
200
200
```

---

---

## MemoryIndex = [int] - ID: 607
/doc/reference/classes/ucalc.item/memoryindex-=-[int]/

**Description:** Returns a stable, predictable index for the object, useful for diagnostics and tracking object lifecycles.

**Remarks:**

The `MemoryIndex` method returns a stable, predictable integer that uniquely identifies an object within its class for the duration of its lifetime. It is primarily a tool for advanced debugging, diagnostics, and tracking object lifecycles.

### Key Characteristics
*   **Predictable**: Unlike a memory address, the `MemoryIndex` is assigned sequentially. The first `Item` created will have index 1, the second will have index 2, and so on.
*   **Stable**: The index of an object will not change during its lifetime.
*   **Recycled**: When an object is released (e.g., via `.Release()`), its `MemoryIndex` is returned to a pool and will be reused by the next object of the same type that is created. This is a key behavior to understand when debugging.

---

### `MemoryIndex` vs. `Handle`

It is crucial to distinguish `MemoryIndex` from an object's [Handle](/reference/ucalcbase/item/handle).

| Feature        | `MemoryIndex`                                    | `Handle`                                       |
| :---           | :---                                             | :---                                           |
| **Stability**  | **Stable & Predictable**. Sequential integers.   | **Volatile**. A memory address that changes between runs. |
| **Uniqueness** | Unique for its lifetime, but **recycled** after release. | Guaranteed unique for the object's lifetime. Never recycled. |
| **Purpose**    | High-level diagnostics, logging, lifecycle tracking. | Low-level object identification for the C++ core. |
| **Use Case**   | "Is this the same object *slot* I saw before?"   | "What is the exact memory reference for this object?" |

---

### 💡 Why uCalc? (Comparative Analysis)

*   **vs. C# `GetHashCode()`**: While `GetHashCode()` provides an integer, it is not guaranteed to be unique, nor is it stable between application runs. `MemoryIndex` is deterministic and predictable within a single run.
*   **vs. C++ Pointers**: A raw pointer address in C++ is volatile, similar to uCalc's `Handle`. `MemoryIndex` provides a higher-level, more stable identifier that is independent of memory layout.

The `MemoryIndex` gives developers a reliable tool for introspection that bridges the gap between low-level memory addresses and high-level object references.

**Examples:**

---

## Name = [string] - ID: 525
/doc/reference/classes/ucalc.item/name-=-[string]/

**Description:** Retrieves the programmatic name of a defined symbol, such as a function, variable, or operator.

**Remarks:**

The `Name()` method provides runtime access to the programmatic name of a uCalc `Item`. This is the primary way to perform introspection on the symbols defined within a uCalc instance.

Items such as functions, operators, variables, and data types are typically assigned a name when they are created. This method retrieves that name as a string.

### Why is this useful?

*   **Runtime Introspection**: You can programmatically list and inspect all available functions, variables, or operators. This is useful for building dynamic UIs, such as a function browser or an auto-complete feature.
*   **Debugging and Logging**: When iterating through lists of items (e.g., from [ListOfItems](/Reference/uCalcBase/uCalc/ListOfItems)), you can print their names to understand the current state of the parser engine.
*   **Metadata Retrieval**: The name is a key piece of metadata that, when combined with other `Item` properties, allows for sophisticated analysis of the uCalc environment.

An item's name can be changed programmatically using [Rename](/Reference/uCalcBase/Item/Rename).

### Comparative Analysis

`Item.Name()` is conceptually similar to reflection mechanisms in other languages:

*   **vs. C# Reflection**: It is analogous to the `MemberInfo.Name` property, which returns the name of a class member (method, property, etc.) at runtime.
*   **vs. Python**: It serves the same purpose as the `__name__` attribute on functions and classes.

By providing this functionality, uCalc allows for a high degree of meta-programming and introspection that is common in more dynamic languages.


**Examples:**

### Example ID: 644

**Description:** A simple demonstration of retrieving the name from a defined variable's Item object.

**Code:**
```pseudocode
// Define a variable and retrieve its name from the Item object.
var myVarItem = uc.DefineVariable("MyCoolVariable = 10");
wl("Item name: ", myVarItem.@Name())
```

**Output:**
```
Item name: mycoolvariable
```

---

### Example ID: 646

**Description:** Internal Test: Verifies correct name retrieval for symbolic operators, internal tokens, and empty items.

**Code:**
```pseudocode
// Internal Test: Verifying names of different item types and edge cases.

// 1. Operator with symbolic name
var plusOp = uc.ItemOf("+", [c]ItemIs::Infix[/c][vb]uCalc.Properties(ItemIs::Infix)[/vb]);
wl("Operator Name: '", plusOp.@Name(), "'")

// 2. Token with internal name
var token = uc.@ExpressionTokens()[TokenType::AlphaNumeric];
wl("Token Name: '", token.@Name(), "'")

// 3. Empty/invalid item
var emptyItem = uc.ItemOf("NonExistentItem");
wl("Empty Item Name: '", emptyItem.@Name(), "'")
wl("Is Found: ", bool([c]![/c]emptyItem.IsProperty(ItemIs::NotFound)[vb]==False[/vb]))
```

**Output:**
```
Operator Name: '+'
Token Name: '_token_alphanumeric'
Empty Item Name: ''
Is Found: False
```

---

### Example ID: 647

**Description:** Introspecting a function or operator from within a callback to retrieve its metadata.

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   wl("Name: " + cb.@Item().@Name())
   wl("Data type: " + cb.@Item().@DataType().@Name())
   wl("Param count: " + to_string(cb.@Item().@Count()))
   w("Procedure type: ")
   if (cb.@Item().IsProperty(ItemIs::Operator))
      wl("Operator")
   else if (cb.@Item().IsProperty(ItemIs::Function))
      wl("Function")
   end if
   wl(cb.@Item().@Text())
   wl(cb.@Item().@Description())
   wl("---")
[/callback]
[body]

uc.DefineFunction("AAA() As Double", ItemCallback).@Description("Does this and that");
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).@Description("Does something else");
uc.DefineOperator("{x} CCC {y} As Int32", 0, Associativity::LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");

```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Function: AAA() As Double
Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Function: BBB(x, y, z) As String
Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Operator: {x} CCC {y} As Int32

---
```

---

### Example ID: 40

**Description:** Determining properties of an expression part

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   wl("Name: ", cb.@Item().@Name())
   wl("Data type: ", cb.@Item().@DataType().@Name())
   wl("Param count: ", cb.@Item().@Count())
   w("Procedure type: ")
   if (cb.@Item().IsProperty(ItemIs::Operator))
      wl("Operator")
   else if (cb.@Item().IsProperty(ItemIs::Function))
      wl("Function")
   end if
   wl(cb.@Item().@Text())
   wl(cb.@Item().@Description())
   wl("---")
[/callback]
[body]

uc.DefineFunction("AAA() As Double", ItemCallback).@Description("Does this and that");
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).@Description("Does something else");
uc.DefineOperator("{x} CCC {y} As Int32", 0, Associativity::LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");

```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Function: AAA() As Double
Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Function: BBB(x, y, z) As String
Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Operator: {x} CCC {y} As Int32

---
```

---

### Example ID: 70

**Description:** Displays the complete list of default token definitions, showing their type, internal name, and regex pattern.

**Code:**
```pseudocode
// Lists all tokens currently defined for the expression evaluator.

wl("Token Count: ", uc.@ExpressionTokens().@Count())
wl("")
wl("Index  Type  Name: regex")
wl("========================")
var Tokens = uc.@ExpressionTokens();
foreach (var token in Tokens)
   w(Tokens.IndexOf(token))
   wl("  ", token.@Description(), "  ", token.@Name(), ": ", token.@Regex())
end for

// Note that the expression evaluator token list has a few extra tokens,
// related to hex/bin/oct notation, string interpolation, and imaginary number
// notation, which are not found in the default Transformer token list.
```

**Output:**
```
Token Count: 30

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
27  literal  _token_imaginaryunit: #i
28  tokentransform  _token_binaryhexoctalnotation: #[bho][0-9A-F]+
29  tokentransform  _token_stringinterpolationquote: \$['"]
```

---

### Example ID: 107

**Description:** uCalc.Items

**Code:**
```pseudocode
// Note: Some items in this list (like bool, or int*) appear more than once or out of chronological
// order because they are aliases (like bool, which is also an alias for boolean)
foreach(var item in uc.@Items())
   wl(item.@Name())
end foreach
```

**Output:**
```
!
%
&
&&
*
+
,
-
/
<
<<
<=
<>
=
==
>
>=
>>
\
^
_enduserformattedoutput
_newline
_token_alphanumeric
_token_argseparator
_token_binaryhexoctalnotation
_token_catchall
_token_catchall_utf8_other
_token_curlybrace
_token_curlybrace_close
_token_floatnumber
_token_imaginaryunit
_token_line
_token_memberaccess
_token_newline
_token_parenthesis
_token_parenthesis_close
_token_punctuation
_token_quotechar
_token_quotechar_double
_token_quotechar_single
_token_quotechar_tripledouble
_token_reducible
_token_reducible2
_token_semicolon
_token_squarebracket
_token_squarebracket_close
_token_string_doublequoted
_token_string_singlequoted
_token_string_tripledoublequoted
_token_stringinterpolationquote
_token_variableargs
_token_whitespace
_ucalc_lib_is32
_ucalc_lib_is64
_ucalc_lib_release_timestamp
_ucalc_lib_version
abs
acos
acosh
addptr
addressof
and
andalso
anytype
append
append_copy
arg
argcount
asc
asin
asinh
atan
atan2
atanh
back
baseconvert
bin
bitand
bitor
bool
bool
int8u
c_str
cbrt
ceil
chr
clear
compare
complex
conj
contains
copysign
cos
cosh
define
doloop
double
endswith
erase
erase_copy
erf
erfc
error
eval
evalstr
evaluate
evaluateint
evaluatestr
exp
exp2
expm1
exprptr
fabs
false
fdim
file
filesize
fill
find_first_not_of
find_first_of
find_last_not_of
find_last_of
single
floor
fmax
fmin
fmod
forloop
format
fpclassify
frac
frexp
fromto
goto
hex
hypot
iif
ilogb
imag
indexof
inf
insert
insert_copy
int
int16
int16u
int
int32u
int64
int64u
int8
int8u
int
isfinite
isinf
isnan
isnormal
lastindexof
lastrandomnumber
lcase
ldexp
length
lgamma
llrint
llround
log
log10
log1p
log2
logb
lrint
lround
ltrim
max
min
mod
modf
nan
nearbyint
nextafter
nexttoward
norm
not
oct
omnitype
or
orelse
padleft
padright
parse
pointer
polar
pop
pow
precedence
proj
push
rand
randfromsameseed
randomnumber
randomseed
real
remainder
remquo
repeat
replace
replace_copy
reset
rint
round
rtrim
sametypeas
scalbln
scalbn
setvar
sgn
signbit
sin
single
sinh
size_t
sizeof
sort
sqr
sqrt
startswith
str
string
substr
subtractptr
swap
tan
tanh
tgamma
trim
true
trunc
ucalcinstance
ucase
valueat
valueattype
void
xor
|
||
~
```

---

### Example ID: 170

**Description:** Token(TokenType)

**Code:**
```pseudocode
wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Name())
wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex())
wl("")

// Note: In C# or VB you can simply use [TokenType::Literal, n]
// instead of ByType(TokenType::Literal, n)
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 0).@Name())
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 1).@Name())
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 2).@Name())
```

**Output:**
```
_token_alphanumeric
[a-zA-Z_][a-zA-Z0-9_]*

_token_string_singlequoted
_token_string_doublequoted
_token_string_tripledoublequoted
```

---

---

## NextOverload - ID: 526
/doc/reference/classes/ucalc.item/nextoverload/

**Description:** Retrieves the next item in a sequence of overloaded or shadowed symbols that share the same name.

**Syntax:** NextOverload()
**Return:** Item - Returns the next `Item` object in the overload chain. If there are no more overloads, it returns an empty `Item` for which `IsProperty(ItemIs::NotFound)` is true.
**Remarks:**

The `NextOverload` method provides a way to traverse the chain of items that share the same name within a uCalc instance. When multiple functions, operators, or even variables are defined with the same name, they form an implicit, stack-like list. This method acts as an iterator to walk through that list.

### Core Concept: The Overload Chain

Think of symbols with the same name as a linked list:

1.  **Head of the List**: Calling [ItemOf("MySymbol")](/Reference/uCalcBase/uCalc/ItemOf) retrieves the most recently defined item—the head of the chain.
2.  **Walking the Chain**: Calling `NextOverload()` on that item returns the previously defined item with the same name.
3.  **End of the Chain**: When no more items with that name exist, `NextOverload()` returns an empty `Item` object. You can check for this termination condition using `item.NotEmpty()` or `item.IsProperty(ItemIs::NotFound) == false`.

This mechanism is essential for introspection and managing complex symbol tables.

### ⚙️ Primary Use Cases

*   **Inspecting Function/Operator Overloads**: The most common use case is to programmatically discover all defined overloads for a function or operator, as shown in the practical example below.
*   **Accessing Shadowed Variables**: If you redefine a variable, the old definition is not destroyed but *shadowed*. `NextOverload` allows you to access the previous value or definition.
*   **Resolving Transformer Rule Precedence**: When multiple [Transformer](/Reference/uCalcBase/uCalc/NewTransformer) rules start with the same anchor text, the most recently defined rule takes precedence. They form an overload chain that you can inspect with this method.

### Typical Loop Structure

A common pattern for iterating through all overloads is a `while` loop:

```pseudocode
var item = uc.ItemOf("SymbolName");

while (item.NotEmpty())
   wl(item.Text()); // Process the current item
   item = item.NextOverload(); // Move to the next one
end while
```

### 💡 Comparative Analysis

In compiled languages like C# or C++, function overloading is a **compile-time** concept. The compiler selects the correct method based on the arguments provided, and there is no built-in mechanism to programmatically iterate through all available overloads at **runtime**. This is a key differentiator for uCalc.

`NextOverload` gives uCalc powerful runtime introspection and metaprogramming capabilities. It allows your application to analyze its own defined symbol space, a feature more common in highly dynamic languages like LISP or Smalltalk, but made accessible here in a simple, procedural way.

**Examples:**

### Example ID: 51

**Description:** Returning data type names for the different definitions of the "+" operator

**Code:**
```pseudocode
var PlusOperator = uc.ItemOf("+");

while (PlusOperator.NotEmpty())
   wl("Def: " + PlusOperator.@Text() + "  Type: " + PlusOperator.@DataType().@Name())
   PlusOperator = PlusOperator.NextOverload();
end while
```

**Output:**
```
Def: Operator: 70 +{x}  Type: double
Def: Operator: 50 {x} + {y}  Type: double
Def: Operator: 50 {x As Int} + {y As Int} As Int  Type: int
Def: Operator: 50 {x As String} + {y As String} As String  Type: string
Def: Operator: 50 {x As Complex} + {y As Complex} As Complex  Type: complex
Def: Operator: 50 {ByHandle x As AnyType Ptr} + {y As Int} As SameTypeAs:0 Ptr  Type: sametypeas:ptr
Def: Operator: 50 {ByHandle x As AnyType} + {ByHandle y As String} As String  Type: string
Def: Operator: 50 {ByHandle x As String} + {ByHandle y As AnyType} As String  Type: string
```

---

---

## Owned - ID: 742
/doc/reference/classes/ucalc.item/owned/

**Description:** Marks a uCalc object for automatic memory release when it goes out of scope, primarily for use in C++ environments.

**Syntax:** Owned()
**Return:** Item - Returns the current Item instance to allow for method chaining.
**Remarks:**

## 🛡️ Object Ownership and Automatic Release

The `Owned()` method is a crucial memory management tool, primarily for C++, that flags a uCalc object for automatic release when its corresponding variable goes out of scope. This aligns with the C++ RAII (Resource Acquisition Is Initialization) paradigm, preventing memory leaks by ensuring resources are cleaned up deterministically.

This method returns the current [Item](/reference/item/) instance, enabling a fluent, chainable syntax.

## ⚙️ How It Works

By default, creating a uCalc object (like an `Item`, `Expression`, or `Transformer`) allocates resources that persist until you explicitly call `.Release()`. This is true even if the variable holding the object goes out of scope.

Calling `Owned()` on an object changes this behavior. The uCalc engine marks the object as "owned" by its current scope. When the scope is exited, the object's destructor is called, which in turn automatically calls [Release()](/reference/item/release/).

## Platform-Specific Usage: `Owned()` vs. `using`

The need for `Owned()` is specific to C++'s memory model. Other languages achieve the same result with different syntax:

*   **C++**: Use `Owned()` on a stack-allocated object or in conjunction with smart pointers.
    ```pseudocode
    // C++ Example
    {
       New(uCalc::Item, myItem("Var: x=5"));
       myItem.Owned(); 
       // myItem will be released automatically at the end of this scope
    }
    ```

*   **C# / VB.NET**: Use the `using` statement (which relies on the `IDisposable` interface).
    ```pseudocode
    // C# Example
    NewUsing(uCalc::Item, myItem("Var: x=5"))
    // myItem is automatically released here
    End Using
    ```

## ⚖️ Comparative Analysis

### `Owned()` vs. Standard C++ RAII
In native C++, you would typically wrap a raw pointer in a smart pointer like `std::unique_ptr` or `std::shared_ptr` to manage its lifetime. uCalc's `Owned()` method provides a similar, built-in mechanism that is simpler and more direct for uCalc objects. It avoids the need for boilerplate smart pointer declarations.

### `Owned()` vs. C# `IDisposable`
The concept is identical. `Owned()` is uCalc's C++-idiomatic way of achieving what `IDisposable` and `using` do in .NET. It provides developers with a consistent cross-platform mental model for resource management, even if the syntax differs.

**Best Practice**: In C++, always call `Owned()` on stack-allocated uCalc objects or objects whose lifetime is tied to a specific scope to prevent resource leaks. For heap-allocated objects that need to persist beyond their initial scope, manual `Release()` is still required.

**Examples:**

---

## Precedence = [int] - ID: 160
/doc/reference/classes/ucalc.item/precedence-=-[int]/

**Description:** Gets the precedence level of a symbol, which determines its binding strength in the order of operations.

**Remarks:**

The `Precedence()` method returns the numeric precedence level of an operator or rule. This value determines the order of operations in an expression, dictating which operations are performed first when multiple operators are present.

For example, in standard mathematics, multiplication has a higher precedence than addition, which is why the expression `2 + 3 * 4` evaluates to `14` (`2 + 12`) rather than `20` (`5 * 4`).

### # ⚙️ How Precedence Works in uCalc

In uCalc, precedence is represented by a numeric value. **A higher number means higher precedence** (it binds more tightly and is evaluated sooner).

This method is essential for two main tasks:

1.  **Inspecting Existing Operators**: You can query the precedence of built-in operators like `+`, `*`, or `And` to understand the default evaluation order.
2.  **Defining New Operators**: When creating a custom operator with [`DefineOperator`](/reference/ucalc/defineoperator), you must assign it a precedence level. The best practice is to base this level on an existing operator's precedence.

### # 💡 Best Practices

Avoid hardcoding 'magic numbers' for precedence levels. The exact numeric values of built-in operators can change between versions. Instead, always define precedence relative to an existing, well-understood operator.

**Good Practice (Relative):**
```pseudocode
// Give the new operator a higher precedence than multiplication.
var mul_prec = uc.ItemOf("*", ItemIs::Infix).Precedence();
uc.DefineOperator("{a} ** {b} = Pow(a, b)", mul_prec + 10);
```

**Bad Practice (Hardcoded):**
```pseudocode
// Avoid this. '60' is an internal detail.
uc.DefineOperator("{a} ** {b} = Pow(a, b)", 70);
```

### # 🆚 Comparative Analysis: Why uCalc?

In most compiled languages like C# or C++, operator precedence is **fixed at compile-time**. You cannot change the fact that `*` is evaluated before `+`, nor can you invent new operators with custom precedence levels.

This is where uCalc offers a significant advantage. Its precedence system is **fully configurable at runtime**. This allows you to:

*   **Create Domain-Specific Languages (DSLs)**: Invent new operators (e.g., `contains`, `matches`, `within`) with intuitive precedence rules that make sense for your specific domain.
*   **Adapt Syntax**: Modify the parsing behavior on the fly, perhaps based on a user's dialect preference or a specific compatibility mode.
*   **Experiment Safely**: Dynamically add or change operators without needing to recompile your application.

### Setter
This method sets the precedence level of an [Item](/reference/ucalc/item/constructor), which is a crucial property for operators and some transformer rules. Precedence determines the order of operations in an expression—which operators are evaluated first. For example, in standard arithmetic, multiplication has a higher precedence than addition.

### Dynamic Control at Runtime

While precedence is typically set when an operator is first created with [DefineOperator()](/reference/ucalc/defineoperator), this method allows you to change it *dynamically at runtime*. This provides powerful control for creating adaptive syntaxes or reconfiguring a parser without a full restart.

> **⚠️ Important Note on Parsing**
> A change in precedence only affects expressions that are parsed **after** the change is made. It does **not** alter expressions that have already been compiled with [Parse()](/reference/ucalc/parse). Those expressions would need to be re-parsed to reflect the new precedence rules.

The actual numeric value of the precedence level is arbitrary; its meaning comes from its relationship to the precedence levels of other operators. A higher number means higher precedence (tighter binding).

### 💡 Comparative Analysis: Why uCalc?

In compiled languages like C# or C++, operator precedence is **fixed by the language specification** and cannot be changed. For example, `*` will always have higher precedence than `+`. This is a rigid, compile-time rule.

uCalc's model is fundamentally more flexible. By allowing precedence to be modified at runtime, you can:

*   **Create Domain-Specific Languages (DSLs)**: Invent a custom order of operations that is intuitive for a specific domain (e.g., financial modeling, scientific notation).
*   **Emulate Other Languages**: Adjust precedence to match the behavior of another language's operators for easier transpilation.
*   **User-Configurable Syntax**: Allow end-users to customize how their formulas are interpreted.

This runtime configurability is a significant advantage over static, compiled-language approaches.

**Examples:**

### Example ID: 655

**Description:** Retrieving the precedence levels of built-in arithmetic operators to compare their binding strength.

**Code:**
```pseudocode
var plus_op = uc.ItemOf("+", uCalc::Properties(ItemIs::Infix));
var mul_op = uc.ItemOf("*", uCalc::Properties( ItemIs::Infix));

wl("Precedence of '+': ", plus_op.@Precedence())
wl("Precedence of '*': ", mul_op.@Precedence())
wl("Does '*' bind tighter than '+'? ", bool(mul_op.@Precedence() > plus_op.@Precedence()))
```

**Output:**
```
Precedence of '+': 50
Precedence of '*': 60
Does '*' bind tighter than '+'? True
```

---

### Example ID: 656

**Description:** Defining a new custom operator with a precedence level set relative to an existing operator.

**Code:**
```pseudocode
// Goal: Define a new power operator '**' with higher precedence than multiplication '*'.
var mul_precedence = uc.ItemOf("*", uCalc::Properties(ItemIs::Infix)).@Precedence();

// Set the new operator's precedence to be higher than multiplication.
uc.DefineOperator("{base} ** {exp} = Pow(base, exp)", mul_precedence + 10);

// The new operator should be evaluated before multiplication and addition.
// The expression is equivalent to: 2 + (3 * (2 ** 3)) -> 2 + (3 * 8) -> 2 + 24 -> 26
wl(uc.Eval("2 + 3 * 2 ** 3"))
```

**Output:**
```
26
```

---

### Example ID: 657

**Description:** Internal Test: Demonstrates how changing an operator's precedence at runtime affects the parsing of subsequent expressions.

**Code:**
```pseudocode
// Define '##' with the same precedence as 'And'. 'And' binds tighter than 'Or'.
var and_prec = uc.ItemOf("And", uCalc::Properties(ItemIs::Infix)).@Precedence();
var op_handle = uc.DefineOperator("{a} ## {b} As Boolean = a and b", and_prec);

wl("--- Initial Precedence (like 'And') ---")
// Evaluation is like: true or (false and false) -> true or false -> true
wl(uc.EvalStr("true or false ## 1 == 2"))

// Now, change the precedence to be lower than 'Or'.
var or_prec = uc.ItemOf("Or", uCalc::Properties(ItemIs::Infix)).@Precedence();
op_handle.@Precedence(or_prec - 10);

wl("")
wl("--- Changed Precedence (lower than 'Or') ---")
// Evaluation is like: (true or false) and false -> true and false -> false
wl(uc.EvalStr("true or false ## 1 == 2"))
```

**Output:**
```
--- Initial Precedence (like 'And') ---
true

--- Changed Precedence (lower than 'Or') ---
false
```

---

### Example ID: 24

**Description:** Finding the precedence level of an operator

**Code:**
```pseudocode
uc.DefineOperator("{a As Bool} ## {b As Bool} As Bool = a And b", uc.ItemOf("And").@Precedence());
wl(uc.EvalStr("true Or false ## 2 > 5"))

uc.ItemOf("##").SetPrecedence(uc.ItemOf("Or").@Precedence());
wl(uc.EvalStr("true Or false ## 2 > 5"))
```

**Output:**
```
true
false
```

---

---

## Regex = [string] - ID: 163
/doc/reference/classes/ucalc.item/regex-=-[string]/

**Description:** Gets or sets the regular expression pattern that defines how a token is recognized by the parser.

**Remarks:**

# ⚙️ The Regex Property: Getter and Setter

The `Regex` property gets or sets the regular expression pattern associated with a token [Item](/Reference/uCalcBase/Item/Constructor). This provides a powerful, programmatic way to inspect and modify the lexical rules of the parser at runtime.

> **Note**: A token is not a separate class in uCalc. It is simply an [Item](/Reference/uCalcBase/Item/Constructor) with specific token-related properties.

---
## 📖 Getter: Inspecting Token Definitions

When used as a getter, this property provides introspection into uCalc's lexical analysis engine.

[pseudocode]`var pattern = myTokenItem.@Regex();`

This is invaluable for:
*   **Debugging**: Verifying that a custom token was defined with the correct regex pattern.
*   **Dynamic Language Modification**: Reading an existing token's regex, modifying it, and then setting it back.
*   **Documentation Generation**: Automatically creating a syntax reference by iterating through all defined tokens and printing their names and regex patterns.

---
## ✏️ Setter: Dynamic Syntax Modification

When used as a setter, this property allows you to alter the lexical rules of the parser dynamically.

[pseudocode]`myTokenItem.@Regex("[a-zA-Z]+");`

Typically, a token's regex is assigned when it is first created with a method like [Tokens.Add](/Reference/uCalcBase/Tokens/Add). The setter allows you to change that definition at runtime for any existing token, including the built-in ones that define the core expression language syntax. This enables you to:
*   **Extend Syntax**: Add support for new number formats (e.g., C-style hex `0x[0-9a-fA-F]+`).
*   **Change Language Rules**: Modify the set of allowed characters in identifiers.
*   **Adapt to Dialects**: Adjust the parser to handle different variations of a language or data format.

---
## 💡 Why uCalc? Dynamic vs. Static Tokenizers

Most traditional parsing tools, like ANTLR or Lex/Flex, use a static approach:
1.  Define token rules in a separate grammar file (`.g4`, `.l`).
2.  Run a code generator to produce source code for a lexer.
3.  Compile this generated code into your application.

To change a token definition, you must modify the grammar file and recompile. This process is static and happens at compile-time.

uCalc's approach is fundamentally different and more flexible:
*   **Runtime Modification**: The token table is a live, mutable collection. You can add, remove, or modify token definitions at runtime using methods like [ExpressionTokens().Add()](/Reference/uCalcBase/Tokens/Add) and [pseudocode]`@Regex("...")`. There is no code generation or recompilation step.
*   **Programmatic Control**: Because the tokenizer is configured through an API, your application can adapt its own syntax on the fly. This enables powerful features like user-defined operators, dialect switching for different versions of a language, or creating sandboxed environments with restricted syntax.

In essence, the `Regex` property provides the tools to treat your application's language syntax as a dynamic, configurable entity rather than a static, compiled artifact.

---
## ⚠️ Best Practices & Performance

*   **Scope of Impact**: Be aware that changing a core token (like the one for numbers or identifiers via [ExpressionTokens](/Reference/uCalcBase/uCalc/ExpressionTokens)) will affect *all* subsequent parsing operations within that `uCalc` instance.
*   **Initialization**: It is generally best to configure custom token definitions once during your application's setup phase rather than repeatedly in a loop.

**Examples:**

### Example ID: 70

**Description:** Displays the complete list of default token definitions, showing their type, internal name, and regex pattern.

**Code:**
```pseudocode
// Lists all tokens currently defined for the expression evaluator.

wl("Token Count: ", uc.@ExpressionTokens().@Count())
wl("")
wl("Index  Type  Name: regex")
wl("========================")
var Tokens = uc.@ExpressionTokens();
foreach (var token in Tokens)
   w(Tokens.IndexOf(token))
   wl("  ", token.@Description(), "  ", token.@Name(), ": ", token.@Regex())
end for

// Note that the expression evaluator token list has a few extra tokens,
// related to hex/bin/oct notation, string interpolation, and imaginary number
// notation, which are not found in the default Transformer token list.
```

**Output:**
```
Token Count: 30

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
27  literal  _token_imaginaryunit: #i
28  tokentransform  _token_binaryhexoctalnotation: #[bho][0-9A-F]+
29  tokentransform  _token_stringinterpolationquote: \$['"]
```

---

### Example ID: 71

**Description:** Change characters accepted as alphanumeric in expressions using ExpressionTokens() & Token()

**Code:**
```pseudocode
// (See alternate version of this example using ItemOf instead of ExpressionTokens)

// In this section underscore, _, and numeric digits
// are accepted as part of alphanumeric tokens
uc.DefineVariable("My_Variable = 111");
wl(uc.@Error().@Message())
uc.DefineVariable("Variable123 = 222");
wl(uc.@Error().@Message())

wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex())
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
wl("---")

// Now we no longer want underscore, _, or numeric digits
// to be accepted in alphanumeric tokens; only A-Z
uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex("[a-zA-Z]+");

uc.DefineVariable("Other_Variable = 333");
wl(uc.@Error().@Message())
uc.DefineVariable("OtherVariable123 = 444");
wl(uc.@Error().@Message())

wl(uc.EvalStr("Other_Variable"))
wl(uc.EvalStr("OtherVariable123 "))
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
wl("---")

// We restore the alphanumeric regex to support _ and numbers again
// Note: My_Variable and Variable123 remained; they were simply inaccessible
uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex("[a-zA-Z_][a-zA-Z0-9_]*");
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
```

**Output:**
```
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222
```

---

### Example ID: 170

**Description:** Token(TokenType)

**Code:**
```pseudocode
wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Name())
wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex())
wl("")

// Note: In C# or VB you can simply use [TokenType::Literal, n]
// instead of ByType(TokenType::Literal, n)
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 0).@Name())
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 1).@Name())
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 2).@Name())
```

**Output:**
```
_token_alphanumeric
[a-zA-Z_][a-zA-Z0-9_]*

_token_string_singlequoted
_token_string_doublequoted
_token_string_tripledoublequoted
```

---

---

## Release - ID: 165
/doc/reference/classes/ucalc.item/release/

**Description:** Removes a defined symbol (like a function, variable, or rule) from the uCalc instance, freeing its resources and making it unavailable for future use.

**Syntax:** Release()
**Return:** void - This method does not return a value.
**Remarks:**

The `Release` method is the primary mechanism for manual memory management of uCalc symbols. When an item such as a [function](/reference/functions_and_operators/functions/math), [variable](/reference/ucalc/definevariable), or [transformer rule](/reference/patterns/rules) is no longer needed, calling `Release()` removes it from the uCalc instance, frees its associated resources, and makes its name available for reuse.

--- 

## 💡 Key Use Cases

While its main purpose is resource management, `Release()` enables several powerful patterns:

*   **Standard Cleanup**: The most common use is to free memory by removing temporary variables, expressions, or rules at the end of a process. This prevents memory leaks in long-running applications.

*   **Un-shadowing Definitions**: uCalc allows multiple definitions for the same name, creating a stack where the newest definition *shadows* older ones. Releasing the newest `Item` pops it from the stack, automatically restoring the previous definition. This is a powerful feature for managing layered configurations or temporary overrides.

*   **Deactivating Rules and Aliases**: Releasing an `Item` that represents a [Transformer](/reference/transformer) rule, a `Format` rule, or an [Alias](/reference/ucalc/alias) effectively deactivates that specific behavior without affecting other definitions.

--- 

## 🗑️ Manual vs. Automatic Release

There are two primary ways an `Item`'s resources are reclaimed:

1.  **Manual Release (Explicit)**
    Calling [pseudocode]`myItem.Release()` directly gives you precise control over the lifetime of an object.

2.  **Automatic Release (Implicit)**
    *   **Parent Release**: Releasing a parent container object automatically releases all of its children. For example, calling `Release()` on a [uCalc](/reference/ucalc) instance will release every function, variable, and expression defined within it.
    *   **Scoped Release**: uCalc objects can be configured for automatic release when they go out of scope, using language-specific constructs like `using` in C# or using [Owned](/ucalc/item/owned) in C++. For more details, see the [uCalc.Constructor](/reference/ucalc/constructor) topic.

--- 

## 🆚 Comparative Analysis

uCalc's memory model is distinct from both standard garbage collection (GC) and native C++ RAII.

*   **vs. Garbage Collection (C#)**: The C# `Item` object is a lightweight handle to a more substantial object inside the core uCalc engine. Even if the C# handle is garbage collected, the underlying engine object **will not be released**. You must call `Release()` or use `using` to free the engine's resources. Failure to do so can lead to memory leaks within the uCalc instance, even in a managed environment.

*   **vs. C++ Destructors**: Similarly, a C++ `Item` object going out of scope does not automatically release the underlying engine resource unless it is explicitly configured as `Owned`. `Release()` provides deterministic cleanup.

**Idempotency Note**: `Release()` is idempotent. Calling it multiple times on the same (already released) `Item` handle is safe and has no effect.

**Examples:**

### Example ID: 31

**Description:** Illustrates the core relationship between the uCalc engine, an Item (variable), and a compiled Expression.

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");
var Expression = "x^2 * 10"; // Replace this with your expression

wl("--- Efficient: Parse() once, then Evaluate() in a loop ---")
var ParsedExpr = uc.Parse(Expression);
for(double x = 1 to 10)
   VariableX.Value(x);
   wl(ParsedExpr.Evaluate())
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
--- Efficient: Parse() once, then Evaluate() in a loop ---
10
40
90
160
250
360
490
640
810
1000
```

---

---

## Rename - ID: 166
/doc/reference/classes/ucalc.item/rename/

**Description:** Changes the name of an existing symbol, such as a variable, function, or operator, at runtime.

**Syntax:** Rename(string)
**Parameters:**
newName - string - The new name to assign to the item.
**Return:** Item - Returns the current [Item](/reference/ucalc/item) instance to allow for method chaining.
**Remarks:**

The `Rename` method provides a direct, efficient way to change the identifier of any named [Item](/reference/ucalc/item) within the uCalc engine at runtime. This is a destructive operation: the original name is removed from the symbol table and is no longer valid.

This is commonly used for refactoring, adapting syntax, or wrapping existing functions with new behavior.

### Impact on Dependencies

By default, uCalc expressions are statically bound when parsed. If you rename a function `f` to `g`, any existing expression that was already parsed to call `f` will **not** be automatically updated and will fail if evaluated. Renaming only affects expressions that are parsed *after* the rename operation has occurred.

To create dynamically-updating (reactive) expressions, you must define functions and operators with the `overwrite: true` flag. See [DefineFunction()](/reference/ucalc/definefunction) for more details.

### ⚖️ Comparative Analysis

It's important to choose the right tool for modifying symbols. `Rename` should be compared with `Alias` and text-based transformers.

*   **vs. [Alias()](/reference/ucalc/alias)**
    *   **Rename**: `A -> B` (A is no longer valid).
    *   **Alias**: `A -> B` (Both A and B are valid, pointing to the same underlying item).
    *   **Use Case**: Use `Rename` for permanent changes or to free up a name for reuse. Use `Alias` to provide synonyms or for backward compatibility.

*   **vs. [ExpressionTransformer()](/reference/ucalc/expressiontransformer)**
    *   **Rename**: Operates directly on the symbol table. It is extremely fast and efficient.
    *   **Transformer**: Performs textual search-and-replace on the raw expression string *before* parsing. It is much slower and can have unintended side effects if the pattern is not specific enough.
    *   **Use Case**: Use `Rename` for simple name changes. Use a `Transformer` for complex structural changes that involve more than just a name (e.g., reordering parameters, changing operators).

**Examples:**

### Example ID: 48

**Description:** Renames the Cos function (which is in Radian) to CosR and defines Cos in Degrees

**Code:**
```pseudocode
uc.DefineConstant("pi = Atan(1) * 4");

// Original Cosine behavior with Radian
wl(uc.EvalStr("Cos(pi)"))
wl(uc.EvalStr("Cos(180)"))

// Cos is renamed to CosR so that Cos can now be defined in Degree
uc.ItemOf("Cos").Rename("CosR");
uc.DefineFunction("Cos(x) = CosR(x*pi/180)");

// Now Cos is in Degree
wl(uc.EvalStr("Cos(pi)"))
wl(uc.EvalStr("Cos(180)"))

// This is the original function now named CosR
wl(uc.EvalStr("CosR(pi)"))
wl(uc.EvalStr("CosR(180)"))
// Note: Some functions may be overloaded, such as the Cos function in
// this example, which has a definition for Double and another for Complex.
// This example renames only the Double precision version.
// You can use NextOverload() and DataType() to pinpoint the one you want
```

**Output:**
```
-1
-0.59846006905785
0.99849714986386
-1
-1
-0.59846006905785
```

---

---

## Text = [string] - ID: 527
/doc/reference/classes/ucalc.item/text-=-[string]/

**Description:** Retrieves the original definition string for an item, such as a function or operator, for introspection and debugging.

**Remarks:**

The `Text()` method provides powerful introspection capabilities by returning the original, literal string that was used to create a uCalc [Item](/reference/ucalc/item). This allows you to programmatically access the "source code" of functions, operators, variables, and other symbols at runtime.

This is invaluable for:
*   **Debugging**: Displaying the exact definition of a function or operator that is being evaluated.
*   **Tooling**: Building IDE-like features, such as property inspectors or function editors, that can show and even modify definitions.
*   **Metaprogramming**: Analyzing the structure of one function to dynamically generate another.
*   **Logging**: Recording the exact state of a function or variable at a specific point in time.

For a function defined via [DefineFunction()](/reference/ucalc/mainclassgroup/definefunction), this method returns the full signature and expression body. For an operator from [DefineOperator()](/reference/ucalc/mainclassgroup/defineoperator), it includes the operands, symbol, and expression.

### Comparative Analysis: Why uCalc?

In compiled languages like C# or C++, reflection can provide metadata about a method—such as its name, parameters, and return type—but it cannot retrieve the original source code. `Item.Text()` is fundamentally different because the uCalc engine retains the complete definition string, bridging the gap between a compiled, executable item and its human-readable source. This makes uCalc an exceptionally powerful tool for dynamic and interactive applications.

**Examples:**

### Example ID: 673

**Description:** Retrieves the full definition string for a user-defined function.

**Code:**
```pseudocode
uc.DefineFunction("MyFunction(x) = x * 2");
wl(uc.ItemOf("MyFunction").@Text())
```

**Output:**
```
Function: MyFunction(x) = x * 2
```

---

### Example ID: 674

**Description:** Practical: Inspects various properties of an item from within a callback, including its definition text.

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   var itm = cb.@Item();
   wl("Name: ", itm.@Name())
   wl("Data type: ", itm.@DataType().@Name())
   wl("Param count: ", to_string(itm.@Count()))
   w("Procedure type: ")
   if (itm.IsProperty(ItemIs::Operator))
      wl("Operator")
   else if (itm.IsProperty(ItemIs::Function))
      wl("Function")
   end if
   wl("Definition: ", itm.@Text())
   wl("Description: ", itm.@Description())
   wl("---")
[/callback]
[body]
uc.DefineFunction("AAA() As Double", ItemCallback).@Description("Does this and that");
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).@Description("Does something else");
uc.DefineOperator("{x} CCC {y} As Int32", 55, Associativity::LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");
```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Definition: Function: AAA() As Double
Description: Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Definition: Function: BBB(x, y, z) As String
Description: Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Definition: Operator: {x} CCC {y} As Int32
Description: 
---
```

---

### Example ID: 675

**Description:** Practical: Iterates through all overloads of the '+' operator and displays their unique definition text.

**Code:**
```pseudocode
var PlusOperator = uc.ItemOf("+");

do
   wl("Def: ", PlusOperator.@Text(), " -- Type: ", PlusOperator.@DataType().@Name())
   PlusOperator = PlusOperator.NextOverload();
loop while(PlusOperator.NotEmpty());
```

**Output:**
```
Def: Operator: 70 +{x} -- Type: double
Def: Operator: 50 {x} + {y} -- Type: double
Def: Operator: 50 {x As Int} + {y As Int} As Int -- Type: int
Def: Operator: 50 {x As String} + {y As String} As String -- Type: string
Def: Operator: 50 {x As Complex} + {y As Complex} As Complex -- Type: complex
Def: Operator: 50 {ByHandle x As AnyType Ptr} + {y As Int} As SameTypeAs:0 Ptr -- Type: sametypeas:ptr
Def: Operator: 50 {ByHandle x As AnyType} + {ByHandle y As String} As String -- Type: string
Def: Operator: 50 {ByHandle x As String} + {ByHandle y As AnyType} As String -- Type: string
```

---

### Example ID: 52

**Description:** Inspecting the parts of a syntax construct

**Code:**
```pseudocode
uc.DefineFunction("MyFunction(x) = x * 2");
wl(uc.ItemOf("MyFunction").@Text())
```

**Output:**
```
Function: MyFunction(x) = x * 2
```

---

### Example ID: 40

**Description:** Determining properties of an expression part

**Code:**
```pseudocode
[head]
[callback ItemCallback]
   wl("Name: ", cb.@Item().@Name())
   wl("Data type: ", cb.@Item().@DataType().@Name())
   wl("Param count: ", cb.@Item().@Count())
   w("Procedure type: ")
   if (cb.@Item().IsProperty(ItemIs::Operator))
      wl("Operator")
   else if (cb.@Item().IsProperty(ItemIs::Function))
      wl("Function")
   end if
   wl(cb.@Item().@Text())
   wl(cb.@Item().@Description())
   wl("---")
[/callback]
[body]

uc.DefineFunction("AAA() As Double", ItemCallback).@Description("Does this and that");
uc.DefineFunction("BBB(x, y, z) As String", ItemCallback).@Description("Does something else");
uc.DefineOperator("{x} CCC {y} As Int32", 0, Associativity::LeftToRight, ItemCallback);

uc.EvalStr("AAA()");
uc.EvalStr("BBB(9, 8, 7)");
uc.EvalStr("5 CCC 4");

```

**Output:**
```
Name: aaa
Data type: double
Param count: 0
Procedure type: Function
Function: AAA() As Double
Does this and that
---
Name: bbb
Data type: string
Param count: 3
Procedure type: Function
Function: BBB(x, y, z) As String
Does something else
---
Name: ccc
Data type: int
Param count: 2
Procedure type: Operator
Operator: {x} CCC {y} As Int32

---
```

---

---

## TypeOfToken = [TokenType] - ID: 808
/doc/reference/classes/ucalc.item/typeoftoken-=-[tokentype]/

**Description:** Gets or sets the lexical category (TokenType) for a specific token Item.

**Remarks:**

This method functions as a dynamic getter/setter for a token's lexical category, allowing you to change how the parser interprets a token at runtime.

### ⚙️ Getter/Setter Behavior
*   **Getter**: When called without a parameter (or with the default `TokenType::None`), `TypeOfToken()` returns the token's current [TokenType](/Reference/Enums/TokenType) without changing it.
*   **Setter**: When you pass a specific `TokenType` enum member, the method re-categorizes the token. For instance, you can change the newline token from a `StatementSep` to `Whitespace`, fundamentally altering the parsing behavior for multi-line text.

### 💡 Why Is This Useful? (Comparative Analysis)
In traditional compiler design using tools like Lex/Flex or ANTLR, token definitions are static and defined in a separate grammar file. Changing a token's type requires modifying the grammar and regenerating/recompiling the parser.

uCalc's `TypeOfToken()` method provides a powerful **runtime mechanism** to alter the lexer's behavior on the fly. This is a significant advantage for:
*   **Syntax Dialects**: Easily switch between language dialects that treat characters differently (e.g., where a newline is sometimes significant and sometimes not).
*   **Context-Sensitive Lexing**: Programmatically change token types based on the application's state. For example, you could treat `*` as multiplication in a math context and as a wildcard character in a search context.
*   **Extensibility**: Allows for creating highly adaptable parsers that can be reconfigured without a full restart or recompilation.

The most common practical use is to re-categorize the newline token (`_token_newline`) from a statement separator to whitespace, which is essential for parsing languages like XML or HTML where newlines are not structurally significant.

**Examples:**

### Example ID: 677

**Description:** Demonstrates getting a token's initial type and then changing it using the setter overload.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
var myToken = t.@Tokens().Add("###", TokenType::Generic);
w("Initial Type: ")
wl(bool(myToken.@TypeOfToken() == TokenType::Generic))

// Change the type
myToken.@TypeOfToken(TokenType::Reducible);
w("New Type is Reducible: ")
wl(bool(myToken.@TypeOfToken() == TokenType::Reducible))
End Using
```

**Output:**
```
Initial Type: True
New Type is Reducible: True
```

---

### Example ID: 678

**Description:** Practical: Re-categorizes the newline token as whitespace to allow a pattern to match across multiple lines, a common requirement for parsing HTML or XML.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
var source = [verbatim]<data>
  content spans
  multiple lines
</data>[/verbatim];
t.FromTo("<data>{body}</data>", "Body: [{body}]");

wl("--- Default (Newline is a Separator) ---")
// This fails because {body} stops at the first newline
wl(t.Transform(source).@Text())
wl("")

wl("--- Modified (Newline is Whitespace) ---")
// Find the newline token and change its type
var newlineToken = t.@Tokens()["_token_newline"];
newlineToken.@TypeOfToken(TokenType::Whitespace);
// Now the transform succeeds
wl(t.Transform(source).@Text())
End Using
```

**Output:**
```
--- Default (Newline is a Separator) ---
<data>
  content spans
  multiple lines
</data>

--- Modified (Newline is Whitespace) ---
Body: [content spans
  multiple lines]
```

---

### Example ID: 679

**Description:** Internal Test: Changes a token's type and then reverts it to ensure the state is managed correctly.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
var alphaToken = t.@Tokens()["_token_alphanumeric"];

wl("1. Initial Type is Alphanumeric: ", bool(alphaToken.@TypeOfToken() == TokenType::AlphaNumeric))

// Change it to a literal
alphaToken.@TypeOfToken(TokenType::Literal);
wl("2. Type is now Literal: ", bool(alphaToken.@TypeOfToken() == TokenType::Literal))
wl("3. Type is no longer Alphanumeric: ", bool(alphaToken.@TypeOfToken() != TokenType::AlphaNumeric))

// Change it back
alphaToken.@TypeOfToken(TokenType::AlphaNumeric);
wl("4. Reverted Type is Alphanumeric: ", bool(alphaToken.@TypeOfToken() == TokenType::AlphaNumeric))
End Using
```

**Output:**
```
1. Initial Type is Alphanumeric: True
2. Type is now Literal: True
3. Type is no longer Alphanumeric: True
4. Reverted Type is Alphanumeric: True
```

---

### Example ID: 178

**Description:** TypeOfToken

**Code:**
```pseudocode
// See uCalc.Tokens.Count() example for list of token names

var t = uc.NewTransformer();
var MyToken = t.@Tokens().Add("###");
var Alpha = t.@Tokens()["_token_alphanumeric"];

wl(bool(MyToken.@TypeOfToken() == TokenType::AlphaNumeric))
wl(bool(MyToken.@TypeOfToken() == TokenType::Generic))
wl(bool(Alpha.@TypeOfToken() == TokenType::AlphaNumeric))
wl(bool(Alpha.@TypeOfToken() == TokenType::Generic))


```

**Output:**
```
False
True
True
False
```

---

### Example ID: 221

**Description:** Change newline from statement separator to whitespace using TypeOfToken

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.Str([verbatim]
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
[/verbatim]);

t.Pattern("<div>{body}</div>");
var NewLineToken = t.@Tokens()["_token_newline"];

wl("Newline as statement separator (default)")
wl("----------------------------------------")
wl(t.Find().@Matches().@Text())
wl("")

wl("Newline as whitespace")
wl("---------------------")
NewLineToken.@TypeOfToken(TokenType::Whitespace);
wl(t.Find().@Matches().@Text())
```

**Output:**
```
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>

Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
```

---

---

## uCalc = [uCalc] - ID: 528
/doc/reference/classes/ucalc.item/ucalc-=-[ucalc]/

**Description:** Retrieves the parent uCalc instance to which this Item belongs, providing access to its execution context.

**Remarks:**

Every [Item](/reference/ucalcbase/item) in uCalc—be it a variable, function, or operator—is owned by a specific [uCalc](/reference/ucalcbase/ucalc) instance. This instance acts as its **execution context** or "sandbox," holding the complete set of definitions and settings that apply to it.

The `uCalc()` method provides a direct way to get a reference back to this parent instance from any `Item` object.

### 🎯 Primary Use Cases

1.  **Contextual Operations**: The most common use is to perform another operation within the same context as the item. If you have an `Item` object but not a direct reference to its parent `uCalc` instance, you can use this method to retrieve it and call methods like [Eval()](/reference/ucalcbase/ucalc/eval) or [DefineVariable()](/reference/ucalcbase/ucalc/definevariable).

2.  **Instance Introspection**: It allows you to determine if two different items belong to the same execution context, which is invaluable for debugging applications that manage multiple, isolated uCalc instances.

3.  **Accessing Sibling Items**: Once you retrieve the parent instance, you can use it to find other items within the same sandbox, for example: `myVar.uCalc().ItemOf("SomeOtherVar")`.

### ⚖️ Comparative Analysis

*   **vs. Native Objects (C#/C++)**: In standard object-oriented programming, an object typically does not maintain a public reference to the factory or container that created it. You would have to design this relationship manually. uCalc makes this parent-child link a first-class, built-in feature, simplifying the management of multiple, concurrent parsing environments.

*   **vs. Document Object Model (DOM)**: The relationship is analogous to the DOM in web development. Just as an HTML element has an `ownerDocument` property that points back to the document it belongs to, a uCalc `Item` has its `uCalc()` method to get back to its owner instance. This provides a consistent and predictable way to navigate the object hierarchy.

**Examples:**

### Example ID: 680

**Description:** Basic round-trip from an item back to its parent instance.

**Code:**
```pseudocode
New(uCalc, myInstance)
// Define a variable and get its Item object
var v = myInstance.DefineVariable("v = 10");

// Use the item to get back to its parent uCalc instance
var parentInstance = v.@uCalc();

// Perform another evaluation in the same context
wl(parentInstance.EvalStr("v + 5"))
```

**Output:**
```
15
```

---

### Example ID: 681

**Description:** A practical example showing how to manage two separate uCalc instances with conflicting variable names.

**Code:**
```pseudocode
// Create two independent uCalc instances
New(uCalc, uc1)
New(uCalc, uc2)

// Define a variable 'x' in each instance with a different value
var itemX1 = uc1.DefineVariable("x = 100");
var itemX2 = uc2.DefineVariable("x = 200");

// Use the item to get its parent context and evaluate 'x * 2'
// This correctly uses uc1's context where x is 100.
wl("Context 1: ", itemX1.@uCalc().Eval("x * 2"));

// This correctly uses uc2's context where x is 200.
wl("Context 2: ", itemX2.@uCalc().Eval("x * 2"))

// Clean up the instances
uc1.Release();
uc2.Release();
```

**Output:**
```
Context 1: 200
Context 2: 400
```

---

### Example ID: 33

**Description:** Doing an Eval in the same uCalc instance a variable belongs to

**Code:**
```pseudocode
New(uCalc, uc1)
New(uCalc, uc2)

var x1 = uc1.DefineVariable("x = 5");
var x2 = uc2.DefineVariable("x = 6");

wl(x1.@uCalc().Eval("x*10")) // Same as uc1.Eval("x*10")
wl(x2.@uCalc().Eval("x*10")) // Same as uc2.Eval("x*10")

uc1.Release();  // Since x1 is part of uc1, x1 is automatically released as well
uc2.Release();  // Since x2 is part of uc2, x2 is automatically released as well

// You should no longer use x1 or x2 because they were part of uc1 & uc2
// Don not try x1.uCalc().Eval("x*10"); or x2.uCalc().Eval("x*10");
```

**Output:**
```
50
60
```

---

---

## Value - ID: 167
/doc/reference/classes/ucalc.item/value/

---

## Value() - ID: 168
/doc/reference/classes/ucalc.item/value/value-void/

**Description:** Retrieves the value of a variable, converting it to a double-precision floating-point number if necessary.

**Syntax:** Value()
**Return:** double - The variable's value as a double-precision number. If the variable holds an integer or boolean, it is converted to a double.
**Remarks:**

The `Value()` method is the primary getter for retrieving the numeric value of a variable represented by an [Item](/reference/ucalc/item) object. It is designed to be a general-purpose accessor for any value that can be reasonably represented as a `Double`.

### Type Conversion

This method automatically handles type conversion from other simple numeric types. If the underlying variable is an `Integer` or `Boolean`, its value is promoted to a `Double` before being returned. This provides flexibility and avoids the need for manual type-checking in many common scenarios.

### Choosing the Right Accessor

uCalc provides several methods to retrieve a variable's value. Use the following guide to choose the most appropriate one:

| Method | Return Type | Use Case |
| :--- | :--- | :--- |
| **`Value()`** | `double` | The default choice for any numeric value when you need a `Double`. Handles conversions automatically. |
| **`ValueInt32()`** | `int` | When you specifically need a 32-bit integer and want to avoid floating-point representation. |
| **`ValueBool()`** | `bool` | For variables that hold boolean states. |
| **`ValueStr()`** | `string` | The universal getter. It can retrieve the value of *any* data type, including complex types, and return it as a string. |

### ⚖️ Comparative Analysis

In a typical programming language like C# or C++, you access a variable's value directly by its name (e.g., `double result = myVar;`). In uCalc, the process is slightly different because you often interact with variables through their metadata object, the `Item`.

*   [DefineVariable()](/reference/ucalc/definevariable) returns an `Item` object.
*   This `Item` is a handle to the underlying variable in the uCalc engine.
*   `Value()` is the method you call on that `Item` to "dereference" it and retrieve its numeric content into your host application's environment.

This object-oriented approach allows for powerful runtime introspection (e.g., checking the variable's name or type via the `Item` object) before accessing its value.

#### ⚡️ Direct Memory Binding: The High-Performance Alternative

While this `Value()` getter is used to retrieve a result, its corresponding setter (`Value(newValue)`) is used to push data into the uCalc engine. In performance-critical loops, repeatedly calling the setter can be inefficient.

As a high-performance alternative, `uCalc` supports direct memory binding. When defining a variable, you can pass the memory address of a host application variable directly to [DefineVariable()](/reference/ucalc/definevariable).

*   **In C++**: You can pass the address of a variable (e.g., `&myHostVar`).
*   **In C#**: This is possible within an `unsafe` context, typically by pinning the variable and passing its address.
*   **In VB.NET**: This is generally not supported.

When a variable is bound this way, the uCalc engine reads from and writes to your native variable's memory directly. This creates a "live link," eliminating the need to call the `Value()` setter inside a loop and offering the best possible performance for tight integrations.

**Examples:**

### Example ID: 17

**Description:** DefineVariable examples

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var MyInt = uc.DefineVariable("MyInt As Int");
var MyStr = uc.DefineVariable("MyStr As String");
uc.DefineVariable("OtherStr = 'string type inferred'");
uc.DefineVariable("MyInt16 = Int16(100/3)"); // type inferred
uc.DefineVariable("MyBool = True"); // type inferred
uc.DefineVariable("MyComplex = 3 + 4*#i"); // type inferred

MyVar.Value(123);
MyInt.ValueInt32(456);
MyStr.ValueStr("This is a test");

wl("MyVar = " + uc.EvalStr("MyVar"))
wl("MyInt = " + uc.EvalStr("MyInt"))
wl("MyStr = " + uc.EvalStr("MyStr"))
wl("OtherStr = " + uc.EvalStr("OtherStr"))
wl("MyInt16 = " + uc.EvalStr("MyInt16"))
wl("MyBool = " + uc.EvalStr("MyBool"))
wl("MyComplex = " + uc.EvalStr("MyComplex"))
wl("---")
wl(MyVar.Value())
wl(MyInt.ValueInt32())
wl(MyStr.ValueStr())
wl("---")
wl(uc.ItemOf("MyVar").@DataType().@Name())
wl(uc.ItemOf("MyInt").@DataType().@Name())
wl(uc.ItemOf("MyStr").@DataType().@Name())
wl(uc.ItemOf("OtherStr").@DataType().@Name())
wl(uc.ItemOf("MyInt16").@DataType().@Name())
wl(uc.ItemOf("MyBool").@DataType().@Name())
wl("---")

var Expression = "x^2 * 10";
var VarX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse(Expression);

w("Expression = ")
wl(Expression)
for (int x = 1 to 10)
   VarX.Value(x); // In C++ you can skip this by passing &x to DefineVariable
   wl("x = " + VarX.ValueStr() + "  Result = " + ParsedExpr.EvaluateStr())
end for

ParsedExpr.Release();
VarX.Release();
```

**Output:**
```
MyVar = 123
MyInt = 456
MyStr = This is a test
OtherStr = string type inferred
MyInt16 = 33
MyBool = true
MyComplex = 3+4i
---
123
456
This is a test
---
double
int
string
string
int16
bool
---
Expression = x^2 * 10
x = 1  Result = 10
x = 2  Result = 40
x = 3  Result = 90
x = 4  Result = 160
x = 5  Result = 250
x = 6  Result = 360
x = 7  Result = 490
x = 8  Result = 640
x = 9  Result = 810
x = 10  Result = 1000
```

---

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## Value(double) - ID: 169
/doc/reference/classes/ucalc.item/value/value-double/

**Description:** Assigns a double-precision floating-point value to a uCalc variable.

**Syntax:** Value(double)
**Parameters:**
value - double - The double-precision floating-point value to assign to the variable.
**Return:** void - This method does not return a value.
**Remarks:**

### ⚙️ Overview
This method provides the primary mechanism for setting the value of a uCalc variable from the host application. It is the most common way to update variables that will be used in subsequent expression evaluations.

When a variable is created using [DefineVariable](/reference/ucalc/definevariable), this method can be called on the returned [Item](/reference/item) object to change its stored value. This overload specifically handles `double` (64-bit floating-point) values.

For other data types, use their corresponding methods:
*   [ValueInt32()](/reference/item/valueint32)
*   [ValueStr()](/reference/item/valuestr)
*   etc.

### 💡 Performance Note: Memory Binding
While `Value()` is convenient, for performance-critical applications where a variable is updated frequently inside a loop, it is more efficient to bind the uCalc variable directly to a host variable's memory address. This can be done by passing a pointer to the host variable in the `variableAddress` parameter of [DefineVariable](/reference/ucalc/definevariable). This direct memory link avoids the overhead of a method call for each update.

### 🆚 Comparative Analysis

#### vs. Native Variable Assignment (C#/C++)
In a language like C#, you would assign a value directly: `myVariable = 123.45;`. This happens at compile time with static type checking.

uCalc's `Value()` method operates at **runtime**. This provides a powerful layer of abstraction for scripting and dynamic environments. It allows your application to control the state of a separate, sandboxed evaluation engine, which is a fundamentally different and more flexible paradigm than native variable assignment.

#### vs. Memory Binding
*   **`item.Value(123.45)`**: Pushes a value from the host application into the uCalc engine's memory space. Involves a function call.
*   **Memory Binding**: The uCalc variable becomes a direct window into the host application's memory. No function call is needed to update the value; changes are reflected automatically. This is the preferred method for high-performance scenarios.

**Examples:**

### Example ID: 14

**Description:** Passing arg ByExpr (delayed lazy eval) and ByHandle

**Code:**
```pseudocode
[head]
[callback MySum]
   var Total = 0.0;
   var Expr = cb.ArgExpr(1);
   var Start = cb.Arg(2);
   var Finish = cb.Arg(3);
   var Variable = cb.ArgItem(4);

   for(double x = Start to Finish)
      Variable.Value(x);
      Total += Expr.Evaluate();
   end for
   cb.Return(Total);
[/callback]
[body]
uc.DefineVariable("x");
uc.DefineFunction("Sum(ByExpr Expr, Start, Finish, ByHandle Var)", MySum);
wl(uc.Eval("Sum(x ^ 2, 1, 10, x)"))

```

**Output:**
```
385
```

---

### Example ID: 31

**Description:** Illustrates the core relationship between the uCalc engine, an Item (variable), and a compiled Expression.

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");
var Expression = "x^2 * 10"; // Replace this with your expression

wl("--- Efficient: Parse() once, then Evaluate() in a loop ---")
var ParsedExpr = uc.Parse(Expression);
for(double x = 1 to 10)
   VariableX.Value(x);
   wl(ParsedExpr.Evaluate())
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
--- Efficient: Parse() once, then Evaluate() in a loop ---
10
40
90
160
250
360
490
640
810
1000
```

---

### Example ID: 17

**Description:** DefineVariable examples

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var MyInt = uc.DefineVariable("MyInt As Int");
var MyStr = uc.DefineVariable("MyStr As String");
uc.DefineVariable("OtherStr = 'string type inferred'");
uc.DefineVariable("MyInt16 = Int16(100/3)"); // type inferred
uc.DefineVariable("MyBool = True"); // type inferred
uc.DefineVariable("MyComplex = 3 + 4*#i"); // type inferred

MyVar.Value(123);
MyInt.ValueInt32(456);
MyStr.ValueStr("This is a test");

wl("MyVar = " + uc.EvalStr("MyVar"))
wl("MyInt = " + uc.EvalStr("MyInt"))
wl("MyStr = " + uc.EvalStr("MyStr"))
wl("OtherStr = " + uc.EvalStr("OtherStr"))
wl("MyInt16 = " + uc.EvalStr("MyInt16"))
wl("MyBool = " + uc.EvalStr("MyBool"))
wl("MyComplex = " + uc.EvalStr("MyComplex"))
wl("---")
wl(MyVar.Value())
wl(MyInt.ValueInt32())
wl(MyStr.ValueStr())
wl("---")
wl(uc.ItemOf("MyVar").@DataType().@Name())
wl(uc.ItemOf("MyInt").@DataType().@Name())
wl(uc.ItemOf("MyStr").@DataType().@Name())
wl(uc.ItemOf("OtherStr").@DataType().@Name())
wl(uc.ItemOf("MyInt16").@DataType().@Name())
wl(uc.ItemOf("MyBool").@DataType().@Name())
wl("---")

var Expression = "x^2 * 10";
var VarX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse(Expression);

w("Expression = ")
wl(Expression)
for (int x = 1 to 10)
   VarX.Value(x); // In C++ you can skip this by passing &x to DefineVariable
   wl("x = " + VarX.ValueStr() + "  Result = " + ParsedExpr.EvaluateStr())
end for

ParsedExpr.Release();
VarX.Release();
```

**Output:**
```
MyVar = 123
MyInt = 456
MyStr = This is a test
OtherStr = string type inferred
MyInt16 = 33
MyBool = true
MyComplex = 3+4i
---
123
456
This is a test
---
double
int
string
string
int16
bool
---
Expression = x^2 * 10
x = 1  Result = 10
x = 2  Result = 40
x = 3  Result = 90
x = 4  Result = 160
x = 5  Result = 250
x = 6  Result = 360
x = 7  Result = 490
x = 8  Result = 640
x = 9  Result = 810
x = 10  Result = 1000
```

---

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

### Example ID: 1460

**Description:** Using the parse-evaluate pattern for high-performance calculations in a loop with a changing variable w/ stopwatch.

**Code:**
```pseudocode
var variableX = uc.DefineVariable("x");
var userExpression = "x * 2 + 5";
var Total = 0.0;
var UpperBound = 1000000; // One million

// Parse the expression just once before the loop begins.
var parsedExpr = uc.Parse(userExpression);

[NotCpp]var stopwatch = System.Diagnostics.Stopwatch.StartNew();[/NotCpp]
for(double x = 1 to UpperBound)
   variableX.Value(x);
   Total = Total + parsedExpr.Evaluate();
end for
[NotCpp]stopwatch.Stop();
//Uncomment the following line to reveal the actual speed:
//Console.WriteLine($"Elapsed Milliseconds: {stopwatch.ElapsedMilliseconds} ms");
[/NotCpp]
w("Sum(1, ", UpperBound, ", ", userExpression, ") = ", [cpp](long long)[/cpp]Total)
```

**Output:**
```
Sum(1, 1000000, x * 2 + 5) = 1000006000000
```

---

---

## Value(string) - ID: 170
/doc/reference/classes/ucalc.item/value/value-string/

**Description:** Sets the value of a variable by parsing and evaluating a string expression, automatically handling type conversion.

**Syntax:** Value(string)
**Parameters:**
valueExpression - string - A string containing the expression to be parsed, evaluated, and assigned to the variable.
**Return:** void - 
**Remarks:**

# ⚙️ Overview
This method provides a universal way to set the value of a variable by parsing and evaluating a string expression. Unlike type-specific setters (e.g., `ValueInt32`), this overload can assign a value to a variable of any data type, automatically handling the necessary parsing and type conversion.

The input string is not just a literal value; it is treated as a complete uCalc expression. This means it can contain calculations, function calls, or even references to other variables.

# 💡 Key Features
*   **Expression Evaluation**: The input string is processed by the uCalc engine. For example, passing `"10 * 2"` will set a numeric variable to `20`.
*   **Automatic Type Conversion**: The result of the expression is automatically converted to the target variable's data type. For instance, if a variable is an `Int32`, setting its value with `"4.75"` will result in the integer `4`. If an unsigned type like `Byte` is given a negative number, it will wrap around (e.g., `-1` becomes `255`).
*   **Universal Applicability**: This single method works for all data types, simplifying code that needs to handle dynamic or user-provided input.

# 🆚 Comparative Analysis

### vs. Standard Type Parsing (e.g., C# `int.Parse()`)
In most languages, converting a string to a value is a direct parsing operation (`int.Parse("123")`). This operation fails if the string is not a valid representation of that type. uCalc's method is more powerful because it treats the string as a full expression to be *evaluated*, not just parsed. This allows for runtime calculations to determine the final value.

### vs. Direct Assignment
In a compiled language, you assign a pre-computed value: [pseudocode]`myVar = 5 * 2;`. With this `Value()` overload, you provide the *formula* as a string: [pseudocode]`MyVar.Value("5 * 2");`. This is fundamental for building applications where logic is determined at runtime, such as scripting engines or spreadsheet applications. It decouples the value assignment from the compile-time logic of the host application.

This method should be used for variables created with [DefineVariable](/Reference/uCalcBase/uCalc/DefineVariable) or [Define](/Reference/uCalcBase/uCalc/Define).

**Examples:**

### Example ID: 25

**Description:** Setting variables of any data type

**Code:**
```pseudocode
var Int32Var = uc.DefineVariable("Int32Var As Int32");
var ByteVar = uc.DefineVariable("ByteVar As Byte");
var StrVar = uc.DefineVariable("StrVar As String");
var SngVar = uc.DefineVariable("SngVar As Single");

Int32Var.Value("4.25"); // Will be converted to integer
ByteVar.Value("-1");    // Will be converted to unsigned byte
StrVar.Value("'Test'");
SngVar.Value("1 + 0.25");

wl(uc.Eval("Int32Var"))
wl(uc.Eval("ByteVar"))
wl(uc.EvalStr("StrVar"))
wl(uc.EvalStr("SngVar"))

```

**Output:**
```
4
255
Test
1.25
```

---

---

## Value(Item) - ID: 592
/doc/reference/classes/ucalc.item/value/value-item/

**Description:** Programmatically assigns the value of one variable to another, bypassing the expression evaluator for high performance.

**Syntax:** Value(Item)
**Parameters:**
sourceItem - Item - The source `Item` (typically a variable) whose value will be copied to the current item.
**Return:** void - This method does not return a value.
**Remarks:**

This method provides a direct, programmatic way to assign the value of one uCalc [Item](/reference/uCalc/Item) (typically a variable) to another. It operates on the underlying data, effectively performing an assignment like `destination = source` at the native level.

### 💡 Comparative Analysis

This method is a high-performance alternative to other forms of assignment within uCalc.

*   **vs. `uc.Eval("destination = source")`**
    Using the [Eval](/reference/uCalc/Eval) function requires the engine to parse the string, look up both symbols, and then perform the assignment. `destination.Value(source)` skips the parsing and lookup steps entirely, making it significantly faster. It is the ideal choice when you are manipulating variables from your host application code (C#, C++, etc.) and performance is critical.

*   **vs. `destination.Value(source.Value())`**
    Manually getting the scalar value from the source and setting it on the destination works, but it involves an intermediary step in your host language. `destination.Value(source)` is more direct, as it allows the uCalc engine to perform an optimized internal copy, which can be more efficient and better handle complex or custom data types.

### Type Compatibility

The assignment will attempt to perform a safe type conversion if the source and destination variables have different data types. For example, assigning a `Double` to an `Int` will result in the value being truncated, similar to a static cast in C++ or an explicit cast in C#.

**Examples:**

---

## ValueAddr - ID: 0
/doc/reference/classes/ucalc.item/valueaddr/

---

## ValueAddr() - ID: 171
/doc/reference/classes/ucalc.item/valueaddr/valueaddr-void/

**Description:** Returns the memory address of an item's value, enabling low-level interoperability and direct memory manipulation.

**Syntax:** ValueAddr()
**Return:** IntPtr - A pointer to the item's underlying value. The exact type is platform-dependent (e.g., `IntPtr` in .NET).
**Remarks:**

The `ValueAddr` method provides a way to get a direct pointer to the memory location where a uCalc item's value is stored. This is an advanced feature primarily used for high-performance scenarios, such as binding uCalc variables to variables in the host application or modifying values by reference within a callback.

### Core Use Cases
*   **Host Application Binding**: Link a uCalc variable directly to a native variable in C++, C#, or VB.
*   **Passing by Reference**: Obtain a pointer to pass to a callback function that needs to modify the original value.
*   **Low-Level Introspection**: Use with methods like [ValueAt](/reference/ucalcbase/ucalc/valueat) to dereference the pointer and read the value.

---

### `ValueAddr` vs. `ValuePtr`: The Critical Distinction

It is essential to understand the difference between `ValueAddr()` and `ValuePtr()`, especially when working with pointer-type variables. Failing to do so can lead to subtle bugs or memory access errors.

| Method | Description | Example Scenario | 
|---|---|---|
| **`ValueAddr()`** | Returns the memory address **OF the item itself**. | If you have a variable `x`, `x.ValueAddr()` gives you the location where the value of `x` is stored. | 
| **`ValuePtr()`** | Returns the memory address **STORED IN the item**. | If you have a variable `p As Int Ptr`, `p.ValuePtr()` gives you the address that `p` is pointing to, *not* the address of `p` itself. | 

In short: `ValueAddr` is for getting the address *of* any variable, while `ValuePtr` is for getting the address *held by* a pointer variable.

---

### ⚖️ Comparative Analysis

*   **vs. C++ (`&` operator)**: `ValueAddr()` is conceptually similar to C++'s address-of operator (`&`). `int x = 10; int* p = &x;` is analogous to [pseudocode]`var x = uc.DefineVariable("x=10"); var p = x.ValueAddr();`.

*   **vs. C# (`unsafe` context)**: In C#, getting the address of a managed variable requires an `unsafe` block and fixed pointers. uCalc provides a safer, managed way to achieve similar low-level memory access without leaving the managed environment, abstracting away the complexities of garbage collection and memory pinning.

**Examples:**

### Example ID: 82

**Description:** Pointer value with ValueAt

**Code:**
```pseudocode
uc.Format("Result = 'Answer: <' + Result + '>'");

var Dbl = uc.DefineVariable("MyDouble = 123.456");

wl(uc.ValueAt(Dbl.ValueAddr(), "Double"))
wl(uc.ValueAt(Dbl.ValueAddr(), BuiltInType::Float_Double))
wl(uc.ValueAt(Dbl.ValueAddr(), BuiltInType::Float_Double, true))


```

**Output:**
```
123.456
123.456
Answer: <123.456>
```

---

### Example ID: 86

**Description:** Returning a pointer with ReturnPtr

**Code:**
```pseudocode
[head]
[callback GetAddressOf]
   cb.ReturnPtr(cb.ArgItem(1).ValueAddr());
[/callback]
[body]

// This example is for sake of illustration
// There is already a built-in AddressOf() function

uc.DefineFunction("GetAddressOf(ByHandle Variable As AnyType) As SameTypeAs:0 Ptr", GetAddressOf);

uc.DefineVariable("MyVariable = 123.456");
uc.DefineVariable("MyStr = 'Hello world!'");

wl(uc.EvalStr("ValueAt(GetAddressOf(MyVariable))"))
wl(uc.EvalStr("ValueAt(GetAddressOf(MyStr))"))
```

**Output:**
```
123.456
Hello world!
```

---

### Example ID: 18

**Description:** DefineVariable; using pointers

**Code:**
```pseudocode
var Int8Var = uc.DefineVariable("x As Int8 = -1");
var Int16Var = uc.DefineVariable("y As Int16 = -1");
var StrVar = uc.DefineVariable("MyStr = 'Hello there'");
wl(uc.EvalStr("x"))
wl(uc.EvalStr("y"))
wl(uc.EvalStr("MyStr"))

var xPtr = uc.DefineVariable("xPtr As Pointer"); // General pointer
var yPtr = uc.DefineVariable("yPtr As Int16u Ptr"); // pointer specific to unsigned Int16
var yPtrB = uc.DefineVariable("yPtrB As Int16 Ptr = AddressOf(y)"); // Using AddressOf
var StrPtr = uc.DefineVariable("StrPtr As String Ptr");
xPtr.ValuePtr(Int8Var.ValueAddr()); // Sets the pointer address
yPtr.ValuePtr(Int16Var.ValueAddr()); // Note: address of signed Int16 going to an unsigned Ptr
StrPtr.ValuePtr(StrVar.ValueAddr());

// Note: for the ints we are now returning unsigned values; so -1 turns into positive numbers
wl(uc.EvalStr("ValueAt(Int8u, xPtr)")) // Type required because it's defined as generar pointer
wl(uc.EvalStr("ValueAt(yPtr)")) // Type name not needed because it's defined as Int16u Ptr
wl(uc.EvalStr("ValueAt(yPtrB)"))
wl(uc.EvalStr("ValueAt(StrPtr)"))

// Iterate through uc.ItemOf(ItemIs.DataType, n).Name()
// to see data type names you can use with ValueAt

var OtherInt = uc.DefineVariable("OtherInt As Int16 = 1234");
uc.DataTypeOf(BuiltInType::Integer_16).SetScalar(Int16Var.ValueAddr(), OtherInt.ValueAddr());

wl(uc.EvalStr("OtherInt"))
wl(uc.EvalStr("ValueAt(yPtrB)"))





```

**Output:**
```
-1
-1
Hello there
255
65535
-1
Hello there
1234
1234
```

---

---

## ValueAddr(ADDR) - ID: 595
/doc/reference/classes/ucalc.item/valueaddr/valueaddr-addr/

**Description:** Re-points a host-bound (proxy) variable to a new memory address at runtime.

**Syntax:** ValueAddr(ADDR)
**Parameters:**
newAddress - ADDR - The new memory address that the uCalc variable will point to. The data at this address must be compatible with the variable's defined data type.
**Return:** void - This method does not return a value.
**Remarks:**

This method re-points a host-bound uCalc variable to a new memory address in the host application. It is the setter for the [ValueAddr()](/reference/item/valueaddr) property and is a powerful tool for low-level memory integration.

### 🔗 Host-Bound (Proxy) Variables

This method applies *only* to variables that were created as proxies for data in your host application. A proxy variable is created by passing a memory address to [uCalc.DefineVariable()](/reference/ucalc/definevariable):

[pseudocode]`// Binds 'ucVar' to the memory location of 'hostVar'
var ucVar = uc.DefineVariable("myVar", AddressOf(hostVar));`

In this state, `ucVar` does not have its own storage within uCalc; it is simply a named reference to an external memory location.

### `ValueAddr()` vs. `Value()`

It is crucial to understand the difference between this method and the `Item.Value()` setter:

*   **`item.Value(newValue)`**: This changes the **data at the currently pointed-to memory address**. It modifies the value of the host variable.
*   **`item.ValueAddr(newAddress)`**: This changes the **address itself**. It makes the uCalc variable stop pointing to the old host variable and start pointing to a new one.

### 💡 Comparative Analysis

*   **vs. C++ Pointers**: This behavior is directly analogous to reassigning a pointer in C++.
    ```cpp
    int a = 10, b = 99;
    int* p = &a; // p points to a
    p = &b;      // Now p points to b. This is what ValueAddr() does.
    ```

*   **vs. C# References**: In safe C#, you cannot easily "re-seat" a reference (`ref`) variable to point to a different memory location after it has been initialized. uCalc's `ValueAddr()` provides a level of dynamic, low-level control that is typically only available in unsafe or unmanaged code, making it a powerful feature for high-performance integrations.

**Examples:**

---

## ValueBool - ID: 172
/doc/reference/classes/ucalc.item/valuebool/

---

## ValueBool() - ID: 173
/doc/reference/classes/ucalc.item/valuebool/valuebool-void/

**Description:** Retrieves the boolean value of a uCalc Item, with automatic type coercion from other data types.

**Syntax:** ValueBool()
**Return:** bool - Returns `true` or `false` representing the item's value. Performs type coercion if the item is not a boolean.
**Remarks:**

The `ValueBool()` method is the accessor for retrieving the value of a uCalc [Item](/Reference/uCalcBase/Item) as a boolean. It is the getter counterpart to the `ValueBool(bool)` setter.

This method is typically used on variables that have been explicitly defined as boolean using [DefineVariable](/Reference/uCalcBase/uCalc/DefineVariable):

[pseudocode]`var myFlag = uc.DefineVariable("myFlag As Bool = true");`
[pseudocode]`wl(myFlag.ValueBool()); // Outputs True`

### Automatic Type Coercion

A key feature of `ValueBool()` is its ability to perform type coercion at runtime. If the `Item` is not a boolean, uCalc will attempt to convert its value according to these rules:

*   **Numeric Types (`Int`, `Double`, etc.)**: A value of `0` is converted to `false`. Any non-zero value is converted to `true`.
*   **String Types**: An empty string (`""`) is converted to `false`. Any non-empty string is converted to `true`.

This behavior makes it easy to write flexible conditional logic without needing to manually check and convert types.

### Comparative Analysis

*   **vs. Native Properties (C#/C++)**: In a statically-typed language, you would access a boolean property directly (e.g., `myObject.IsEnabled`). A uCalc [Item](/Reference/uCalcBase/Item) is a generic, type-aware container. The `ValueBool()` method is a specialized accessor that queries the `Item` for its value and returns it as a specific type. This is closer to working with a `Dictionary<string, object>` or a `variant` type, where you must cast or convert the value after retrieving it. uCalc simplifies this by providing direct, type-safe accessor methods.

*   **Why uCalc?**: The power lies in runtime introspection. You can retrieve an [Item](/Reference/uCalcBase/Item) by its string name and then dynamically query its value as a boolean, all without compile-time knowledge of the variable. This is fundamental for building dynamic scripting and configuration engines.

**Examples:**

### Example ID: 75

**Description:** Checking if a uCalc object is the default with IsDefault

**Code:**
```pseudocode
var Status = uc.DefineVariable("Status As Bool");
wl(bool(Status.ValueBool()))

New(uCalc, MyuCalc)

Status.ValueBool(MyuCalc.@IsDefault());
wl(uc.EvalStr("$'MyuCalc is the current default? {Status}'"))

MyuCalc.@IsDefault(true);
Status.ValueBool(MyuCalc.@IsDefault());

wl(uc.EvalStr("$'MyuCalc is the current default? {Status}'"))
```

**Output:**
```
False
MyuCalc is the current default? false
MyuCalc is the current default? true
```

---

---

## ValueBool(bool) - ID: 174
/doc/reference/classes/ucalc.item/valuebool/valuebool-bool/

**Description:** Assigns a boolean value to a variable item from the host application.

**Syntax:** ValueBool(bool)
**Parameters:**
value - bool - The boolean value to assign to the variable item.
**Return:** void - This method does not return a value.
**Remarks:**

The `ValueBool` method provides a direct way for the host application to set the value of a uCalc variable that has been defined as a `Boolean` type.

This method is part of a family of type-specific setters (e.g., `ValueInt32`, `ValueStr`) that act as a bridge between your native code and the uCalc engine's internal state. It is the primary mechanism for updating variables programmatically without executing an expression string.

To retrieve the current value, use the getter overload: [ValueBool()](/reference/ucalc/item/valuebool/valuebool).

### 💡 Comparative Analysis

There are two ways to change a variable's value:

1.  **Programmatic (Host-Side)**: Using `item.ValueBool(true)`
    *   **Use Case**: When the host application needs to update the engine's state based on its own logic (e.g., user input in a checkbox, application state changes).
    *   **Performance**: Very fast, as it involves a direct memory write with no parsing overhead.

2.  **Expression-Based (Engine-Side)**: Using `uc.EvalStr("myVar = true")`
    *   **Use Case**: When the value change is the result of a user-written script or a calculation within the uCalc engine itself.
    *   **Performance**: Slower, as it requires the string to be parsed and evaluated.

In summary, use this `ValueBool(bool)` setter for efficient, direct state manipulation from your application code. Use an expression-based assignment when the logic resides within the user's script. See [DefineVariable](/reference/ucalc/item/definevariable) for more information on creating variables.

**Examples:**

### Example ID: 75

**Description:** Checking if a uCalc object is the default with IsDefault

**Code:**
```pseudocode
var Status = uc.DefineVariable("Status As Bool");
wl(bool(Status.ValueBool()))

New(uCalc, MyuCalc)

Status.ValueBool(MyuCalc.@IsDefault());
wl(uc.EvalStr("$'MyuCalc is the current default? {Status}'"))

MyuCalc.@IsDefault(true);
Status.ValueBool(MyuCalc.@IsDefault());

wl(uc.EvalStr("$'MyuCalc is the current default? {Status}'"))
```

**Output:**
```
False
MyuCalc is the current default? false
MyuCalc is the current default? true
```

---

---

## ValueByPtr - ID: 175
/doc/reference/classes/ucalc.item/valuebyptr/

**Description:** Sets the value of a variable by performing a direct memory copy from a given pointer address.

**Syntax:** ValueByPtr(POINTER)
**Parameters:**
valuePointer - POINTER - A pointer to the memory location of the source value to be copied.
**Return:** void - 
**Remarks:**

The `ValueByPtr` method performs a low-level, direct memory copy to set an [Item's](/reference/item/) value. It takes a pointer to a source value and copies the bytes from that memory location into the memory allocated for the target item.

This method is a "power-user" feature intended for performance-critical scenarios or for working with complex data types.

### ⚠️ Crucial Safety Note
This is a raw memory operation that bypasses uCalc's type-safety checks. The source and destination [DataTypes](/reference/datatype/) **must** be compatible and have the same byte size. Using this method with mismatched types can lead to memory corruption, unexpected behavior, or application instability.

### Comparative Analysis

*   **vs. `Value()` Setters**: Standard methods like `Item.Value(123)` or `Item.Value("abc")` are high-level and type-safe. `ValueByPtr` is low-level, potentially faster for large or complex data structures by avoiding type conversions, but sacrifices the safety guarantees of the standard methods.

*   **vs. `DefineVariable` with Memory Binding**: When you use `uc.DefineVariable("MyVar", &hostVar)`, you create a **persistent link** between the uCalc variable and the host variable. Changes are always synchronized. In contrast, `ValueByPtr` performs a **one-time copy** at the moment it is called. Subsequent changes to the source value will not affect the destination (see the internal test example below).

**Examples:**

### Example ID: 49

**Description:** Setting a variable value by pointer

**Code:**
```pseudocode
var x = uc.DefineVariable("x = 123");
var y = uc.DefineVariable("y");

y.ValueByPtr(x.ValueAddr());

wl(uc.Eval("x"))
wl(uc.Eval("y"))
```

**Output:**
```
123
123
```

---

---

## ValueByte - ID: 176
/doc/reference/classes/ucalc.item/valuebyte/

---

## ValueByte() - ID: 177
/doc/reference/classes/ucalc.item/valuebyte/valuebyte-void/

**Description:** Retrieves the 8-bit unsigned integer (byte) value associated with a uCalc Item.

**Syntax:** ValueByte()
**Return:** Byte - Returns the 8-bit unsigned integer (byte) value of the item.
**Remarks:**

The `ValueByte()` method retrieves the value of a uCalc [Item](/Reference/uCalcBase/Item/Constructor) as an 8-bit unsigned integer (a byte, 0-255).

This accessor is specifically designed for variables that have been defined with the `Byte` or `Integer_8u` data type using [DefineVariable](/Reference/uCalcBase/uCalc/DefineVariable). While you can call this method on an item of a different numeric type, the value will be cast, which may result in data loss or overflow if the original value is outside the 0-255 range.

This method is the getter counterpart to the setter, [ValueByte(byte)](/Reference/uCalcBase/Item/ValueByte/ValueByte).

### ⚖️ Comparative Analysis

In statically-typed languages like C# or C++, a variable is declared with a fixed type at compile time (e.g., `byte myValue = 10;`). Accessing it simply involves reading the variable.

uCalc operates at runtime. A uCalc [Item](/Reference/uCalcBase/Item/Constructor) is a more flexible container that can hold various data types. The `ValueByte()` method provides a type-safe way to retrieve the underlying value *as a byte*, ensuring that the host application receives the data in the expected format. This is part of a family of type-specific accessors (like `ValueInt32`, `ValueDbl`, etc.) that provide strong typing within a dynamic environment.

**Examples:**

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## ValueByte(Byte) - ID: 178
/doc/reference/classes/ucalc.item/valuebyte/valuebyte-byte/

**Description:** Sets the value of an Item that represents an 8-bit integer (byte) variable.

**Syntax:** ValueByte(Byte)
**Parameters:**
value - Byte - The 8-bit integer (byte) value to assign to the variable.
**Return:** void - This method does not return a value.
**Remarks:**

This method provides a type-safe way to assign a value to a uCalc [Item](/reference/item) that has been defined as an 8-bit integer, such as `Int8` or `Byte` ([BuiltInType::Integer_8u](/reference/enums/builtintype)). It is the counterpart to the getter version of `ValueByte()`.

It is more efficient than using the generic `Value(string)` overload, as it avoids the overhead of parsing and evaluating a string.

### Comparative Analysis

*   **vs. Native C#/C++**: In native code, you would assign a value directly (e.g., `myByte = 255;`). uCalc's `ValueByte` method provides a consistent API for dynamically manipulating the engine's internal variables at runtime, either by the `Item` handle or through its name. This allows the host application to interact with the uCalc state in a structured, type-safe manner without needing to bind variables directly to memory addresses.

*   **vs. `Item.Value(string)`**: The generic string-based setter is more flexible but less performant. It must parse and evaluate the input string before converting it to the target type. `ValueByte` is a direct, type-safe assignment that bypasses this process, making it ideal for performance-critical updates.

Use [DefineVariable](/reference/ucalc/definevariable) to create the variable before setting its value.

**Examples:**

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## ValueDbl - ID: 179
/doc/reference/classes/ucalc.item/valuedbl/

---

## ValueDbl() - ID: 180
/doc/reference/classes/ucalc.item/valuedbl/valuedbl-void/

**Description:** Retrieves the value of a uCalc Item, such as a variable, only if its data type is double-precision floating-point.

**Syntax:** ValueDbl()
**Return:** double - Returns the item's double-precision floating-point value. Returns 0 if the item's data type is not `Double`.
**Remarks:**

`ValueDbl()` is a type-safe accessor that retrieves the value of a uCalc [Item](/reference/item) if and only if its underlying data type is `Double`. It is the strict counterpart to the more general-purpose [Value()](/reference/item/value) method.

### Strict Typing vs. Flexible Conversion

It is crucial to understand the difference between `ValueDbl()` and the generic `Value()`:

*   **`ValueDbl()`**: This method is **strict**. It will only return a meaningful value if the [Item's](/reference/item) data type is `Double`. If called on a variable of a different type (e.g., `Integer`, `String`), it will return `0` or an otherwise invalid value without attempting a conversion.

*   **`Value()`**: This method is **flexible**. It defaults to returning a `double` and will actively attempt to *coerce* other types into a `double` (e.g., an `Integer` `123` becomes `123.0`, a `Boolean` `true` becomes `1.0`).

Choose `ValueDbl()` when your logic requires strict type safety and you want to ensure you are only working with double-precision floating-point numbers.

### 💡 Comparative Analysis

In a compiled language like C#, attempting to read an `int` as a `double` without an explicit cast is a compile-time error. uCalc, being a dynamic engine, handles this at runtime. The `ValueDbl()` method provides a way to enforce similar type safety within the uCalc environment.

*   **Safe Approach (`ValueDbl`)**: Guarantees you are retrieving a `Double`. Use this when the precision and type are critical.
*   **Convenient Approach (`Value`)**: Useful when you need a numeric representation of *any* variable and are comfortable with implicit type conversions.

To retrieve a variable's handle, use the [ItemOf()](/reference/ucalc/itemof) method.

**Examples:**

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## ValueDbl(double) - ID: 181
/doc/reference/classes/ucalc.item/valuedbl/valuedbl-double/

**Description:** Sets the value of a uCalc Item, but only if its data type is double-precision floating-point.

**Syntax:** ValueDbl(double)
**Parameters:**
value - double - The double-precision floating-point value to assign to the variable.
**Return:** void - This method does not return a value.
**Remarks:**

`ValueDbl(double)` is a type-safe method for setting the value of a uCalc [Item](/reference/item), such as a variable. It will only succeed if the target item's underlying data type is `Double`.

### Strict Typing vs. Flexible Conversion

It is crucial to understand the difference between this method and the more general `Value()` setters:

*   **`ValueDbl(double)` (Strict)**: This method requires the variable to already be a `Double`. If you attempt to use it on a variable of another type (e.g., `Integer` or `String`), the operation will fail silently, and the variable's value will not be changed.

*   **`Value(double)` or `Value(string)` (Flexible)**: The generic `Value` setters are more lenient. They will attempt to *coerce* or convert the input to the variable's target type. For example, calling `myIntItem.Value(5.5)` would successfully truncate the double and store `5` in the integer variable.

Use `ValueDbl(double)` when you need to guarantee type integrity and prevent accidental data loss or type conversions.

### 💡 Comparative Analysis

In a compiled language like C#, attempting to assign a `double` to an `int` variable without an explicit cast is a compile-time error. uCalc is a dynamic engine, so these checks happen at runtime. The `ValueDbl` method provides a programmatic way to enforce this type safety.

This is a critical feature for preventing logical errors in complex calculations where mixing data types could lead to unexpected results (e.g., loss of precision). By using the type-specific setters, you opt into a safer, more predictable way of manipulating variables programmatically.

**Examples:**

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## ValueInt16 - ID: 182
/doc/reference/classes/ucalc.item/valueint16/

---

## ValueInt16() - ID: 183
/doc/reference/classes/ucalc.item/valueint16/valueint16-void/

**Description:** Performs a direct memory read of a variable's value, reinterpreting the first 16 bits as a signed integer.

**Syntax:** ValueInt16()
**Return:** int16 - Returns a 16-bit integer
**Remarks:**

The `ValueInt16()` method is a low-level, high-performance accessor that reads the value of a uCalc [Item](/reference/ucalcbase/item/) by interpreting its first 16 bits (2 bytes) of memory as a signed integer (`short` in C#).

### ⚠️ Direct Memory Interpretation

This method **does not perform type checking or conversion**. It is a direct memory operation.

*   **Correct Usage**: When called on a variable that was defined as `Int16`, it correctly returns the variable's value.
*   **Incorrect Usage (Type Mismatch)**: When called on a variable of a different data type, this method performs a direct, low-level memory read. It reinterprets the first 2 bytes of the variable's stored value as a 16-bit signed integer, which can lead to unpredictable or meaningless results if the underlying data types are not compatible.
    *   **On an `Int32`**: It will read the lower 16 bits of the 32-bit integer.
    *   **On a `Double`**: It will read the first 2 bytes of the 8-byte floating-point representation, resulting in a value that is not numerically related to the original double.
    *   **On a `String`**: It will read the first 2 bytes of the internal string object's memory (which could be part of a pointer or length field), leading to unpredictable results.

For safe, type-converting access, use [ValueStr()](/reference/ucalcbase/item/valuestr) and parse the resulting string.

### 💡 Comparative Analysis

This method's behavior is analogous to low-level type punning operations in other languages, designed for performance at the cost of safety.

*   **vs. C++ `reinterpret_cast`**: Functionally similar to casting a pointer of one type to a `short*` and dereferencing it. It's a powerful tool for performance-critical code but bypasses the type system.
*   **vs. C# `BitConverter.ToInt16`**: Similar to taking the first two bytes from another type's byte array and converting them to a `short`.

Use this method only when performance is critical and the data type is guaranteed.

**Examples:**

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## ValueInt16(int16) - ID: 184
/doc/reference/classes/ucalc.item/valueint16/valueint16-int16/

**Description:** Sets the value of a uCalc variable defined as a 16-bit integer (signed or unsigned).

**Syntax:** ValueInt16(int16)
**Parameters:**
value - int16 - The 16-bit integer value to assign to the variable.
**Return:** void - 
**Remarks:**

This method provides a direct and type-safe way to set the value of a uCalc variable that has been defined as a 16-bit integer (`Int16` or `Int16u`).

It is more efficient than the generic [Item.Value(string)](/Reference/uCalcBase/Item/Value) setter because it avoids the overhead of parsing and evaluating a string expression.

### Signed and Unsigned Handling

This method accepts a signed 16-bit integer. When the target uCalc variable is defined as unsigned (`Int16u`), the bit pattern of the input value is reinterpreted. For example, passing `-1` (which is `0xFFFF` in two's complement) to an unsigned variable will result in the value `65535`.

### ⚙️ Comparative Analysis

*   **vs. `Item.Value(string)`**: Using [pseudocode]`myVar.Value("123")` involves the parser, which is flexible but slower. `ValueInt16(123)` is a direct memory operation and should be preferred in performance-critical code where the type is known.
*   **vs. Native Assignment**: In C# or C++, you would simply use `myVar = 123;`. In uCalc, interaction is through the [Item](/Reference/uCalcBase/Item) object, which acts as a proxy to the engine's internal state. This method is the uCalc equivalent of that direct assignment for 16-bit integers.

Use this method after creating a variable with [DefineVariable](/Reference/uCalcBase/uCalc/DefineVariable).

**Examples:**

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## ValueInt32 - ID: 185
/doc/reference/classes/ucalc.item/valueint32/

---

## ValueInt32() - ID: 186
/doc/reference/classes/ucalc.item/valueint32/valueint32-void/

**Description:** Retrieves the 32-bit integer value of an item, typically a variable, without performing type conversion.

**Syntax:** ValueInt32()
**Return:** int32 - The 32-bit signed integer value of the item.
**Remarks:**

### ⚙️ Overview

The `ValueInt32()` method is a direct, type-safe accessor for retrieving the 32-bit integer value of a uCalc [Item](/reference/ucalc/item). It is primarily used to get the current value of a variable that was explicitly defined with the `Int32` (or `Int`) data type using [DefineVariable](/reference/ucalc/definevariable).

This method is part of a family of type-specific accessors, including `Value()`, `ValueStr()`, `ValueBool()`, etc. Using the most specific accessor for a variable's type is more efficient than retrieving a string representation and converting it.

### 🛡️ Type Safety: No Implicit Conversions

A key behavior of `ValueInt32()` is that it **does not perform type conversions**. It expects the underlying data of the [Item](/reference/ucalc/item) to be a 32-bit integer.

*   **Correct Usage**: Calling `ValueInt32()` on a variable defined as `Int` or `Int32`.
*   **Incorrect Usage**: If called on an [Item](/reference/ucalc/item) of a different type (e.g., a `Double` or `String`), it will not attempt to parse or cast the value.

This strictness ensures type integrity and prevents unexpected behavior from implicit conversions.

### 💡 Comparative Analysis

*   **vs. Native Variable Access (C#/C++)**
    In native code, you access a variable's value directly (e.g., `int myVal = myIntObject.Value;`). uCalc abstracts this behind the versatile [Item](/reference/ucalc/item) object. While this adds a layer of indirection, it provides significant benefits for dynamic environments. You can write generic code that inspects any `Item`—retrieving its name, type, and value through a consistent interface—which is ideal for building tools like debuggers, watch windows, or property editors.

*   **vs. `Value()` and `ValueStr()`**
    The generic `Value()` and `ValueStr()` methods are more flexible, as they will attempt to convert any numeric or string type. However, `ValueInt32()` is more performant when you know the variable is an integer, as it avoids the overhead of type checking and conversion.

**Examples:**

### Example ID: 17

**Description:** DefineVariable examples

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var MyInt = uc.DefineVariable("MyInt As Int");
var MyStr = uc.DefineVariable("MyStr As String");
uc.DefineVariable("OtherStr = 'string type inferred'");
uc.DefineVariable("MyInt16 = Int16(100/3)"); // type inferred
uc.DefineVariable("MyBool = True"); // type inferred
uc.DefineVariable("MyComplex = 3 + 4*#i"); // type inferred

MyVar.Value(123);
MyInt.ValueInt32(456);
MyStr.ValueStr("This is a test");

wl("MyVar = " + uc.EvalStr("MyVar"))
wl("MyInt = " + uc.EvalStr("MyInt"))
wl("MyStr = " + uc.EvalStr("MyStr"))
wl("OtherStr = " + uc.EvalStr("OtherStr"))
wl("MyInt16 = " + uc.EvalStr("MyInt16"))
wl("MyBool = " + uc.EvalStr("MyBool"))
wl("MyComplex = " + uc.EvalStr("MyComplex"))
wl("---")
wl(MyVar.Value())
wl(MyInt.ValueInt32())
wl(MyStr.ValueStr())
wl("---")
wl(uc.ItemOf("MyVar").@DataType().@Name())
wl(uc.ItemOf("MyInt").@DataType().@Name())
wl(uc.ItemOf("MyStr").@DataType().@Name())
wl(uc.ItemOf("OtherStr").@DataType().@Name())
wl(uc.ItemOf("MyInt16").@DataType().@Name())
wl(uc.ItemOf("MyBool").@DataType().@Name())
wl("---")

var Expression = "x^2 * 10";
var VarX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse(Expression);

w("Expression = ")
wl(Expression)
for (int x = 1 to 10)
   VarX.Value(x); // In C++ you can skip this by passing &x to DefineVariable
   wl("x = " + VarX.ValueStr() + "  Result = " + ParsedExpr.EvaluateStr())
end for

ParsedExpr.Release();
VarX.Release();
```

**Output:**
```
MyVar = 123
MyInt = 456
MyStr = This is a test
OtherStr = string type inferred
MyInt16 = 33
MyBool = true
MyComplex = 3+4i
---
123
456
This is a test
---
double
int
string
string
int16
bool
---
Expression = x^2 * 10
x = 1  Result = 10
x = 2  Result = 40
x = 3  Result = 90
x = 4  Result = 160
x = 5  Result = 250
x = 6  Result = 360
x = 7  Result = 490
x = 8  Result = 640
x = 9  Result = 810
x = 10  Result = 1000
```

---

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## ValueInt32(int32) - ID: 187
/doc/reference/classes/ucalc.item/valueint32/valueint32-int32/

**Description:** Sets the value of a 32-bit integer variable.

**Syntax:** ValueInt32(int32)
**Parameters:**
value - int32 - The 32-bit integer value to assign to the variable.
**Return:** void - This method does not return a value.
**Remarks:**

# 📝 Setting Integer Values Programmatically

The `ValueInt32` method provides a direct and type-safe way to set the value of a uCalc variable that holds a 32-bit integer. It is the most common setter for variables defined as `Int` or `Int32`.

### ⚙️ Core Usage

This method is used after a variable has been created with a method like [DefineVariable](/reference/ucalcbase/ucalc/definevariable). It allows the host application to update the variable's state before an expression is evaluated.

```pseudocode
// 1. Define an integer variable
var myCounter = uc.DefineVariable("myCounter As Int");

// 2. Set its value using ValueInt32
myCounter.ValueInt32(100);

// 3. Use it in an expression
wl(uc.EvalStr("myCounter * 2")); // Outputs: 200
```

This method handles both signed (`Int32`) and unsigned (`Int32u`) variables correctly. When setting an unsigned variable, the bit pattern is preserved. For example, setting an `Int32u` variable to `-1` will result in the value `4294967295`.

### 🆚 Comparative Analysis: Performance and Approach

There are three primary ways to manage variable values in uCalc, each with different performance characteristics.

1.  **`ValueInt32` (Type-Safe Setter - Recommended)**
    *   **Pros**: Fast, type-safe, and avoids string parsing overhead.
    *   **Cons**: Requires a specific method call for each data type.
    *   **Best for**: Updating variables in performance-critical loops.

2.  **`Value(string)` (Expression-Based Setter)**
    *   **Pros**: Flexible; can set a variable of any type from a string expression.
    *   **Cons**: Slower, as it involves parsing and evaluating the input string.
    *   **Best for**: Setting values from user input or configuration files.

3.  **Direct Memory Binding (Highest Performance)**
    *   When defining the variable with [DefineVariable](/reference/ucalcbase/ucalc/definevariable), you can pass a pointer to a host application variable. The uCalc variable becomes a direct proxy to your native variable, eliminating the need for any setter calls.
    *   **Pros**: The fastest possible method, zero overhead per update.
    *   **Cons**: Requires more complex setup, especially in managed languages like C#.
    *   **Best for**: High-frequency updates in scientific simulations or real-time systems.

In summary, `ValueInt32` offers the best balance of performance, safety, and ease of use for programmatically updating integer variables.

**Examples:**

### Example ID: 17

**Description:** DefineVariable examples

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var MyInt = uc.DefineVariable("MyInt As Int");
var MyStr = uc.DefineVariable("MyStr As String");
uc.DefineVariable("OtherStr = 'string type inferred'");
uc.DefineVariable("MyInt16 = Int16(100/3)"); // type inferred
uc.DefineVariable("MyBool = True"); // type inferred
uc.DefineVariable("MyComplex = 3 + 4*#i"); // type inferred

MyVar.Value(123);
MyInt.ValueInt32(456);
MyStr.ValueStr("This is a test");

wl("MyVar = " + uc.EvalStr("MyVar"))
wl("MyInt = " + uc.EvalStr("MyInt"))
wl("MyStr = " + uc.EvalStr("MyStr"))
wl("OtherStr = " + uc.EvalStr("OtherStr"))
wl("MyInt16 = " + uc.EvalStr("MyInt16"))
wl("MyBool = " + uc.EvalStr("MyBool"))
wl("MyComplex = " + uc.EvalStr("MyComplex"))
wl("---")
wl(MyVar.Value())
wl(MyInt.ValueInt32())
wl(MyStr.ValueStr())
wl("---")
wl(uc.ItemOf("MyVar").@DataType().@Name())
wl(uc.ItemOf("MyInt").@DataType().@Name())
wl(uc.ItemOf("MyStr").@DataType().@Name())
wl(uc.ItemOf("OtherStr").@DataType().@Name())
wl(uc.ItemOf("MyInt16").@DataType().@Name())
wl(uc.ItemOf("MyBool").@DataType().@Name())
wl("---")

var Expression = "x^2 * 10";
var VarX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse(Expression);

w("Expression = ")
wl(Expression)
for (int x = 1 to 10)
   VarX.Value(x); // In C++ you can skip this by passing &x to DefineVariable
   wl("x = " + VarX.ValueStr() + "  Result = " + ParsedExpr.EvaluateStr())
end for

ParsedExpr.Release();
VarX.Release();
```

**Output:**
```
MyVar = 123
MyInt = 456
MyStr = This is a test
OtherStr = string type inferred
MyInt16 = 33
MyBool = true
MyComplex = 3+4i
---
123
456
This is a test
---
double
int
string
string
int16
bool
---
Expression = x^2 * 10
x = 1  Result = 10
x = 2  Result = 40
x = 3  Result = 90
x = 4  Result = 160
x = 5  Result = 250
x = 6  Result = 360
x = 7  Result = 490
x = 8  Result = 640
x = 9  Result = 810
x = 10  Result = 1000
```

---

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## ValueInt64 - ID: 188
/doc/reference/classes/ucalc.item/valueint64/

---

## ValueInt64() - ID: 189
/doc/reference/classes/ucalc.item/valueint64/valueint64-void/

**Description:** Retrieves the 64-bit integer value from a uCalc variable.

**Syntax:** ValueInt64()
**Return:** int64 - The 64-bit integer value of the variable.
**Remarks:**

#  Retrieving 64-bit Integer Values

The `ValueInt64()` method provides a direct, type-safe way to retrieve the value of a uCalc variable defined as a 64-bit integer (`Int64` or `Int64u`).

### Core Usage

This method is the counterpart to the `ValueInt64` setter. It is used to access the current value of a variable from the host application, typically after it has been manipulated by a uCalc expression or set programmatically.

```pseudocode
// Define a 64-bit integer variable
var myId = uc.DefineVariable("myId As Int64");

// Set its value
myId.ValueInt64(9007199254740991);

// Retrieve its value using the type-safe getter
var(int64_t, retrievedId) = myId.ValueInt64();
wl("Retrieved ID: ", retrievedId);
```

### 🆚 Comparative Analysis: Why Use a Type-Specific Getter?

While uCalc offers several ways to retrieve a variable's value, `ValueInt64()` is the best choice for 64-bit integers due to performance and data integrity.

1.  **`ValueInt64()` (Type-Safe Getter - Recommended)**
    *   **Pros**: Fastest method, returns the exact binary value without conversion, and preserves the full precision of 64-bit integers.
    *   **Cons**: Specific to one data type.
    *   **Best for**: Performance-critical code and handling large numbers like timestamps, database IDs, or financial calculations.

2.  **`Value()` (Generic Getter - Potential Precision Loss)**
    *   This method always returns a `double`. While convenient, a `double` only has about 15-17 decimal digits of precision. A 64-bit integer can have up to 19 digits. Using `Value()` on large `Int64` values **will result in precision loss**.
    *   **Best for**: General-purpose numeric retrieval where maximum precision is not critical.

3.  **`ValueStr()` (String-Based Getter)**
    *   This method returns the value as a string. It preserves precision but is slower due to the overhead of converting the number to a string and subsequent parsing if you need to use it as a number in your host application.
    *   **Best for**: Displaying values or when a string representation is the desired final format.

In summary, always use `ValueInt64()` to retrieve `Int64` or `Int64u` variables to guarantee both speed and data integrity.

**Examples:**

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## ValueInt64(int64) - ID: 190
/doc/reference/classes/ucalc.item/valueint64/valueint64-int64/

**Description:** Sets the value of a uCalc variable to a specified 64-bit integer.

**Syntax:** ValueInt64(int64)
**Parameters:**
value - int64 - The 64-bit integer value to assign to the variable.
**Return:** void - This method does not return a value.
**Remarks:**

# 📝 Setting 64-bit Integer Values Programmatically

The `ValueInt64` method provides a direct and type-safe way to set the value of a uCalc variable that holds a 64-bit integer. It is the primary setter for variables defined as `Int64` or `Long`.

### ⚙️ Core Usage

This method is used after a variable has been created with a method like `DefineVariable`. It allows the host application to update the variable's state before an expression is evaluated, which is crucial for performance.

```pseudocode
// 1. Define a 64-bit integer variable for a database record ID
var recordId = uc.DefineVariable("recordId As Int64");

// 2. Set its value using ValueInt64
recordId.ValueInt64(8192837123981273);

// 3. Use it in an expression
wl(uc.EvalStr("recordId")); // Outputs: 8192837123981273
```

This method handles both signed (`Int64`) and unsigned (`Int64u`) variables correctly. When setting an unsigned variable, the bit pattern is preserved. For example, setting an `Int64u` variable to `-1` will result in its maximum possible value, `18446744073709551615`.

### 🆚 Comparative Analysis: Performance and Approach

There are three primary ways to manage variable values in uCalc, each with different performance characteristics.

1.  **`ValueInt64` (Type-Safe Setter - Recommended)**
    *   **Pros**: Fast, type-safe, and avoids string parsing overhead.
    *   **Cons**: Requires a specific method call for each data type.
    *   **Best for**: Updating variables in performance-critical loops where values are already available as native 64-bit integers.

2.  **`Value(string)` (Expression-Based Setter)**
    *   **Pros**: Flexible; can set a variable of any type from a string expression.
    *   **Cons**: Slower, as it involves parsing and evaluating the input string.
    *   **Best for**: Setting values from user input or configuration files where performance is not the primary concern.

3.  **Direct Memory Binding (Highest Performance)**
    *   When defining the variable with `DefineVariable`, you can pass a pointer to a host application variable. The uCalc variable becomes a direct proxy to your native variable, eliminating the need for any setter calls.
    *   **Pros**: The fastest possible method, zero overhead per update.
    *   **Cons**: Requires more complex setup, especially in managed languages like C#.
    *   **Best for**: High-frequency updates in scientific simulations, financial modeling, or real-time systems.

In summary, [pseudocode]`ValueInt64` offers the best balance of performance, safety, and ease of use for programmatically updating 64-bit integer variables.

**Examples:**

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## ValuePtr - ID: 191
/doc/reference/classes/ucalc.item/valueptr/

---

## ValuePtr() - ID: 192
/doc/reference/classes/ucalc.item/valueptr/valueptr-void/

**Description:** Retrieves the pointer value stored within a pointer-type variable.

**Syntax:** ValuePtr()
**Return:** IntPtr - The memory address stored in the variable as a pointer.
**Remarks:**

The `ValuePtr()` method retrieves the value of an [Item](/reference/ucalc/item/constructor) that is defined as a pointer type. This allows you to work with memory addresses within the uCalc engine, enabling powerful interoperability with native code.

### `ValuePtr()` vs. `ValueAddr()`

Understanding the difference between `ValuePtr()` and `ValueAddr()` is crucial for correct pointer manipulation. They answer two different questions:

*   **`ValueAddr()`**: "What is the memory address *of this variable*?" (like `&myVar` in C++).
*   **`ValuePtr()`**: "What is the memory address *stored inside this variable*?" (like `myPtrVar` in C++, where `myPtrVar` holds an address).

| Method | Analogy (C++) | Description | Use Case |
| :--- | :--- | :--- | :--- |
| `item.ValueAddr()` | `&variable` | Returns the memory address where the item's own value is stored. | Getting a pointer *to* a variable to pass to another function. |
| `item.ValuePtr()` | `pointer_variable` | Returns the value *contained within* the item, assuming that value is a pointer. | Dereferencing a pointer variable that you have already stored. |

This is best illustrated by the `AddressOf` function. When you define a pointer variable like `xPtr As Ptr = AddressOf(x)`, the `ValuePtr()` of `xPtr` will be equal to the `ValueAddr()` of `x`.

### Why uCalc? (Comparative Analysis)

*   **vs. C++ `void*` / `reinterpret_cast`**: In C++, working with generic pointers often involves unsafe casting and manual memory management. uCalc provides a managed environment where pointer variables are still strongly typed (e.g., `Int Ptr`, `String Ptr`), reducing the risk of type-related memory errors.

*   **vs. C# `IntPtr` and `unsafe` code**: To achieve similar functionality in C#, you would typically need to enter an `unsafe` code block and work with raw pointers. uCalc abstracts this away, providing a safe, cross-language mechanism to pass memory references between the scripting engine and the host application without requiring `unsafe` contexts in your C# code.

This makes `ValuePtr()` a key feature for building high-performance bridges between uCalc expressions and native libraries.

**Examples:**

### Example ID: 102

**Description:** Using ValuePtr

**Code:**
```pseudocode
var xVar = uc.DefineVariable("x = 123");
var xVarPtr = uc.DefineVariable("xPtr As Double Ptr = AddressOf(x)");

wl(bool((xVarPtr.ValuePtr() == xVar.ValueAddr())))
```

**Output:**
```
True
```

---

---

## ValuePtr(POINTER) - ID: 193
/doc/reference/classes/ucalc.item/valueptr/valueptr-pointer/

**Description:** Sets the memory address stored within a pointer-type variable, changing what the variable points to.

**Syntax:** ValuePtr(POINTER)
**Parameters:**
pointerAddress - POINTER - The memory address to be stored in the pointer variable.
**Return:** void - This method does not return a value.
**Remarks:**

The `ValuePtr(POINTER)` method sets the memory address stored within a pointer-type variable, effectively changing which memory location the variable points to. It is the primary way to programmatically assign a target to a pointer that has been defined using [DefineVariable](/reference/ucalc/definevariable).

### `ValuePtr()` vs. `ValueAddr()`

Understanding the difference between these concepts is crucial for pointer manipulation:

*   **`item.ValueAddr()`**: Gets the address *of the item itself*.
*   **`item.ValuePtr(address)`**: Sets the value *stored inside the item* to be a new address.

This method is the programmatic equivalent of the `=` assignment operator for pointers in an expression. The following are functionally identical:

```pseudocode
// Programmatic assignment
ptrVar.ValuePtr(targetVar.ValueAddr());

// Expression-based assignment
uc.Eval("ptrVar = AddressOf(targetVar)");
```

### Why uCalc? (Comparative Analysis)

In native languages, pointer assignment is a fundamental but low-level operation.

*   **vs. C++**: The uCalc line `ptr.ValuePtr(target.ValueAddr())` is the safe, managed equivalent of the C++ statement `ptr = &target;`. uCalc's system ensures that pointer types are handled correctly across the C++/C#/VB language barrier.
*   **vs. C# `unsafe` code**: To manipulate pointers directly in C#, you typically need to use an `unsafe` block, which introduces complexity and potential instability. uCalc provides a safe abstraction layer, allowing you to perform pointer assignments without leaving the managed code environment.

This makes `ValuePtr` a key feature for creating high-performance links between uCalc variables and data buffers in the host application.

**Examples:**

### Example ID: 18

**Description:** DefineVariable; using pointers

**Code:**
```pseudocode
var Int8Var = uc.DefineVariable("x As Int8 = -1");
var Int16Var = uc.DefineVariable("y As Int16 = -1");
var StrVar = uc.DefineVariable("MyStr = 'Hello there'");
wl(uc.EvalStr("x"))
wl(uc.EvalStr("y"))
wl(uc.EvalStr("MyStr"))

var xPtr = uc.DefineVariable("xPtr As Pointer"); // General pointer
var yPtr = uc.DefineVariable("yPtr As Int16u Ptr"); // pointer specific to unsigned Int16
var yPtrB = uc.DefineVariable("yPtrB As Int16 Ptr = AddressOf(y)"); // Using AddressOf
var StrPtr = uc.DefineVariable("StrPtr As String Ptr");
xPtr.ValuePtr(Int8Var.ValueAddr()); // Sets the pointer address
yPtr.ValuePtr(Int16Var.ValueAddr()); // Note: address of signed Int16 going to an unsigned Ptr
StrPtr.ValuePtr(StrVar.ValueAddr());

// Note: for the ints we are now returning unsigned values; so -1 turns into positive numbers
wl(uc.EvalStr("ValueAt(Int8u, xPtr)")) // Type required because it's defined as generar pointer
wl(uc.EvalStr("ValueAt(yPtr)")) // Type name not needed because it's defined as Int16u Ptr
wl(uc.EvalStr("ValueAt(yPtrB)"))
wl(uc.EvalStr("ValueAt(StrPtr)"))

// Iterate through uc.ItemOf(ItemIs.DataType, n).Name()
// to see data type names you can use with ValueAt

var OtherInt = uc.DefineVariable("OtherInt As Int16 = 1234");
uc.DataTypeOf(BuiltInType::Integer_16).SetScalar(Int16Var.ValueAddr(), OtherInt.ValueAddr());

wl(uc.EvalStr("OtherInt"))
wl(uc.EvalStr("ValueAt(yPtrB)"))





```

**Output:**
```
-1
-1
Hello there
255
65535
-1
Hello there
1234
1234
```

---

---

## ValueSng - ID: 194
/doc/reference/classes/ucalc.item/valuesng/

---

## ValueSng() - ID: 195
/doc/reference/classes/ucalc.item/valuesng/valuesng-void/

**Description:** Retrieves the value of a variable defined as a single-precision (32-bit) floating-point number.

**Syntax:** ValueSng()
**Return:** float - Returns a Single precision value
**Remarks:**

This method provides direct, high-performance access to the value of a variable that was explicitly defined with the `Single` data type.

### 🎯 Purpose and Use Cases

A single-precision float uses 32 bits of memory, offering a balance between range and precision that is suitable for many applications. It is particularly useful in memory-sensitive scenarios where the full 64-bit precision of a `Double` is unnecessary, such as:
*   Storing large arrays of 3D coordinates in graphics or game development.
*   Processing large batches of sensor or signal data.
*   Any situation where memory usage can be halved by reducing floating-point precision without a significant impact on accuracy.

This is the getter counterpart to the setter method, which takes a float as an argument (e.g., [pseudocode]`.ValueSng(1.23)`).

### 💡 Comparative Analysis

*   **vs. Native Type Casting (e.g., C# `(float)obj`)**: In native languages, you often cast a generic `object` or `variant` to the desired type, which can lead to runtime errors if the cast is invalid. uCalc's [Item](/Reference/uCalcBase/Item) provides a type-safe accessor. Calling `ValueSng()` on an [Item](/Reference/uCalcBase/Item) that is not of type `Single` will not perform an implicit conversion.

*   **vs. `uc.EvalStr("MyVar")`**: Retrieving a value via [EvalStr](/Reference/uCalcBase/uCalc/EvalStr) involves a multi-step process: the engine must look up the symbol name, evaluate it, and format the result as a string. In contrast, [pseudocode]`myItem.ValueSng()` is a direct memory access operation, making it significantly faster and the preferred method for performance-critical code, especially within loops.

*   **vs. Direct Memory Binding**: For ultimate performance, the [DefineVariable](/Reference/uCalcBase/uCalc/DefineVariable) method allows you to bind a uCalc variable directly to the memory address of a variable in your host application (e.g., via pointers in C++ or an `unsafe` context in C#). When a variable is bound this way, its value is always synchronized with the host, making explicit calls to `ValueSng()` unnecessary. `ValueSng()` remains the best practice for safe, programmatic access when direct memory binding is not used.

**Examples:**

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## ValueSng(float) - ID: 196
/doc/reference/classes/ucalc.item/valuesng/valuesng-float/

**Description:** Sets the value of a variable that was defined with the 'Single' (32-bit float) data type.

**Syntax:** ValueSng(float)
**Parameters:**
value - float - The single-precision floating-point value to assign to the variable.
**Return:** void - This method does not return a value.
**Remarks:**

This method sets the value of a uCalc variable that was specifically defined as a `Single` (a 32-bit floating-point number).

It is the type-safe and recommended way to update single-precision variables from your host application. The variable must first be created using a method like [DefineVariable](/reference/ucalc/definevariable), explicitly specifying the type:

[pseudocode]`var myFloat = uc.DefineVariable("myFloat As Single");`
[pseudocode]`myFloat.ValueSng(1.23);`

### Comparative Analysis

*   **vs. `Value(string)`**: You could set the value using the generic string-based `Value("1.23")`, but `ValueSng` is more efficient. It avoids the overhead of parsing and evaluating a string, passing the native `float` value directly to the engine.

*   **vs. Direct Memory Binding**: For maximum performance in C++ or `unsafe` C#, you can bind a uCalc variable directly to a host variable's memory address when calling [DefineVariable](/reference/ucalc/definevariable). This creates a live link, eliminating the need for setter methods entirely. `ValueSng` provides a safe, cross-platform alternative that does not require direct memory manipulation.

**Examples:**

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## ValueStr - ID: 197
/doc/reference/classes/ucalc.item/valuestr/

**Examples:**

### Example ID: 13

**Description:** Passing arg ByHandle to retrieve meta data such as arg data type; and AnyType

**Code:**
```pseudocode
[head]
[callback DisplayArgs]
for(int x = 1 to cb.ArgCount())
   wl(cb.ArgItem(x).ValueStr() + "  Type: " + cb.ArgItem(x).@DataType().@Name())
end for
[/callback]
[body]
uc.DefineFunction("DisplayArgs(ByHandle Arg As AnyType ...)", DisplayArgs);
uc.Eval("DisplayArgs(5, 3+2*#i, 'Hello', True, False, Int16(5+4.1))");
```

**Output:**
```
5  Type: double
3+2i  Type: complex
Hello  Type: string
true  Type: bool
false  Type: bool
9  Type: int16
```

---

### Example ID: 32

**Description:** Displaying Integer (Int32) results with Evaluate32

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");

var ParsedExpr = uc.Parse("x / 2", "Integer"); // Causes output of "x / 2" to convert to an integer

// NOTE: EvaluateInt32 should only be used when Parse() explicitly specifies Integer
// (Or Int, or Int32) as the second argument, or if the expression evaluates to an integer
// (such as evaluating a variable that was explicitly defined as integer;
// other arithmetic operators typically evaluate to Double floating point).

for (double x = 1 to 10)
   VariableX.Value(x);
   wl("x = " + VariableX.ValueStr() + "  Result = " + to_string(ParsedExpr.EvaluateInt32()))
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  Result = 0
x = 2  Result = 1
x = 3  Result = 1
x = 4  Result = 2
x = 5  Result = 2
x = 6  Result = 3
x = 7  Result = 3
x = 8  Result = 4
x = 9  Result = 4
x = 10  Result = 5
```

---

---

## ValueStr(bool) - ID: 198
/doc/reference/classes/ucalc.item/valuestr/valuestr-bool/

**Description:** Retrieves the value of a uCalc item as a string, with optional custom formatting, converting from any data type.

**Syntax:** ValueStr(bool)
**Parameters:**
formatOutput - bool [default = false] - If true, the output string is processed by any custom formatters defined with uCalc.Format. If false, the raw default string representation is returned.
**Return:** string - The string representation of the item's value.
**Remarks:**

The `ValueStr()` method is the universal accessor for retrieving the value of any [Item](/reference/item) as a string. It serves two primary functions: converting any data type to its string representation and optionally applying a sophisticated, user-defined formatting pipeline.

### Universal Type Conversion

This method acts as a robust, all-purpose converter. Unlike type-specific getters (e.g., `ValueInt32`, `ValueDbl`), `ValueStr()` works on an item of any data type, automatically handling the conversion to a human-readable string. This makes it the ideal choice for logging, debugging, and displaying values in a user interface.

### The Formatting Pipeline

The `formatOutput` parameter is a powerful switch that controls whether the string result is processed by uCalc's formatting engine.

*   **`ValueStr(false)` (Default)**: Returns the raw, default string representation of the value (e.g., a number like `99.5`).
*   **`ValueStr(true)`**: Passes the raw string through the formatting pipeline defined by [uCalc.Format](/reference/ucalc/format). This allows for centralized and declarative control over output appearance, such as formatting numbers as currency (`$99.50`) or dates into a specific layout.

### Comparative Analysis

*   **vs. C# `.ToString()` / C++ `std::to_string`**: While similar in purpose, `ValueStr` is more versatile. Standard library functions typically require the developer to apply formatting imperatively at every call site (e.g., `value.ToString("C2")`). uCalc's model is declarative: you define the formatting rules once with [uCalc.Format](/reference/ucalc/format), and `ValueStr(true)` applies them automatically everywhere, separating the presentation logic from the data retrieval logic.

*   **vs. other `Value...` methods**: Methods like `Value()` or `ValueInt32()` return raw data types for computational use. `ValueStr()` is specifically for presentation and display. It is the only `Value` accessor that supports the custom formatting pipeline.

**Examples:**

### Example ID: 103

**Description:** Using ValueStr()

**Code:**
```pseudocode
var MyStr = uc.DefineVariable("MyStr As String");
var MyDbl = uc.DefineVariable("MyDbl As Double");
var MyCplx = uc.DefineVariable("MyCplx As Complex");
var MyBool = uc.DefineVariable("MyBool As Boolean");

MyStr.ValueStr("Hello world!");
MyDbl.ValueStr("123.456");
MyCplx.ValueStr("3+4*#i");
MyBool.ValueStr("True");

wl(uc.EvalStr("$'MyStr = {MyStr}'"))
wl(uc.EvalStr("$'MyDbl = {MyDbl}'"))
wl(uc.EvalStr("$'MyCplx = {MyCplx}'"))
wl(uc.EvalStr("$'MyBool = {MyBool}'"))
wl("---")
wl(MyStr.ValueStr())
wl(MyDbl.ValueStr())
wl(MyCplx.ValueStr())
wl(MyBool.ValueStr())
```

**Output:**
```
MyStr = Hello world!
MyDbl = 123.456
MyCplx = 3+4i
MyBool = true
---
Hello world!
123.456
3+4i
true
```

---

### Example ID: 93

**Description:** EvaluateBool, also ValueStr which converts numeric value to string

**Code:**
```pseudocode

var VariableX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse("x > 3"); // The > operation returns a Boolean instead of the default floating point

for (double x = 1 to 5)
   VariableX.Value(x);
   wl("x = ", VariableX.ValueStr(), "  x > 3 is ", bool(ParsedExpr.EvaluateBool()))
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  x > 3 is False
x = 2  x > 3 is False
x = 3  x > 3 is False
x = 4  x > 3 is True
x = 5  x > 3 is True
```

---

### Example ID: 32

**Description:** Displaying Integer (Int32) results with Evaluate32

**Code:**
```pseudocode
var VariableX = uc.DefineVariable("x");

var ParsedExpr = uc.Parse("x / 2", "Integer"); // Causes output of "x / 2" to convert to an integer

// NOTE: EvaluateInt32 should only be used when Parse() explicitly specifies Integer
// (Or Int, or Int32) as the second argument, or if the expression evaluates to an integer
// (such as evaluating a variable that was explicitly defined as integer;
// other arithmetic operators typically evaluate to Double floating point).

for (double x = 1 to 10)
   VariableX.Value(x);
   wl("x = " + VariableX.ValueStr() + "  Result = " + to_string(ParsedExpr.EvaluateInt32()))
end for

ParsedExpr.Release();
VariableX.Release();
```

**Output:**
```
x = 1  Result = 0
x = 2  Result = 1
x = 3  Result = 1
x = 4  Result = 2
x = 5  Result = 2
x = 6  Result = 3
x = 7  Result = 3
x = 8  Result = 4
x = 9  Result = 4
x = 10  Result = 5
```

---

### Example ID: 17

**Description:** DefineVariable examples

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var MyInt = uc.DefineVariable("MyInt As Int");
var MyStr = uc.DefineVariable("MyStr As String");
uc.DefineVariable("OtherStr = 'string type inferred'");
uc.DefineVariable("MyInt16 = Int16(100/3)"); // type inferred
uc.DefineVariable("MyBool = True"); // type inferred
uc.DefineVariable("MyComplex = 3 + 4*#i"); // type inferred

MyVar.Value(123);
MyInt.ValueInt32(456);
MyStr.ValueStr("This is a test");

wl("MyVar = " + uc.EvalStr("MyVar"))
wl("MyInt = " + uc.EvalStr("MyInt"))
wl("MyStr = " + uc.EvalStr("MyStr"))
wl("OtherStr = " + uc.EvalStr("OtherStr"))
wl("MyInt16 = " + uc.EvalStr("MyInt16"))
wl("MyBool = " + uc.EvalStr("MyBool"))
wl("MyComplex = " + uc.EvalStr("MyComplex"))
wl("---")
wl(MyVar.Value())
wl(MyInt.ValueInt32())
wl(MyStr.ValueStr())
wl("---")
wl(uc.ItemOf("MyVar").@DataType().@Name())
wl(uc.ItemOf("MyInt").@DataType().@Name())
wl(uc.ItemOf("MyStr").@DataType().@Name())
wl(uc.ItemOf("OtherStr").@DataType().@Name())
wl(uc.ItemOf("MyInt16").@DataType().@Name())
wl(uc.ItemOf("MyBool").@DataType().@Name())
wl("---")

var Expression = "x^2 * 10";
var VarX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse(Expression);

w("Expression = ")
wl(Expression)
for (int x = 1 to 10)
   VarX.Value(x); // In C++ you can skip this by passing &x to DefineVariable
   wl("x = " + VarX.ValueStr() + "  Result = " + ParsedExpr.EvaluateStr())
end for

ParsedExpr.Release();
VarX.Release();
```

**Output:**
```
MyVar = 123
MyInt = 456
MyStr = This is a test
OtherStr = string type inferred
MyInt16 = 33
MyBool = true
MyComplex = 3+4i
---
123
456
This is a test
---
double
int
string
string
int16
bool
---
Expression = x^2 * 10
x = 1  Result = 10
x = 2  Result = 40
x = 3  Result = 90
x = 4  Result = 160
x = 5  Result = 250
x = 6  Result = 360
x = 7  Result = 490
x = 8  Result = 640
x = 9  Result = 810
x = 10  Result = 1000
```

---

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## ValueStr(string) - ID: 199
/doc/reference/classes/ucalc.item/valuestr/valuestr-string/

**Description:** Sets the value of an Item by parsing and evaluating a string expression.

**Syntax:** ValueStr(string)
**Parameters:**
expressionString - string - A string containing the value or expression to be parsed, evaluated, and assigned to the item.
**Return:** void - 
**Remarks:**

`ValueStr` is a powerful and versatile method for setting the value of an [Item](/reference/uCalc/Item) (typically a variable) by parsing and evaluating a string expression. Unlike type-specific setters like `ValueInt32(int)`, this method accepts a string, processes it through the uCalc engine, and assigns the result, automatically handling type conversions.

### ⚙️ How It Works

When you call `item.ValueStr("5 * 2")` on an integer variable, uCalc performs the following steps:
1.  **Parse & Evaluate**: The string `"5 * 2"` is parsed and evaluated, resulting in the numeric value `10`.
2.  **Type Coercion**: The engine checks the target variable's [DataType](/reference/uCalc/DataType) (in this case, an integer).
3.  **Assignment**: The result `10` is safely converted to the target type and assigned to the variable.

This mechanism allows you to set variables of any type—`Int`, `Double`, `String`, `Complex`, `Boolean`—using a consistent, string-based input. For string literals, the expression should be enclosed in single quotes (e.g., `'hello world'`).

### 🆚 Comparative Analysis: uCalc vs. Native Languages

In a statically-typed language like C# or C++, setting a variable from a string requires explicit parsing and error handling for each data type.

**Native C# Approach:**
```csharp
int myInt;
string userInput = "123";
if (!int.TryParse(userInput, out myInt))
{
    // Handle parsing error...
}
```
You would need separate logic for `double.TryParse`, `bool.TryParse`, and complex custom parsing for other types.

**The uCalc Advantage:**
uCalc abstracts this complexity into a single method call. It leverages its own internal parser and type system to handle the conversion seamlessly.
```pseudocode
// Define an integer variable
var myInt = uc.DefineVariable("myInt As Int");

// Set its value from a string expression. uCalc handles parsing and conversion.
myInt.ValueStr("100 + 23"); 

wl(myInt.ValueInt32()); // Output: 123
```
This is particularly powerful for applications that accept user input or read from configuration files, as it centralizes the logic for interpreting and assigning values.

### 💡 When to Use `ValueStr` vs. `Value<Type>`

*   Use **`ValueStr("...")`** when your source data is a **string** that needs to be parsed (e.g., user input, file content).
*   Use a type-specific setter like **`ValueInt32(123)`** when you already have a **native variable** in your host application (C#, C++, etc.) and want to assign its value directly, which is more performant as it bypasses the parsing step.

This method is the setter counterpart to the getter version of [ValueStr()](/reference/uCalc/Item/ValueStr/ValueStr).


**Examples:**

### Example ID: 103

**Description:** Using ValueStr()

**Code:**
```pseudocode
var MyStr = uc.DefineVariable("MyStr As String");
var MyDbl = uc.DefineVariable("MyDbl As Double");
var MyCplx = uc.DefineVariable("MyCplx As Complex");
var MyBool = uc.DefineVariable("MyBool As Boolean");

MyStr.ValueStr("Hello world!");
MyDbl.ValueStr("123.456");
MyCplx.ValueStr("3+4*#i");
MyBool.ValueStr("True");

wl(uc.EvalStr("$'MyStr = {MyStr}'"))
wl(uc.EvalStr("$'MyDbl = {MyDbl}'"))
wl(uc.EvalStr("$'MyCplx = {MyCplx}'"))
wl(uc.EvalStr("$'MyBool = {MyBool}'"))
wl("---")
wl(MyStr.ValueStr())
wl(MyDbl.ValueStr())
wl(MyCplx.ValueStr())
wl(MyBool.ValueStr())
```

**Output:**
```
MyStr = Hello world!
MyDbl = 123.456
MyCplx = 3+4i
MyBool = true
---
Hello world!
123.456
3+4i
true
```

---

### Example ID: 17

**Description:** DefineVariable examples

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var MyInt = uc.DefineVariable("MyInt As Int");
var MyStr = uc.DefineVariable("MyStr As String");
uc.DefineVariable("OtherStr = 'string type inferred'");
uc.DefineVariable("MyInt16 = Int16(100/3)"); // type inferred
uc.DefineVariable("MyBool = True"); // type inferred
uc.DefineVariable("MyComplex = 3 + 4*#i"); // type inferred

MyVar.Value(123);
MyInt.ValueInt32(456);
MyStr.ValueStr("This is a test");

wl("MyVar = " + uc.EvalStr("MyVar"))
wl("MyInt = " + uc.EvalStr("MyInt"))
wl("MyStr = " + uc.EvalStr("MyStr"))
wl("OtherStr = " + uc.EvalStr("OtherStr"))
wl("MyInt16 = " + uc.EvalStr("MyInt16"))
wl("MyBool = " + uc.EvalStr("MyBool"))
wl("MyComplex = " + uc.EvalStr("MyComplex"))
wl("---")
wl(MyVar.Value())
wl(MyInt.ValueInt32())
wl(MyStr.ValueStr())
wl("---")
wl(uc.ItemOf("MyVar").@DataType().@Name())
wl(uc.ItemOf("MyInt").@DataType().@Name())
wl(uc.ItemOf("MyStr").@DataType().@Name())
wl(uc.ItemOf("OtherStr").@DataType().@Name())
wl(uc.ItemOf("MyInt16").@DataType().@Name())
wl(uc.ItemOf("MyBool").@DataType().@Name())
wl("---")

var Expression = "x^2 * 10";
var VarX = uc.DefineVariable("x");
var ParsedExpr = uc.Parse(Expression);

w("Expression = ")
wl(Expression)
for (int x = 1 to 10)
   VarX.Value(x); // In C++ you can skip this by passing &x to DefineVariable
   wl("x = " + VarX.ValueStr() + "  Result = " + ParsedExpr.EvaluateStr())
end for

ParsedExpr.Release();
VarX.Release();
```

**Output:**
```
MyVar = 123
MyInt = 456
MyStr = This is a test
OtherStr = string type inferred
MyInt16 = 33
MyBool = true
MyComplex = 3+4i
---
123
456
This is a test
---
double
int
string
string
int16
bool
---
Expression = x^2 * 10
x = 1  Result = 10
x = 2  Result = 40
x = 3  Result = 90
x = 4  Result = 160
x = 5  Result = 250
x = 6  Result = 360
x = 7  Result = 490
x = 8  Result = 640
x = 9  Result = 810
x = 10  Result = 1000
```

---

### Example ID: 19

**Description:** Setting a variable value

**Code:**
```pseudocode
var MyVar = uc.DefineVariable("MyVar");
var ByteVar = uc.DefineVariable("ByteVar As Int8");
var Int16uVar = uc.DefineVariable("Int16uVar As Int16u");
var Int32uVar = uc.DefineVariable("Int32uVar As Int32u");
var Int64uVar = uc.DefineVariable("Int64uVar As Int64u");
var SingleVar = uc.DefineVariable("SingleVar As Single");
var DoubleVar = uc.DefineVariable("DoubleVar As Double");
var StringVar = uc.DefineVariable("StringVar As String");

MyVar.Value(1.25);
ByteVar.ValueByte(255);
Int16uVar.ValueInt16(-1);
Int32uVar.ValueInt32(-1);
Int64uVar.ValueInt64(-1);
SingleVar.ValueSng([C](float)[/C]1.5);
DoubleVar.ValueDbl(2.5);
StringVar.ValueStr("Test");

wl(MyVar.Value())
wl([C](int)[/C]ByteVar.ValueByte())
wl(Int16uVar.ValueInt16())
wl(Int32uVar.ValueInt32())
wl(Int64uVar.ValueInt64())
wl(SingleVar.ValueSng())
wl(DoubleVar.ValueDbl())
wl(StringVar.ValueStr())
wl("---")
wl("MyVar value: " + uc.EvalStr("MyVar"))
wl("ByteVar value: " + uc.EvalStr("ByteVar"))
wl("Int16uVar value: " + uc.EvalStr("Int16uVar"))
wl("Int32uVar value: " + uc.EvalStr("Int32uVar"))
wl("Int64uVar value: " + uc.EvalStr("Int64uVar"))
wl("SingleVar value: " + uc.EvalStr("SingleVar"))
wl("DoubleVar value: " + uc.EvalStr("DoubleVar"))
wl("StringVar value: " + uc.EvalStr("StringVar"))
```

**Output:**
```
1.25
255
-1
-1
-1
1.5
2.5
Test
---
MyVar value: 1.25
ByteVar value: -1
Int16uVar value: 65535
Int32uVar value: 4294967295
Int64uVar value: 18446744073709551615
SingleVar value: 1.5
DoubleVar value: 2.5
StringVar value: Test
```

---

---

## uCalc.ItemsAccessor - ID: 856
/doc/reference/classes/ucalc.itemsaccessor/

**Description:** Items accessor

**Examples:**

### Example ID: 384

**Description:** Lists the names of all user-defined and built-in functions.

**Code:**
```pseudocode
// Note: Some items in this list (like bool, or int*) appear more than once or out of chronological
// order because they are aliases (like bool, which is also an alias for boolean)
wl("Defined Functions:")
foreach(var item in uc.GetItems(ItemIs::Function))
   wl(" - ", item.@Name())
end foreach
```

**Output:**
```
Defined Functions:
 - abs
 - acos
 - acosh
 - addptr
 - addressof
 - anytype
 - append
 - append_copy
 - arg
 - argcount
 - asc
 - asin
 - asinh
 - atan
 - atan2
 - atanh
 - back
 - baseconvert
 - bin
 - bool
 - bool
 - int8u
 - c_str
 - cbrt
 - ceil
 - chr
 - clear
 - compare
 - complex
 - conj
 - contains
 - copysign
 - cos
 - cosh
 - define
 - doloop
 - double
 - endswith
 - erase
 - erase_copy
 - erf
 - erfc
 - error
 - eval
 - evalstr
 - evaluate
 - evaluateint
 - evaluatestr
 - exp
 - exp2
 - expm1
 - exprptr
 - fabs
 - fdim
 - file
 - filesize
 - fill
 - find_first_not_of
 - find_first_of
 - find_last_not_of
 - find_last_of
 - single
 - floor
 - fmax
 - fmin
 - fmod
 - forloop
 - format
 - fpclassify
 - frac
 - frexp
 - fromto
 - goto
 - hex
 - hypot
 - iif
 - ilogb
 - imag
 - indexof
 - inf
 - insert
 - insert_copy
 - int
 - int16
 - int16u
 - int
 - int32u
 - int64
 - int64u
 - int8
 - int8u
 - int
 - isfinite
 - isinf
 - isnan
 - isnormal
 - lastindexof
 - lcase
 - ldexp
 - length
 - lgamma
 - llrint
 - llround
 - log
 - log10
 - log1p
 - log2
 - logb
 - lrint
 - lround
 - ltrim
 - max
 - min
 - modf
 - nan
 - nearbyint
 - nextafter
 - nexttoward
 - norm
 - oct
 - omnitype
 - padleft
 - padright
 - parse
 - pointer
 - polar
 - pop
 - pow
 - precedence
 - proj
 - push
 - rand
 - randfromsameseed
 - randomnumber
 - randomseed
 - real
 - remainder
 - remquo
 - repeat
 - replace
 - replace_copy
 - reset
 - rint
 - round
 - rtrim
 - sametypeas
 - scalbln
 - scalbn
 - setvar
 - sgn
 - signbit
 - sin
 - single
 - sinh
 - size_t
 - sizeof
 - sort
 - sqr
 - sqrt
 - startswith
 - str
 - string
 - substr
 - subtractptr
 - swap
 - tan
 - tanh
 - tgamma
 - trim
 - trunc
 - ucalcinstance
 - ucase
 - valueat
 - valueattype
 - void
```

---

### Example ID: 107

**Description:** uCalc.Items

**Code:**
```pseudocode
// Note: Some items in this list (like bool, or int*) appear more than once or out of chronological
// order because they are aliases (like bool, which is also an alias for boolean)
foreach(var item in uc.@Items())
   wl(item.@Name())
end foreach
```

**Output:**
```
!
%
&
&&
*
+
,
-
/
<
<<
<=
<>
=
==
>
>=
>>
\
^
_enduserformattedoutput
_newline
_token_alphanumeric
_token_argseparator
_token_binaryhexoctalnotation
_token_catchall
_token_catchall_utf8_other
_token_curlybrace
_token_curlybrace_close
_token_floatnumber
_token_imaginaryunit
_token_line
_token_memberaccess
_token_newline
_token_parenthesis
_token_parenthesis_close
_token_punctuation
_token_quotechar
_token_quotechar_double
_token_quotechar_single
_token_quotechar_tripledouble
_token_reducible
_token_reducible2
_token_semicolon
_token_squarebracket
_token_squarebracket_close
_token_string_doublequoted
_token_string_singlequoted
_token_string_tripledoublequoted
_token_stringinterpolationquote
_token_variableargs
_token_whitespace
_ucalc_lib_is32
_ucalc_lib_is64
_ucalc_lib_release_timestamp
_ucalc_lib_version
abs
acos
acosh
addptr
addressof
and
andalso
anytype
append
append_copy
arg
argcount
asc
asin
asinh
atan
atan2
atanh
back
baseconvert
bin
bitand
bitor
bool
bool
int8u
c_str
cbrt
ceil
chr
clear
compare
complex
conj
contains
copysign
cos
cosh
define
doloop
double
endswith
erase
erase_copy
erf
erfc
error
eval
evalstr
evaluate
evaluateint
evaluatestr
exp
exp2
expm1
exprptr
fabs
false
fdim
file
filesize
fill
find_first_not_of
find_first_of
find_last_not_of
find_last_of
single
floor
fmax
fmin
fmod
forloop
format
fpclassify
frac
frexp
fromto
goto
hex
hypot
iif
ilogb
imag
indexof
inf
insert
insert_copy
int
int16
int16u
int
int32u
int64
int64u
int8
int8u
int
isfinite
isinf
isnan
isnormal
lastindexof
lastrandomnumber
lcase
ldexp
length
lgamma
llrint
llround
log
log10
log1p
log2
logb
lrint
lround
ltrim
max
min
mod
modf
nan
nearbyint
nextafter
nexttoward
norm
not
oct
omnitype
or
orelse
padleft
padright
parse
pointer
polar
pop
pow
precedence
proj
push
rand
randfromsameseed
randomnumber
randomseed
real
remainder
remquo
repeat
replace
replace_copy
reset
rint
round
rtrim
sametypeas
scalbln
scalbn
setvar
sgn
signbit
sin
single
sinh
size_t
sizeof
sort
sqr
sqrt
startswith
str
string
substr
subtractptr
swap
tan
tanh
tgamma
trim
true
trunc
ucalcinstance
ucase
valueat
valueattype
void
xor
|
||
~
```

---

### Example ID: 108

**Description:** ListOfItem with name / property

**Code:**
```pseudocode
wl("Items with the Prefix property")
wl("------------------------------")
foreach(var item in uc.GetItems(ItemIs::Prefix))
   wl(item.@Name())
end foreach

wl("")
wl("Different versions of the + operator")
wl("------------------------------------")
foreach(var item in uc.GetItems("+"))
   wl(item.@Text())
end foreach
```

**Output:**
```
Items with the Prefix property
------------------------------
!
+
-
not
~

Different versions of the + operator
------------------------------------
Operator: 70 +{x}
Operator: 50 {x} + {y}
Operator: 50 {x As Int} + {y As Int} As Int
Operator: 50 {x As String} + {y As String} As String
Operator: 50 {x As Complex} + {y As Complex} As Complex
Operator: 50 {ByHandle x As AnyType Ptr} + {y As Int} As SameTypeAs:0 Ptr
Operator: 50 {ByHandle x As AnyType} + {ByHandle y As String} As String
Operator: 50 {ByHandle x As String} + {ByHandle y As AnyType} As String
```

---

---

## Introduction - ID: 964
/doc/reference/classes/ucalc.itemsaccessor/introduction/

**Description:** Provides an iterable, queryable interface to the collection of all symbols (items) defined within a uCalc instance.

**Remarks:**

# 🔍 ItemsAccessor: The Symbol Table Gateway

The `ItemsAccessor` class is the modern, object-oriented gateway to a `uCalc` instance's symbol table. It is not created directly; instead, you retrieve it from the [uCalc.Items](/Reference/uCalcBase/uCalc/Items) property. It provides a powerful and flexible way to query, inspect, and iterate through all defined symbols—such as functions, variables, and operators—within a specific parser context.

---

## Class Members

The `ItemsAccessor` behaves like a read-only collection, providing the following primary members:

| Member | Description |
| :--- | :--- |
| `Count` (Property) | Gets the total number of items in the collection. |
| [`Indexer [index]`](/Reference/uCalcBase/ItemsAccessor/Indexer%5B%5D) | Retrieves an item by its zero-based numerical index. |
| [`Indexer [name]`](/Reference/uCalcBase/ItemsAccessor/Indexer%5B%5D) | Retrieves the first item that matches the given string name. |
| (Iteration) | The object directly supports `foreach` loops to iterate over all `Item` objects. |

---
## Filtering Items

While the accessor returns all items by default, you can easily filter the collection within a loop by checking each item's properties using [Item.IsProperty](/Reference/uCalcBase/Item/IsProperty).

```pseudocode
// Example: Find and print only the variables
foreach(var item in uc.Items)
  if (item.IsProperty(ItemIs.Variable))
    wl(item.Name, " = ", item.ValueStr());
  end if
end foreach
```

---

## 🆚 Comparative Analysis

*   **vs. .NET `IEnumerable<T>`**: The `ItemsAccessor` is conceptually very similar to a standard .NET collection interface. It supports `foreach` and indexed access, making it intuitive for C# and VB.NET developers.


**Examples:**

### Example ID: 108

**Description:** ListOfItem with name / property

**Code:**
```pseudocode
wl("Items with the Prefix property")
wl("------------------------------")
foreach(var item in uc.GetItems(ItemIs::Prefix))
   wl(item.@Name())
end foreach

wl("")
wl("Different versions of the + operator")
wl("------------------------------------")
foreach(var item in uc.GetItems("+"))
   wl(item.@Text())
end foreach
```

**Output:**
```
Items with the Prefix property
------------------------------
!
+
-
not
~

Different versions of the + operator
------------------------------------
Operator: 70 +{x}
Operator: 50 {x} + {y}
Operator: 50 {x As Int} + {y As Int} As Int
Operator: 50 {x As String} + {y As String} As String
Operator: 50 {x As Complex} + {y As Complex} As Complex
Operator: 50 {ByHandle x As AnyType Ptr} + {y As Int} As SameTypeAs:0 Ptr
Operator: 50 {ByHandle x As AnyType} + {ByHandle y As String} As String
Operator: 50 {ByHandle x As String} + {ByHandle y As AnyType} As String
```

---

### Example ID: 107

**Description:** uCalc.Items

**Code:**
```pseudocode
// Note: Some items in this list (like bool, or int*) appear more than once or out of chronological
// order because they are aliases (like bool, which is also an alias for boolean)
foreach(var item in uc.@Items())
   wl(item.@Name())
end foreach
```

**Output:**
```
!
%
&
&&
*
+
,
-
/
<
<<
<=
<>
=
==
>
>=
>>
\
^
_enduserformattedoutput
_newline
_token_alphanumeric
_token_argseparator
_token_binaryhexoctalnotation
_token_catchall
_token_catchall_utf8_other
_token_curlybrace
_token_curlybrace_close
_token_floatnumber
_token_imaginaryunit
_token_line
_token_memberaccess
_token_newline
_token_parenthesis
_token_parenthesis_close
_token_punctuation
_token_quotechar
_token_quotechar_double
_token_quotechar_single
_token_quotechar_tripledouble
_token_reducible
_token_reducible2
_token_semicolon
_token_squarebracket
_token_squarebracket_close
_token_string_doublequoted
_token_string_singlequoted
_token_string_tripledoublequoted
_token_stringinterpolationquote
_token_variableargs
_token_whitespace
_ucalc_lib_is32
_ucalc_lib_is64
_ucalc_lib_release_timestamp
_ucalc_lib_version
abs
acos
acosh
addptr
addressof
and
andalso
anytype
append
append_copy
arg
argcount
asc
asin
asinh
atan
atan2
atanh
back
baseconvert
bin
bitand
bitor
bool
bool
int8u
c_str
cbrt
ceil
chr
clear
compare
complex
conj
contains
copysign
cos
cosh
define
doloop
double
endswith
erase
erase_copy
erf
erfc
error
eval
evalstr
evaluate
evaluateint
evaluatestr
exp
exp2
expm1
exprptr
fabs
false
fdim
file
filesize
fill
find_first_not_of
find_first_of
find_last_not_of
find_last_of
single
floor
fmax
fmin
fmod
forloop
format
fpclassify
frac
frexp
fromto
goto
hex
hypot
iif
ilogb
imag
indexof
inf
insert
insert_copy
int
int16
int16u
int
int32u
int64
int64u
int8
int8u
int
isfinite
isinf
isnan
isnormal
lastindexof
lastrandomnumber
lcase
ldexp
length
lgamma
llrint
llround
log
log10
log1p
log2
logb
lrint
lround
ltrim
max
min
mod
modf
nan
nearbyint
nextafter
nexttoward
norm
not
oct
omnitype
or
orelse
padleft
padright
parse
pointer
polar
pop
pow
precedence
proj
push
rand
randfromsameseed
randomnumber
randomseed
real
remainder
remquo
repeat
replace
replace_copy
reset
rint
round
rtrim
sametypeas
scalbln
scalbn
setvar
sgn
signbit
sin
single
sinh
size_t
sizeof
sort
sqr
sqrt
startswith
str
string
substr
subtractptr
swap
tan
tanh
tgamma
trim
true
trunc
ucalcinstance
ucase
valueat
valueattype
void
xor
|
||
~
```

---

---

## Indexer[] - ID: 939
/doc/reference/classes/ucalc.itemsaccessor/indexer[]/

**Syntax:** Indexer[]()
**Return:**  - 
---

## uCalc.Matches - ID: 200
/doc/reference/classes/ucalc.matches/

**Description:** Class for returning a list of matches

---

## Introduction - ID: 965
/doc/reference/classes/ucalc.matches/introduction/

**Description:** An overview of the Matches collection, which holds the results of a Transformer pattern-matching operation.

**Remarks:**

# 🎯 The Matches Collection: Your Search Results

The `uCalc.Matches` object is a collection that holds the results of a pattern-matching operation performed by a [uCalc.Transformer](/Reference/uCalcBase/Transformer/Constructor). It is not created directly; instead, it is returned by the [Matches](/Reference/uCalcBase/Transformer/Matches) property of a `Transformer` after calling [Find()](/Reference/uCalcBase/Transformer/Find), [Filter()](/Reference/uCalcBase/Transformer/Filter), or [Transform()](/Reference/uCalcBase/Transformer/Transform).

---

## ⚙️ Core Concepts

*   **Read-Only Snapshot**: A `Matches` object is a snapshot of the results at a moment in time. The collection itself doesn't change if you re-run a transform, but you can get a *new* `Matches` object with updated results.
*   **Collection-like Behavior**: It acts like a list or array. You can get its [Count()](/Reference/uCalcBase/Matches/Count), iterate through it, and access individual `Match` objects by index.
*   **Rich Metadata**: Each element in the collection is not just a string, but a rich [Match](/Reference/uCalcBase/Matches/Match) object containing details like the captured text, its start and end positions, its length, and—crucially—a reference to the [Rule](/Reference/uCalcBase/Rule/Constructor) that generated the match.

### How to Use It

The typical workflow is simple:
1.  Configure a `Transformer` with rules.
2.  Run an operation like [Find()](/Reference/uCalcBase/Transformer/Find).
3.  Get the results via the [Matches](/Reference/uCalcBase/Transformer/Matches) property.
4.  Loop through the collection to analyze each `Match`.

```pseudocode
NewUsing(uCalc::Transformer, t)
t.Pattern("{@Alphanumeric}");
t.Text("One two three");
t.Find();

var m = t.Matches();
wl("Found ", m.Count(), " matches.");
for (var i = 0 to m.Count() - 1)
    wl(" - Match ", i, ": '", m[i].Text(), "' at position ", m[i].StartPosition());
end for
End Using
```

---

## 📜 Members of the Matches Collection

This section provides a high-level overview. For details on the individual `Match` object, see the [Match](/Reference/uCalcBase/Matches/Match) class documentation.

| Member                                                        | Description                                                                                                      |
| :------------------------------------------------------------ | :--------------------------------------------------------------------------------------------------------------- |
| **Indexer `[]`**                                              | Accesses an individual `Match` object in the collection by its zero-based index.                                   |
| [`Count()`](/Reference/uCalcBase/Matches/Count)               | Gets the total number of matches in the collection.                                                              |
| [`Text`](/Reference/uCalcBase/Matches/Text)                   | Returns a single string of all match texts concatenated by newlines.                                             |
| [`ApplyOffset()`](/Reference/uCalcBase/Matches/ApplyOffset)       | Adjusts the start/end positions of all matches by a given offset.                                                |
| [`IndexOf()`](/Reference/uCalcBase/Matches/IndexOf)           | Finds the index of a match given its starting character position.                                                |
| [`Reset()`](/Reference/uCalcBase/Matches/Reset)                 | Clears or re-filters the match list without re-running the search.                                               |
| [`uCalc()`](/Reference/uCalcBase/Matches/uCalc)                 | Retrieves the parent `uCalc` instance providing the execution context.                                           |
| [`Release()`](/Reference/uCalcBase/Matches/Release)               | Releases the `Matches` object and its resources.                                                                 |
| [`Match`](/Reference/uCalcBase/Matches/Match) class             | Represents a single match, with properties like [Text](/Reference/uCalcBase/Matches/Match/Text), [StartPosition](/Reference/uCalcBase/Matches/Match/StartPosition), [EndPosition](/Reference/uCalcBase/Matches/Match/EndPosition), [Length](/Reference/uCalcBase/Matches/Match/Length), and [Rule()](/Reference/uCalcBase/Matches/Match/Rule). |

---

### ⚖️ Comparative Analysis: `uCalc.Matches` vs. Regex `MatchCollection`

*   **Token Awareness**: Regex matches are character-based. A `uCalc.Matches` collection contains results from a token-aware engine, so the matches are structurally sound and respect boundaries like quotes and brackets by default.
*   **Introspection**: A standard regex `Match` provides the captured string and its position. A uCalc [Match](/Reference/uCalcBase/Matches/Match) provides much richer context. The ability to retrieve the specific [Rule](/Reference/uCalcBase/Rule/Constructor) that generated the match via [match.Rule()](/Reference/uCalcBase/Matches/Match/Rule) is invaluable for debugging and for building applications with complex, layered logic where you need to know *why* something was matched.
*   **Filtering**: uCalc provides built-in, engine-side filtering via [MatchesOption](/Reference/Enums/MatchesOption) flags (e.g., [RootLevelOnly](/Reference/Enums/MatchesOption), [InnermostOnly](/Reference/Enums/MatchesOption)) which is more efficient than filtering a full result set in application code.

**Examples:**

### Example ID: 785

**Description:** How to count all alphanumeric words in a sentence.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("There are five words here.");

// Define a pattern to find any alphanumeric word
t.Pattern("{@Alpha}");
t.Find();

wl("Total words found: ", t.@Matches().Count())
```

**Output:**
```
Total words found: 5
```

---

### Example ID: 1312

**Description:** Finding all occurrences of a word, getting the total count, and displaying the text of the first match.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
t.@Text("apple banana apple cherry");
t.Pattern("apple");
t.Find();

var m = t.@Matches();
wl("Matches found: ", m.Count())
if (m.Count() > 0)
    wl("First match: ", m[0].@Text())
end if
End Using;
```

**Output:**
```
Matches found: 2
First match: apple
```

---

### Example ID: 855

**Description:** Filters matches by rule; FilterByRule, Matches.Str, Matches.Count

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

wl("All matches -- count = ", t.@Matches().Count())
wl("----------------------")
wl(t.@Matches().@Text())
wl("")

wl("Only BoldTag matches -- count = ", BoldTag.@Matches().Count())
wl("-------------------------------")
wl(BoldTag.@Matches().@Text())
wl("")

wl("Only H3Tag matches -- count = ", H3Tag.@Matches().Count())
wl("-----------------------------")
wl(H3Tag.@Matches().@Text())
```

**Output:**
```
All matches -- count = 5
----------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
<p>My paragraph</p>

Only BoldTag matches -- count = 2
-------------------------------
<b>Bold statement</b>
<b>Other text</b>

Only H3Tag matches -- count = 2
-----------------------------
<h3>Title</h3>
<h3>Title B</h3>
```

---

---

## (Constructor) - ID: 658
/doc/reference/classes/ucalc.matches/-constructor/

**Description:** A collection representing the results of a pattern matching operation, created by a Transformer.

**Remarks:**


The `uCalc.Matches` object is a read-only collection that holds the results of a pattern-matching operation performed by a [uCalc.Transformer](/Reference/uCalcBase/Transformer/Constructor). It is not created directly; instead, it is returned by the [Matches()](/Reference/uCalcBase/Transformer/Matches) method of a `Transformer` after calling [Find()](/Reference/uCalcBase/Transformer/Find), [Filter()](/Reference/uCalcBase/Transformer/Filter), or [Transform()](/Reference/uCalcBase/Transformer/Transform).

### What a `Matches` Object Contains

The collection represents all the substrings that successfully matched one of the transformer's defined patterns. For each match in the list, you can retrieve detailed information using its index:

*   **Text**: The actual string that was matched, using [Str(index)](/Reference/uCalcBase/Matches/Str).
*   **Position**: The starting and ending character position, using [StartPosition(index)](/Reference/uCalcBase/Matches/StartPosition) and [EndPosition(index)](/Reference/uCalcBase/Matches/EndPosition).
*   **Length**: The length of the matched string, using [Length(index)](/Reference/uCalcBase/Matches/Length).
*   **Source Rule**: The specific [Rule](/Reference/uCalcBase/Rule/Constructor) that generated the match, using [Rule(index)](/Reference/uCalcBase/Matches/Rule).
*   **Count**: The total number of matches in the collection, using [Count()](/Reference/uCalcBase/Matches/Count).

### Iterating Through Matches

To access the matches, you typically loop from `0` to `Matches.Count() - 1`.

```pseudocode
New(uCalc::Transformer, t);
// ... define rules and input text ...
t.Find();

var m = t.Matches();
for (var i = 0 to m.Count() - 1)
wl("Match ", i, ": ", m.Str(i));
end for
```

### ⚖️ Comparative Analysis: `uCalc.Matches` vs. Regex `MatchCollection`

In environments like .NET, a regular expression search returns a `MatchCollection`. While functionally similar, uCalc's `Matches` object has distinct advantages rooted in its token-aware architecture.

*   **Token Awareness vs. Character Awareness**: A standard regex match is purely character-based and can easily fail on nested structures. uCalc's matches are token-aware. A match for [pseudocode]`{@Bracketed}` will correctly capture `(a + (b * c))`, something that is extremely difficult for a simple regex. The resulting `Matches` object represents these structurally sound matches.

*   **Rich Metadata**: A regex match typically provides the captured string and its position. A uCalc match provides much richer context. The ability to retrieve the specific [Rule](/Reference/uCalcBase/Rule/Constructor) that generated the match via [pseudocode]`Matches.Rule(i)` is invaluable for debugging and for building applications with complex, layered logic where you need to know *why* something was matched.

**Examples:**

### Example ID: 114

**Description:** Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>");
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text())
   wl("Start pos: ", match.@StartPosition())
   wl("End pos: ", match.@EndPosition())
   wl("Length: ", match.@Length())
   wl("")
end foreach
```

**Output:**
```
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
```

---

---

## Indexer[] - ID: 935
/doc/reference/classes/ucalc.matches/indexer[]/

**Syntax:** Indexer[]()
**Return:**  - 
---

## uCalc.Match - ID: 841
/doc/reference/classes/ucalc.matches/ucalc.match/

**Description:** Details of an individual match

---

## Introduction - ID: 966
/doc/reference/classes/ucalc.matches/ucalc.match/introduction/

**Description:** Represents a single successful match from a Transformer operation, providing access to its text, position, and originating rule.

**Remarks:**

# 🎯 The Match Object: A Snapshot of a Find

A `Match` object represents a single successful pattern match from a [Transformer](/Reference/uCalcBase/Transformer/Constructor) operation. It is a read-only snapshot that contains detailed information about a specific substring that was found, including its content, its location within the source text, and the rule that generated it.

You do not create `Match` objects directly. Instead, you access them by iterating through a [Matches](/Reference/uCalcBase/Matches/Constructor) collection, which is returned by methods like [Transformer.Matches](/Reference/uCalcBase/Transformer/Matches) after a [Find()](/Reference/uCalcBase/Transformer/Find) or [Transform()](/Reference/uCalcBase/Transformer/Transform) operation.

---

## ⚙️ Core Properties

| Property | Description |
| :--- | :--- |
| [`Text`](/Reference/uCalcBase/Matches/Match/Text) | Retrieves the read-only string of characters captured by the match. |
| [`StartPosition`](/Reference/uCalcBase/Matches/Match/StartPosition) | Gets the zero-based starting character position of the match within the source text. |
| [`EndPosition`](/Reference/uCalcBase/Matches/Match/EndPosition) | Gets the zero-based index of the character position immediately following the match's last character. |
| [`Length`](/Reference/uCalcBase/Matches/Match/Length) | Gets the length, in characters, of the substring captured by the match. |
| [`Rule`](/Reference/uCalcBase/Matches/Match/Rule) | Retrieves the [Rule](/Reference/uCalcBase/Rule/Constructor) object that generated this specific match, enabling runtime introspection. |

**Examples:**

### Example ID: 827

**Description:** Assigns descriptive text to multiple rules and uses the `Rule` property to identify which rule generated each match.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>").SetDescription("other kind of tag");
var BoldTag = t.Pattern("<b>{text}</b>").SetDescription("bold tag");
var H3Tag = t.Pattern("<h3>{text}</h3>").SetDescription("h3 tag");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text() + "   Description: " + match.@Rule().@Description())
end foreach
```

**Output:**
```
<h3>Title</h3>   Description: h3 tag
<b>Bold statement</b>   Description: bold tag
<h3>Title B</h3>   Description: h3 tag
<b>Other text</b>   Description: bold tag
<p>My paragraph</p>   Description: other kind of tag
```

---

### Example ID: 824

**Description:** A practical example that iterates through all words in a sentence to find the one with the greatest length.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("Find the longest word in this sentence.");
t.Pattern("{@Alpha}"); // Match all words
t.Find();

var(int, maxLength) = 0;
var(string, longestWord) = "";
foreach(var match in t.@Matches())
    if (match.@Length() > maxLength)
        maxLength = match.@Length();
        longestWord = match.@Text();
    end if
end foreach

wl("Longest word is '", longestWord, "' with length: ", maxLength)
```

**Output:**
```
Longest word is 'sentence' with length: 8
```

---

### Example ID: 826

**Description:** Finds a single match and retrieves the name of the rule that generated it.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var ruleA = t.FromTo("apple", "fruit");
t.@Text("an apple a day");
t.Find();

var firstMatch = t.@Matches()[0];
var generatingRule = firstMatch.@Rule();

w("Match text: '", firstMatch.@Text(), "' was found by rule: '", generatingRule.@Name(), "'")
```

**Output:**
```
Match text: 'apple' was found by rule: 'apple'
```

---

---

## EndPosition = [int] - ID: 845
/doc/reference/classes/ucalc.matches/ucalc.match/endposition-=-[int]/

**Description:** Gets the zero-based index of the character position immediately following the match's last character.

**Remarks:**

### 🎯 Finding Where a Match Concludes

The `EndPosition` property returns the zero-based character index immediately **after** the last character of a specific match. It represents the exclusive end boundary of the matched text segment.

This property is fundamental for understanding the location and span of a match. It is almost always used in conjunction with the [StartPosition](/Reference/uCalcBase/Matches/Match/StartPosition) property to determine the exact range of a match in the source text.

### The `End = Start + Length` Rule

The relationship between the three positional properties is simple and consistent:

[pseudocode]`match.Length() = match.EndPosition() - match.StartPosition()`

This means `EndPosition` points to where the next search would begin after this match is processed, making it crucial for manual parsing logic or when building tools that need to slice the original string.

### 💡 Comparative Analysis

*   **vs. .NET Regex `Match.Index + Match.Length`**: In .NET's `System.Text.RegularExpressions`, you typically calculate the end position manually by adding the `Length` to the starting `Index`. uCalc provides a dedicated `EndPosition` property for convenience, reducing boilerplate code and making the intent clearer.

*   **vs. String Substring/Slicing Functions**: Many language's substring functions require a start index and a length. `EndPosition` provides the information needed to calculate this length, but also serves as the direct `end` index for languages that support range-based slicing (like Python's `text[start:end]`).

**Examples:**

### Example ID: 788

**Description:** Returns Start and End positions of Transformer matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>");
//         ^             ^                       ^              ^
//     012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50
// Carrets (^) point to Start and End locations of the matches

wl(t.@Text())
wl("")

t.Pattern("<{tag}>{etc}</{tag}>");
t.Find();
var Matches = t.@Matches();

wl(Matches[0].@Text())
wl("Start pos: ", Matches[0].@StartPosition())
wl("End pos: ", Matches[0].@EndPosition())
wl("Length: ", Matches[0].@Length())
wl("")

wl(Matches[1].@Text())
wl("Start pos: ", Matches[1].@StartPosition())
wl("End pos: ", Matches[1].@EndPosition())
wl("Length: ", Matches[1].@Length())
```

**Output:**
```
<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>

<h1>First</h1>
Start pos: 4
End pos: 18
Length: 14

<h2>Second</h2>
Start pos: 42
End pos: 57
Length: 15
```

---

### Example ID: 111

**Description:** Returns Start and End positions of Transformer matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>");
//         ^             ^                       ^              ^
//     012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50
// Carrets (^) point to Start and End locations of the matches

wl(t.@Text())
wl("")

t.Pattern("<{tag}>{etc}</{tag}>");
t.Find();
var Matches = t.@Matches();

wl(Matches[0].@Text())
wl("Start pos: ", Matches[0].@StartPosition())
wl("End pos: ", Matches[0].@EndPosition())
wl("Length: ", Matches[0].@Length())
wl("")

wl(Matches[1].@Text())
wl("Start pos: ", Matches[1].@StartPosition())
wl("End pos: ", Matches[1].@EndPosition())
wl("Length: ", Matches[1].@Length())
```

**Output:**
```
<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>

<h1>First</h1>
Start pos: 4
End pos: 18
Length: 14

<h2>Second</h2>
Start pos: 42
End pos: 57
Length: 15
```

---

### Example ID: 114

**Description:** Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>");
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text())
   wl("Start pos: ", match.@StartPosition())
   wl("End pos: ", match.@EndPosition())
   wl("Length: ", match.@Length())
   wl("")
end foreach
```

**Output:**
```
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
```

---

---

## Length = [int] - ID: 844
/doc/reference/classes/ucalc.matches/ucalc.match/length-=-[int]/

**Description:** Gets the length, in characters, of the substring captured by an individual match.

**Remarks:**

The `Length` property returns the number of characters in the matched text for a single `Match` within a [Matches](/Reference/uCalcBase/Matches/Constructor) collection.

### How It's Calculated

The length is derived from the match's start and end positions within the source string. It is functionally equivalent to:

[pseudocode]`match.EndPosition() - match.StartPosition()`

This makes it a convenient shortcut for determining the size of the captured substring.

### 💡 Comparative Analysis

This property is analogous to similar features in other text-processing libraries, such as `.Length` on a `System.Text.RegularExpressions.Match` object in .NET or `strlen` on a captured C-style string.

uCalc's advantage lies in its token-aware matching. While a regex match length might be misleading if the pattern incorrectly crosses structural boundaries (like parentheses or quotes), the length of a `uCalc` match reflects a structurally sound capture. For example, a match for `{@Bracketed}` will have a `Length` that correctly includes all nested content, a task notoriously difficult for basic regular expressions.



**Examples:**

### Example ID: 824

**Description:** A practical example that iterates through all words in a sentence to find the one with the greatest length.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("Find the longest word in this sentence.");
t.Pattern("{@Alpha}"); // Match all words
t.Find();

var(int, maxLength) = 0;
var(string, longestWord) = "";
foreach(var match in t.@Matches())
    if (match.@Length() > maxLength)
        maxLength = match.@Length();
        longestWord = match.@Text();
    end if
end foreach

wl("Longest word is '", longestWord, "' with length: ", maxLength)
```

**Output:**
```
Longest word is 'sentence' with length: 8
```

---

### Example ID: 114

**Description:** Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>");
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text())
   wl("Start pos: ", match.@StartPosition())
   wl("End pos: ", match.@EndPosition())
   wl("Length: ", match.@Length())
   wl("")
end foreach
```

**Output:**
```
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
```

---

### Example ID: 111

**Description:** Returns Start and End positions of Transformer matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>");
//         ^             ^                       ^              ^
//     012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50
// Carrets (^) point to Start and End locations of the matches

wl(t.@Text())
wl("")

t.Pattern("<{tag}>{etc}</{tag}>");
t.Find();
var Matches = t.@Matches();

wl(Matches[0].@Text())
wl("Start pos: ", Matches[0].@StartPosition())
wl("End pos: ", Matches[0].@EndPosition())
wl("Length: ", Matches[0].@Length())
wl("")

wl(Matches[1].@Text())
wl("Start pos: ", Matches[1].@StartPosition())
wl("End pos: ", Matches[1].@EndPosition())
wl("Length: ", Matches[1].@Length())
```

**Output:**
```
<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>

<h1>First</h1>
Start pos: 4
End pos: 18
Length: 14

<h2>Second</h2>
Start pos: 42
End pos: 57
Length: 15
```

---

---

## Rule = [Rule] - ID: 861
/doc/reference/classes/ucalc.matches/ucalc.match/rule-=-[rule]/

**Description:** Retrieves the Rule object that generated this specific match, enabling runtime introspection of the pattern and its properties.

**Remarks:**

# 🕵️‍♀️ Introspection: Linking a Match to its Origin

The `Rule` property is a powerful introspection tool that returns the specific [Rule](/Reference/uCalcBase/Rule/Constructor) object responsible for generating an individual match. This creates a direct link from a result (`Match`) back to its origin (the pattern definition), which is crucial for debugging and building context-aware logic.

When you iterate through a [Matches](/Reference/uCalcBase/Matches/Constructor) collection, you can call this property on each `Match` to access the full metadata of the rule that found it.

### 🎯 What Can You Do with the Rule Object?

Once you retrieve the `Rule` object, you can query its properties to understand *why* the match occurred:

*   **[Description()](/Reference/uCalcBase/Rule/Description)**: Get the human-readable description you assigned to the rule.
*   **[Name()](/Reference/uCalcBase/Rule/Name)**: Get the rule's internal name (often derived from its pattern).
*   **[Pattern()](/Reference/uCalcBase/Rule/Pattern)**: Get the original pattern string.
*   **[Tag()](/Reference/uCalcBase/Rule/Tag)**: Retrieve a custom integer tag for programmatic identification.
*   **Behavioral Properties**: Check flags like `CaseSensitive()`, `WhitespaceSensitive()`, etc.

### 💡 Comparative Analysis

This feature provides a significant advantage over traditional regular expression engines.

*   **vs. .NET `Regex.Match`**: In .NET, a `Match` object provides access to captured groups by name or index. However, it offers no direct link back to the `Regex` object that created it, let alone a specific sub-expression within a complex pattern. To achieve similar logic, you would need to use named capture groups and manually map those names back to your application's internal rule definitions. uCalc's `Match.Rule` property provides this link automatically and transparently. This makes building tools like syntax highlighters or debug visualizers significantly simpler, as you can directly query the source `Rule` for metadata like a `Tag` or `Description` to decide how to render the match.

**Examples:**

### Example ID: 826

**Description:** Finds a single match and retrieves the name of the rule that generated it.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var ruleA = t.FromTo("apple", "fruit");
t.@Text("an apple a day");
t.Find();

var firstMatch = t.@Matches()[0];
var generatingRule = firstMatch.@Rule();

w("Match text: '", firstMatch.@Text(), "' was found by rule: '", generatingRule.@Name(), "'")
```

**Output:**
```
Match text: 'apple' was found by rule: 'apple'
```

---

### Example ID: 827

**Description:** Assigns descriptive text to multiple rules and uses the `Rule` property to identify which rule generated each match.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>").SetDescription("other kind of tag");
var BoldTag = t.Pattern("<b>{text}</b>").SetDescription("bold tag");
var H3Tag = t.Pattern("<h3>{text}</h3>").SetDescription("h3 tag");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text() + "   Description: " + match.@Rule().@Description())
end foreach
```

**Output:**
```
<h3>Title</h3>   Description: h3 tag
<b>Bold statement</b>   Description: bold tag
<h3>Title B</h3>   Description: h3 tag
<b>Other text</b>   Description: bold tag
<p>My paragraph</p>   Description: other kind of tag
```

---

### Example ID: 828

**Description:** Internal Test: Uses integer tags to programmatically categorize matches and process them differently in a loop.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("Log: INFO message. Log: ERROR alert. Log: INFO another message.");

var infoRule = t.Pattern("Log: INFO {msg}.").SetTag(1); // Tag 1 for INFO
var errorRule = t.Pattern("Log: ERROR {msg}.").SetTag(99); // Tag 99 for ERROR

t.Find();

foreach(var match in t.@Matches())
    var ruleTag = match.@Rule().@Tag();
    if (ruleTag == 1)
        wl("Found informational log: ", match.@Text())
    end if
    if (ruleTag == 99)
        wl("!!! Found CRITICAL error: ", match.@Text(), " !!!")
    end if
end foreach
```

**Output:**
```
Found informational log: Log: INFO message.
!!! Found CRITICAL error: Log: ERROR alert. !!!
Found informational log: Log: INFO another message.
```

---

### Example ID: 118

**Description:** How to assign and retrieve descriptions for specific transformation patterns using SetDescription().

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>").SetDescription("other kind of tag");
var BoldTag = t.Pattern("<b>{text}</b>").SetDescription("bold tag");
var H3Tag = t.Pattern("<h3>{text}</h3>").SetDescription("h3 tag");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text() + "   Description: " + match.@Rule().@Description())
end foreach
```

**Output:**
```
<h3>Title</h3>   Description: h3 tag
<b>Bold statement</b>   Description: bold tag
<h3>Title B</h3>   Description: h3 tag
<b>Other text</b>   Description: bold tag
<p>My paragraph</p>   Description: other kind of tag
```

---

---

## StartPosition = [int] - ID: 843
/doc/reference/classes/ucalc.matches/ucalc.match/startposition-=-[int]/

**Description:** Retrieves the zero-based starting character position of the matched substring within the source text.

**Remarks:**

# 🎯 Position Property: StartPosition

The `StartPosition` property returns the zero-based character index where an individual match begins within the original source string. It is a fundamental property for understanding the location and context of a match found by a [Transformer](/Reference/uCalcBase/Transformer/Constructor) operation.

This property is accessed on an individual [Match](/Reference/uCalcBase/Matches/Match/Constructor) object, which is typically retrieved by iterating through a [Matches](/Reference/uCalcBase/Matches/Constructor) collection returned by [Transformer.Matches()](/Reference/uCalcBase/Transformer/Matches).

## ⚙️ How It Works: The Match Coordinate System

`StartPosition` is part of a coordinate system that precisely defines a match's location and size:

*   **`StartPosition`**: The index of the *first* character of the match.
*   **[EndPosition](/Reference/uCalcBase/Matches/Match/EndPosition)**: The index of the character *immediately after* the last character of the match.
*   **[Length](/Reference/uCalcBase/Matches/Match/Length)**: The total number of characters in the match.

These three properties are always related by the formula:
[pseudocode]`match.Length() == match.EndPosition() - match.StartPosition()`

Understanding this relationship is key to programmatically selecting, analyzing, or modifying substrings based on match results.

## 💡 Comparative Analysis

*   **vs. C# Regex `Match.Index`**: The `StartPosition` property is functionally identical to the `Index` property on a `System.Text.RegularExpressions.Match` object in .NET. This design choice makes uCalc's API feel familiar and intuitive to developers accustomed to standard regular expression libraries.


## ⚠️ For Internal Use: The Setter

This property also has a setter which is **not intended for general use**. It is used internally by the uCalc wrappers for .NET (C# and VB.NET) to adjust character positions when mapping from the engine's internal UTF-8 string representation to .NET's native UTF-16. Modifying this value directly may lead to inconsistent or incorrect match data.

**Examples:**

### Example ID: 829

**Description:** A basic example to get the starting index of a single word.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("Hello World");
t.Pattern("World");
t.Find();

var matches = t.@Matches();
wl("Match found at position: ", matches[0].@StartPosition())
```

**Output:**
```
Match found at position: 6
```

---

### Example ID: 830

**Description:** Parsing log entries to create a map of error locations within the text.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("[INFO] System boot. [ERROR] Connection failed. [INFO] Retrying...");
t.Pattern("'['ERROR']' {msg}.");
t.Find();

wl("Found ", t.@Matches().Count(), " error(s):")
foreach(var match in t.@Matches())
  wl("- '", match.@Text(), "' starts at index ", match.@StartPosition())
end foreach
```

**Output:**
```
Found 1 error(s):
- '[ERROR] Connection failed.' starts at index 20
```

---

### Example ID: 831

**Description:** Internal Test: Verifies that StartPosition is correct for multiple, non-contiguous matches.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("a b c a d e a f g");
//        ^       ^       ^
// Pos:   0       6       12
t.Pattern("a");
t.Find();

var matches = t.@Matches();
wl("Match 1 Start: ", matches[0].@StartPosition()) // Should be 0
wl("Match 2 Start: ", matches[1].@StartPosition()) // Should be 6
wl("Match 3 Start: ", matches[2].@StartPosition()) // Should be 12
```

**Output:**
```
Match 1 Start: 0
Match 2 Start: 6
Match 3 Start: 12
```

---

### Example ID: 111

**Description:** Returns Start and End positions of Transformer matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>");
//         ^             ^                       ^              ^
//     012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50
// Carrets (^) point to Start and End locations of the matches

wl(t.@Text())
wl("")

t.Pattern("<{tag}>{etc}</{tag}>");
t.Find();
var Matches = t.@Matches();

wl(Matches[0].@Text())
wl("Start pos: ", Matches[0].@StartPosition())
wl("End pos: ", Matches[0].@EndPosition())
wl("Length: ", Matches[0].@Length())
wl("")

wl(Matches[1].@Text())
wl("Start pos: ", Matches[1].@StartPosition())
wl("End pos: ", Matches[1].@EndPosition())
wl("Length: ", Matches[1].@Length())
```

**Output:**
```
<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>

<h1>First</h1>
Start pos: 4
End pos: 18
Length: 14

<h2>Second</h2>
Start pos: 42
End pos: 57
Length: 15
```

---

### Example ID: 114

**Description:** Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>");
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text())
   wl("Start pos: ", match.@StartPosition())
   wl("End pos: ", match.@EndPosition())
   wl("Length: ", match.@Length())
   wl("")
end foreach
```

**Output:**
```
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
```

---

---

## Text = [string] - ID: 842
/doc/reference/classes/ucalc.matches/ucalc.match/text-=-[string]/

**Description:** Retrieves the read-only string of characters captured by an individual match result.

**Remarks:**

The `Text` property returns the exact string of text that was captured by the pattern rule that generated this specific match.

### 🎯 Primary Use Case

This property is the main way to access the content of an individual result from a [Matches](/Reference/uCalcBase/Matches/Constructor) collection. It is a read-only property; a match's text is a snapshot of the source string from a find operation and cannot be modified directly.

### ⚡️ `Match.Text` vs. `Matches.Text`

It is crucial to distinguish between the property on a single `Match` object and the property on the parent `Matches` collection:

*   **`Match.Text` (This Property)**: Returns the text for **one specific match**. This is what you get when you index into a `Matches` collection (e.g., [pseudocode]`myMatches[0].@Text()`).
*   [**`Matches.Text`**](/Reference/uCalcBase/Matches/Text): Returns a single string containing **all matches** concatenated together, typically separated by newlines.

### ⚙️ Behavior After a `Transform()` Operation

A `Match` object is a read-only snapshot of the **original** source string. Therefore, `Text` will always contain the text segment that was found *before* any replacement occurred. To see the new, modified string, you must inspect the `Transformer`'s final output (e.g., `myTransformer.Text()`). The internal test example demonstrates this behavior clearly.

### 📝 Design Note & Future Direction

Based on user feedback, a new property such as `NewText` or `ReplacementText` is under consideration. This would return the text that replaced the original `Match.Text` after a `Transform()` operation. Logically, this would also require corresponding `NewStartPosition`, `NewEndPosition`, and `NewLength` properties to describe the replacement's location and size within the *newly transformed string*. This is a complex feature involving coordinate mapping and is not yet implemented.

### ⚖️ Comparative Analysis

This property is analogous to `Match.Value` in .NET's `System.Text.RegularExpressions` or the result of a captured group in other regex engines.

However, a uCalc `Match` object provides richer context than a standard regex match. While `Text` gives you the captured string, the `Match` object itself also gives you access to:

*   The specific [Rule](/Reference/uCalcBase/Rule/Constructor) that generated the match.
*   The match's [StartPosition](/Reference/uCalcBase/Matches/Match/StartPosition) and [Length](/Reference/uCalcBase/Matches/Match/Length).
*   Nested or child matches if they exist.

This makes `Match.Text` a component of a much more powerful and introspective result set than what is typically available from character-based regex libraries.

**Examples:**

### Example ID: 837

**Description:** Retrieving the text of the first match found in a simple search.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("The price is $19.99 today.");
t.Pattern("{@Number}"); // Find the first number
t.Find();

// Get the collection of matches
var matches = t.@Matches();

// Check if any match was found and get its text
if (matches.Count() > 0)
    wl(matches[0].@Text())
end if
```

**Output:**
```
19.99
```

---

### Example ID: 838

**Description:** Iterating through multiple HTML tag matches and printing the text of each one.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<p>First paragraph.</p> <div>Content</div>");

// Pattern to find any simple HTML-like tag
t.Pattern("<{tag}>{content}</{tag}>");
t.Find();

var matches = t.@Matches();
wl("Found ", matches.Count(), " tags:")
foreach (var match in t.@Matches())
    wl("- ", match.@Text())
end foreach
```

**Output:**
```
Found 2 tags:
- <p>First paragraph.</p>
- <div>Content</div>
```

---

### Example ID: 832

**Description:** How to get the text of the first match found.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("The quick brown fox");
t.Pattern("brown");
t.Find();

// Get the collection of matches
var matches = t.@Matches();

// Check if any matches were found
    // Get the first match object and retrieve its text
    var firstMatch = matches[0];
    wl("Found match: '", firstMatch.@Text(), "'")

```

**Output:**
```
Found match: 'brown'
```

---

### Example ID: 833

**Description:** A practical example that finds all HTML-style tags and prints the text of each one.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h1>Title</h1><p>Text</p>");

// Pattern to find any tag and its content
t.Pattern("<{tag}>{content}</{tag}>");
t.Find();

var allMatches = t.@Matches();
wl("Found ", allMatches.Count(), " matches:")

// Loop through each Match object and print its Text
foreach (var match in allMatches)
    wl(" - ", match.@Text())
end foreach
```

**Output:**
```
Found 2 matches:
 - <h1>Title</h1>
 - <p>Text</p>
```

---

### Example ID: 111

**Description:** Returns Start and End positions of Transformer matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>");
//         ^             ^                       ^              ^
//     012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50
// Carrets (^) point to Start and End locations of the matches

wl(t.@Text())
wl("")

t.Pattern("<{tag}>{etc}</{tag}>");
t.Find();
var Matches = t.@Matches();

wl(Matches[0].@Text())
wl("Start pos: ", Matches[0].@StartPosition())
wl("End pos: ", Matches[0].@EndPosition())
wl("Length: ", Matches[0].@Length())
wl("")

wl(Matches[1].@Text())
wl("Start pos: ", Matches[1].@StartPosition())
wl("End pos: ", Matches[1].@EndPosition())
wl("Length: ", Matches[1].@Length())
```

**Output:**
```
<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>

<h1>First</h1>
Start pos: 4
End pos: 18
Length: 14

<h2>Second</h2>
Start pos: 42
End pos: 57
Length: 15
```

---

### Example ID: 114

**Description:** Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>");
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text())
   wl("Start pos: ", match.@StartPosition())
   wl("End pos: ", match.@EndPosition())
   wl("Length: ", match.@Length())
   wl("")
end foreach
```

**Output:**
```
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
```

---

---

## ApplyOffset - ID: 213
/doc/reference/classes/ucalc.matches/applyoffset/

**Description:** Adjusts the start and end positions of all matches in the collection by a specified offset value.

**Syntax:** ApplyOffset(int64)
**Parameters:**
offset - int64 [default = 0] - The integer value to add to the `StartPosition` and `EndPosition` of every match in the collection. This value can be negative.
**Return:** int64 - Returns the number of matches in the collection whose positions were updated.
**Remarks:**

The `Offset` method provides a crucial utility for remapping match coordinates. It modifies the [StartPosition](/Reference/uCalcBase/Matches/Match/StartPosition) and [EndPosition](/Reference/uCalcBase/Matches/Match/EndPosition) of every match in the collection by adding the specified `offset` value. This is an in-place modification.

### 🎯 Primary Use Case: Remapping Local Coordinates

This method is most powerful when you perform a search on a *substring* of a larger document. The resulting matches will have positions relative to the start of the substring (index 0), not the original document. `Offset` allows you to easily translate these local coordinates back into the global coordinate space of the original document.

Consider the following workflow:
1.  Extract a portion of a large text document.
2.  Run a [Find()](/Reference/uCalcBase/Transformer/Find) operation on that smaller portion.
3.  Determine the starting position of the substring within the original document.
4.  Call `Offset()` on the resulting [Matches](/Reference/uCalcBase/Matches/Constructor) collection, passing the substring's starting position as the offset.

After this operation, the [StartPosition](/Reference/uCalcBase/Matches/Match/StartPosition) and [EndPosition](/Reference/uCalcBase/Matches/Match/EndPosition) of each match will correctly reflect its location within the original, full document.

### 💡 Comparative Analysis

Without this method, remapping coordinates would require a manual loop, which is both verbose and error-prone:

```pseudocode
// Manual, less efficient way
for (i = 0 to matches.Count() - 1)
    var oldPos = matches[i].@StartPosition();
    matches[i].@StartPosition(oldPos + globalOffset);
    // ... and repeat for EndPosition ...
end for
```

The `Offset` method provides a single, high-performance, atomic operation that handles this logic internally, leading to cleaner and more reliable code.

**Examples:**

### Example ID: 849

**Description:** A simple demonstration of adding a fixed offset to a match's coordinates.

**Code:**
```pseudocode
var t = uc.NewTransformer().SetText("The quick brown fox jumps over.");
t.Pattern("fox");
t.Find();

var matches = t.@Matches();
wl("Original Start Position: ", matches[0].@StartPosition())

// Add an offset of 100 to all match positions
matches.ApplyOffset(100);

wl("New Start Position: ", matches[0].@StartPosition())
```

**Output:**
```
Original Start Position: 16
New Start Position: 116
```

---

### Example ID: 850

**Description:** A practical example showing how to remap a match found in a substring back to the global coordinates of the original document.

**Code:**
```pseudocode
[c]string document[/c][vb]Dim Document As String[/vb] = "HEADER::BEGIN[data to find]END::FOOTER";

// 1. Isolate the content block we want to search in.
// Assume the block we care about is between BEGIN and END.
var startIndex = document.[cpp]find[/cpp][NotCpp]IndexOf[/NotCpp]("BEGIN[") + 6;
var endIndex = document.[cpp]find[/cpp][NotCpp]IndexOf[/NotCpp]("]END");
var contentLength = endIndex - startIndex;
var contentBlock = document.[cpp]substr[/cpp][NotCpp]Substring[/NotCpp](startIndex, contentLength);
wl("Searching within substring: '", contentBlock, "'")

// 2. Perform a find operation on just that substring.
var t = uc.NewTransformer().SetText(contentBlock);
t.Pattern("find");
t.Find();
var matches = t.@Matches();

wl("Local match StartPosition: ", matches[0].@StartPosition()) // Relative to 'contentBlock'

// 3. Apply the offset to remap to the global 'document' coordinate space.
matches.ApplyOffset(startIndex);

wl("Global match StartPosition: ", matches[0].@StartPosition())
```

**Output:**
```
Searching within substring: 'data to find'
Local match StartPosition: 8
Global match StartPosition: 22
```

---

---

## Count - ID: 201
/doc/reference/classes/ucalc.matches/count/

**Description:** Gets the total number of matches found by a Transformer operation.

**Syntax:** Count()
**Return:** int - The total number of matches found in the collection.
**Remarks:**

`Count()` returns the total number of matches found by the most recent [Transformer](/Reference/uCalcBase/Transformer/Constructor) operation, such as [Find()](/Reference/uCalcBase/Transformer/Find), [Filter()](/Reference/uCalcBase/Transformer/Filter), or [Transform()](/Reference/uCalcBase/Transformer/Transform).

### 🎯 Primary Use Case: Loop Boundaries

This method is most commonly used to determine the upper bound for a `for` loop that iterates through the collection of matches to inspect or process each one individually.

```pseudocode
// Get the collection of all matches
var allMatches = myTransformer.Matches();

// Loop from the first match to the last
for (i = 0 to allMatches.Count() - 1)
    // Access the i-th match
    wl("Match ", i, ": ", allMatches[i].@Text());
end for
```

### 🌍 Global Count vs. Rule-Specific Count

It's important to distinguish between the total match count and the count for a specific rule:

*   [pseudocode]`myTransformer.Matches().Count()`: Returns the total number of matches found by **all** active rules in the transformer.
*   [pseudocode]`myRule.Matches().Count()`: Returns the number of matches found **only by that specific rule**.

This allows for both a high-level overview and a granular analysis of the transformation results.

### 💡 Comparative Analysis

The `Count()` method is analogous to `.Count` properties on collections in C# or `.size()` methods in C++. It provides a familiar way to determine the size of a result set.

However, unlike a simple collection, the [Matches](/Reference/uCalcBase/Matches/Constructor) object represents the outcome of a complex, pattern-based search across an input string. Its count reflects how many times the defined rules successfully matched segments of the text, taking into account precedence, tokenization, and any exclusion rules (like [SkipOver](/Reference/uCalcBase/Transformer/SkipOver)). The value is therefore the result of a dynamic process, not just the size of a static list.

**Examples:**

### Example ID: 785

**Description:** How to count all alphanumeric words in a sentence.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("There are five words here.");

// Define a pattern to find any alphanumeric word
t.Pattern("{@Alpha}");
t.Find();

wl("Total words found: ", t.@Matches().Count())
```

**Output:**
```
Total words found: 5
```

---

### Example ID: 786

**Description:** A practical example showing the difference between counting all matches and counting matches for a specific rule.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h1>Header</h1><p>Paragraph 1.</p><p>Paragraph 2.</p>");

// Define rules for different tags
var h1Rule = t.Pattern("<h1>{text}</h1>");
var pRule = t.Pattern("<p>{text}</p>");
t.Find();

// Get the total count of all matches from all rules
wl("Total matches (all rules): ", t.@Matches().Count())

// Get the count for only the paragraph rule
wl("Paragraph matches only: ", pRule.@Matches().Count())
```

**Output:**
```
Total matches (all rules): 3
Paragraph matches only: 2
```

---

### Example ID: 787

**Description:** Internal Test: Verifies how filtering the matches collection affects the count.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("ID:100, Name:Admin, ID:200");

// Define two rules, but only one is marked as 'focusable'
var idRule = t.Pattern("ID:{@Number}").SetFocusable(true);
var nameRule = t.Pattern("Name:{@Alpha}").SetFocusable(false);
t.Find();

// The total count includes all matches regardless of properties
wl("Total matches found: ", t.@Matches().Count())

// The count changes when we filter the list to only include focusable matches
var focusableMatches = t.GetMatches(MatchesOption::FocusableOnly);
wl("Focusable matches count: ", focusableMatches.Count())
```

**Output:**
```
Total matches found: 3
Focusable matches count: 2
```

---

### Example ID: 110

**Description:** How to find matched patterns while skipping commented text using SkipOver().

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("int result = (x + 3) * 2 - (y - 7 / z) * (5 ^ a + 10); /* (x + y) */");

// Capture standard blocks surrounded by parentheses
t.Pattern("({expr})");

// Instruct the transformer to ignore any text inside C-style block comments.
// This prevents the commented "(x + y)" from being falsely counted as a match.
t.SkipOver("/* {etc} */"); // commented text between /* */ is skipped

t.Find();
wl(t.@Matches().Count())
```

**Output:**
```
3
```

---

### Example ID: 114

**Description:** Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>");
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text())
   wl("Start pos: ", match.@StartPosition())
   wl("End pos: ", match.@EndPosition())
   wl("Length: ", match.@Length())
   wl("")
end foreach
```

**Output:**
```
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
```

---

---

## Handle - ID: 204
/doc/reference/classes/ucalc.matches/handle/

**Description:** Returns the handle of an object

**Syntax:** Handle()
**Return:** Matches - 
**Remarks:**

Mostly for internal use.

Each object has a handle, which is used to communicate with the uCalc library.  It may not have other uses cases beyond troubleshooting.

---

## IndexOf - ID: 205
/doc/reference/classes/ucalc.matches/indexof/

**Description:** Retrieves the zero-based index of a match based on its starting character position within the source text.

**Syntax:** IndexOf(int, int)
**Parameters:**
startPos - int - The starting character position of the match to find.
nearestIndex - int [default = 0] - An optional performance hint specifying a nearby match index to start the search from, which is faster than searching from the beginning of a large list.
**Return:** int - The zero-based index of the match at the specified position. Returns an invalid index (typically the maximum value for size_t) if no match starts at that exact position.
**Remarks:**

The `IndexOf` method provides a way to find the index of a match within a [Matches](/Reference/uCalcBase/Matches/Constructor) collection by using its starting character position as a key.

This is the reverse of methods like [StartPosition()](/Reference/uCalcBase/Matches/StartPosition), which give you the position for a given index. `IndexOf` is essential when you have a location in the text and need to identify which match in the collection it corresponds to.

### Parameters

*   `startPos`: The exact, zero-based character position where the desired match begins in the original source string.
*   `nearestIndex` (Performance Hint): This optional parameter provides a significant performance optimization for large collections. If you have an estimate of where the match is likely to be, providing a `nearestIndex` tells the search algorithm to start looking from that point instead of from the beginning of the list.

### 💡 Comparative Analysis

*   **vs. `List.IndexOf` in C#**: Standard library search methods typically find an item by object equality or a predicate. `Matches.IndexOf` is specialized for its context; it searches by a piece of metadata (the start position) rather than by the match's content or object reference. This is a more direct and efficient way to map a location in a text document back to a structured match.

*   **vs. Manual Search**: Without this method, you would need to iterate through the entire `Matches` collection and check the `StartPosition` of each item until you found a match. This is inefficient, especially in large collections. `IndexOf` leverages optimized internal search algorithms, and the `nearestIndex` hint further enhances this performance.

**Examples:**

### Example ID: 843

**Description:** A simple lookup to find the index of the second occurrence of the word 'is'.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("This is a test. It is simple.");
t.Pattern("{@Alpha}");
t.Find();

// The second 'is' starts at character position 19
var index = t.@Matches().IndexOf(19);

wl("The match at character 19 is at index: ", index) 
wl("Match content: '", t.@Matches()[index].@Text(), "'")
```

**Output:**
```
The match at character 19 is at index: 5
Match content: 'is'
```

---

### Example ID: 844

**Description:** Finds the global index of a match that was retrieved from a rule-specific match list.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var log = "INFO: Task started. ERROR: Connection failed. INFO: Task finished.";


var infoRule = t.Pattern("INFO: {msg}.");
var errorRule = t.Pattern("ERROR: {msg}.");
t.@Text(log);
t.Find();

// Get the first match specific to the error rule
var firstErrorMatch = errorRule.@Matches()[0];
wl("First error match text: '", firstErrorMatch.@Text(), "'")

// Now, find its index within the global list of all matches
var globalIndex = t.@Matches().IndexOf(firstErrorMatch.@StartPosition());
wl("The first error is the match at global index: ", globalIndex)

// Verify by printing the match from the global list
wl("Global match at that index: '", t.@Matches()[globalIndex].@Text(), "'")
```

**Output:**
```
First error match text: 'ERROR: Connection failed.'
The first error is the match at global index: 1
Global match at that index: 'ERROR: Connection failed.'
```

---

### Example ID: 113

**Description:** Using IndexOf() in Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");
//     ^             ^                    ^               ^                ^
//     012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50        60        70        80
// Carrets (^) point to Start locations of the matches

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

wl("IndexOf   StartPos   Match")
wl("")

wl("All Matches")
wl("-----------")
foreach(var match in t.@Matches()) 
   wl(t.@Matches().IndexOf(match.@StartPosition()), "         ", match.@StartPosition(), "          ", match.@Text())
end for
wl("")

wl("Bold Matches")
wl("------------")
foreach(var BoldMatch in BoldTag.@Matches()) 
   wl(t.@Matches().IndexOf(BoldMatch.@StartPosition()), "         ", BoldMatch.@StartPosition(), "          ", BoldMatch.@Text())
end for
wl("")

wl("H3 Matches")
wl("----------")
foreach(var H3Match in H3Tag.@Matches()) 
   wl(t.@Matches().IndexOf(H3Match.@StartPosition()), "         ", H3Match.@StartPosition(), "          ", H3Match.@Text())
end for
wl("")

wl("Other Matches")
wl("-------------")
foreach(var AnyOtherMatch in AnyOtherTag.@Matches()) 
   wl(t.@Matches().IndexOf(AnyOtherMatch.@StartPosition()), "         ", AnyOtherMatch.@StartPosition(), "          ", AnyOtherMatch.@Text())
end for
```

**Output:**
```
IndexOf   StartPos   Match

All Matches
-----------
0         0          <h3>Title</h3>
1         14          <b>Bold statement</b>
2         35          <h3>Title B</h3>
3         51          <b>Other text</b>
4         68          <p>My paragraph</p>

Bold Matches
------------
1         14          <b>Bold statement</b>
3         51          <b>Other text</b>

H3 Matches
----------
0         0          <h3>Title</h3>
2         35          <h3>Title B</h3>

Other Matches
-------------
4         68          <p>My paragraph</p>
```

---

---

## MemoryIndex = [int] - ID: 608
/doc/reference/classes/ucalc.matches/memoryindex-=-[int]/

**Description:** Returns the unique index value associated with the object

**Remarks:**

Mostly for internal use.

Each object has an integer index value that is unique to the object within the class.  Unlike the [topic: Handle] value that may change each time you run uCalc, the MemoryIndex value is predictable.

This function may not have other uses cases beyond troubleshooting.

---

## NewStr - ID: 212
/doc/reference/classes/ucalc.matches/newstr/

**Description:** Returns the new string a match was changed to

**Syntax:** NewStr(int)
**Parameters:**
Index - int - Index of match
**Return:** string - String value
**Remarks:**

[revisit this]
This returns the new string that a match was changed to.  For instance if you do a transformation operation that changes all occurrences of "This" in a string to "That", then NewStr(n) would return "That".

**Examples:**

---

## Release - ID: 218
/doc/reference/classes/ucalc.matches/release/

**Description:** Releases a Matches object

**Syntax:** Release()
**Return:** void - 
**Remarks:**

This releases a Matches object from memory.

---

## Remove - ID: 219
/doc/reference/classes/ucalc.matches/remove/

**Description:** Removes a match from the list of matches

**Syntax:** Remove(int)
**Parameters:**
Index - int - Index of match
**Return:** void - 
**Remarks:**

[revisit]

**Examples:**

---

## Reset - ID: 220
/doc/reference/classes/ucalc.matches/reset/

**Description:** Clears or re-filters the collection of matches from a Transformer operation.

**Syntax:** Reset(MatchesOption)
**Parameters:**
options - MatchesOption [default = MatchesOption::SameAsBefore] - An enum member specifying how to reset or filter the collection of matches.
**Return:** void - This method does not return a value; it modifies the `Matches` object in place.
**Remarks:**

The `Reset` method modifies the current [Matches](/Reference/uCalcBase/Matches/Constructor) collection by either clearing it or re-filtering the original result set according to the specified `options`.

This is primarily a performance optimization. Instead of re-running a potentially expensive [Find()](/Reference/uCalcBase/Transformer/Find) operation on a [Transformer](/Reference/uCalcBase/Transformer/Constructor), you can use `Reset` to quickly obtain a different view of the matches that were already found.

### Filtering with `MatchesOption`

The behavior of `Reset` is controlled by the `options` parameter, which accepts a member of the [MatchesOption](/Reference/Enums/MatchesOption) enum:

*   `MatchesOption::EmptyList`: Clears the collection, resulting in a count of 0. This is useful for freeing memory associated with the match list.
*   `MatchesOption::All`: Resets the list to include all matches originally found by the `Transformer` operation.
*   `MatchesOption::FocusableOnly`: Filters the list to include only those matches generated by rules that were marked as focusable (e.g., with `rule.Focusable(true)`).
*   `MatchesOption::RootLevelOnly`: In a set of nested matches created by a [LocalTransformer](/Reference/uCalcBase/Rule/LocalTransformer), this option filters the list to include only the top-level (parent) matches.
*   `MatchesOption::InnermostOnly`: The opposite of `RootLevelOnly`; filters the list to include only the most deeply nested (child) matches.
*   `MatchesOption::SameAsBefore` (Default): Re-applies the same filter option that was used when the [Matches](/Reference/uCalcBase/Matches/Constructor) object was last retrieved. For example, if you called `transformer.Matches(MatchesOption::FocusableOnly)`, a subsequent call to `matches.Reset()` would behave as if you called `matches.Reset(MatchesOption::FocusableOnly)`.

### ⚖️ Comparative Analysis

In a language like C#, developers might filter a collection of results using LINQ:

```csharp
// C# LINQ example
var focusableMatches = allMatches.Where(m => m.Rule.IsFocusable).ToList();
```

This approach is stateless and creates a *new* collection. uCalc's `Reset` method is different: it is **stateful** and modifies the *existing* `Matches` collection in-place. This can be more memory-efficient as it avoids allocating a new list for each filtered view. The ability to re-filter without re-running the initial `Find` operation is a significant performance advantage for complex patterns on large documents.

**Examples:**

### Example ID: 853

**Description:** Practical: Re-filters a result set to show only 'focusable' matches without re-running the search.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("ID:100, Name:Admin, ID:200");

// Define two rules, but only one is marked as 'focusable'
var idRule = t.Pattern("ID:{@Number}").SetFocusable(true);
var nameRule = t.Pattern("Name:{@Alpha}").SetFocusable(false);
t.Find();

var matches = t.GetMatches(MatchesOption::All);
wl("--- All Matches ---")
wl("Count: ", matches.Count())
wl(matches.@Text())

// Now, re-filter the same results to get only the focusable ones
matches.Reset(MatchesOption::FocusableOnly);
wl("")
wl("--- Focusable Matches Only ---")
wl("Count: ", matches.Count())
wl(matches.@Text())
```

**Output:**
```
--- All Matches ---
Count: 3
ID:100
Name:Admin
ID:200

--- Focusable Matches Only ---
Count: 2
ID:100
ID:200
```

---

---

## Text = [string] - ID: 880
/doc/reference/classes/ucalc.matches/text-=-[string]/

**Description:** Retrieves a single string containing the text of all matches, concatenated and separated by newlines.

**Remarks:**

The `Text` property aggregates the text of every individual [Match](/Reference/uCalcBase/Matches/Match/Constructor) in the collection into a single, newline-separated string. This provides a quick and convenient way to get a consolidated list of all substrings found by a [Transformer](/Reference/uCalcBase/Transformer/Constructor) operation.

### `Matches.Text` vs. `Match.Text`

It is crucial to distinguish between the property on the collection and the property on an individual match:

*   **`Matches.Text` (This Property)**: Operates on the entire `Matches` collection and returns a single string containing *all* matches (e.g., `"match1\nmatch2\nmatch3"`).
*   **[Match.Text](/Reference/uCalcBase/Matches/Match/Text)**: Operates on a single `Match` object within the collection and returns only its text (e.g., `"match1"`).

### ⚖️ Comparative Analysis

This property is a convenience feature analogous to joining a list of strings in other languages.

*   **vs. C# `string.Join`**: In C#, you would typically iterate through a `MatchCollection`, extract the `Value` of each match into a new list, and then call `string.Join("\n", listOfValues)`. uCalc's `Matches.Text` property encapsulates this entire process into a single, efficient call.

Currently, the separator is hardcoded to a newline. For more flexible concatenation (e.g., creating a comma-separated list), you would need to iterate through the matches and build the string manually.

**Examples:**

### Example ID: 855

**Description:** Filters matches by rule; FilterByRule, Matches.Str, Matches.Count

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

wl("All matches -- count = ", t.@Matches().Count())
wl("----------------------")
wl(t.@Matches().@Text())
wl("")

wl("Only BoldTag matches -- count = ", BoldTag.@Matches().Count())
wl("-------------------------------")
wl(BoldTag.@Matches().@Text())
wl("")

wl("Only H3Tag matches -- count = ", H3Tag.@Matches().Count())
wl("-----------------------------")
wl(H3Tag.@Matches().@Text())
```

**Output:**
```
All matches -- count = 5
----------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
<p>My paragraph</p>

Only BoldTag matches -- count = 2
-------------------------------
<b>Bold statement</b>
<b>Other text</b>

Only H3Tag matches -- count = 2
-----------------------------
<h3>Title</h3>
<h3>Title B</h3>
```

---

---

## uCalc = [uCalc] - ID: 529
/doc/reference/classes/ucalc.matches/ucalc-=-[ucalc]/

**Description:** Retrieves the parent uCalc instance that owns the transformer and its matches, providing access to the full evaluation context.

**Remarks:**

### 🎯 Retrieving the Execution Context

Every [Matches](/Reference/uCalcBase/Matches/Constructor) object is intrinsically linked to the [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance that created its parent [Transformer](/Reference/uCalcBase/Transformer/Constructor). This parent instance holds the complete context—variables, functions, operators, and settings—required for any subsequent evaluations. The `uCalc()` property provides a way to retrieve this parent instance, enabling you to inspect or modify the evaluation environment dynamically.

This is a read-only property.

### 💡 Core Use Cases

1.  **Contextual Operations**: The most common use is to perform another operation within the same context as the matches. If you have a `Matches` object but not a direct reference to its parent `uCalc` instance, you can use this property to retrieve it and call methods like [Eval()](/Reference/uCalcBase/uCalc/Eval) or [DefineVariable()](/Reference/uCalcBase/uCalc/DefineVariable).

2.  **Instance Introspection**: It allows you to determine if two different `Matches` collections belong to the same execution context, which is invaluable for debugging applications that manage multiple, isolated uCalc instances.

3.  **Accessing Sibling Items**: Once you retrieve the parent instance, you can use it to find other items within the same sandbox, for example: [pseudocode]`myMatches.@uCalc().ItemOf("SomeOtherVar")`.

### ⚖️ Comparative Analysis

*   **vs. Native Objects (C#/C++)**: In standard object-oriented programming, an object typically does not maintain a public reference to the factory or container that created it. You would have to design this relationship manually. uCalc makes this parent-child link a first-class, built-in feature, simplifying the management of multiple, concurrent parsing environments.

*   **vs. Document Object Model (DOM)**: The relationship is analogous to the DOM in web development. Just as an HTML element has an `ownerDocument` property that points back to the document it belongs to, a uCalc `Matches` object has its `uCalc()` property to get back to its owner instance. This provides a consistent and predictable way to navigate the object hierarchy.

**Examples:**

### Example ID: 859

**Description:** How to retrieve the parent uCalc instance from a Matches object and verify its identity.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("some text");
t.Pattern("some");
t.Find();
var m = t.@Matches();

// Get the parent uCalc instance from the Matches collection
var parent_uc = m.@uCalc();

// Verify they are the same instance using their MemoryIndex
wl(bool(parent_uc.@MemoryIndex() == uc.@MemoryIndex()))
```

**Output:**
```
True
```

---

### Example ID: 860

**Description:** Demonstrates context isolation by retrieving the parent uCalc instance from a Matches object and evaluating an expression that only exists in that parent's context.

**Code:**
```pseudocode
New(uCalc, uc1)
uc1.DefineVariable("val = 100");

New(uCalc, uc2)
uc2.DefineVariable("val = 200");

// Create the transformer in uc1's context
var t = uc1.NewTransformer();
t.@Text("data");
t.Pattern("data");
t.Find();

var m = t.@Matches();
var parent_uc = m.@uCalc();

wl("Parent has value: ", parent_uc.Eval("val"))
wl("Is parent uc1? ", bool(parent_uc.@MemoryIndex() == uc1.@MemoryIndex()))
wl("Is parent uc2? ", bool(parent_uc.@MemoryIndex() == uc2.@MemoryIndex()))
```

**Output:**
```
Parent has value: 100
Is parent uc1? True
Is parent uc2? False
```

---

### Example ID: 861

**Description:** Internal Test: Verifies that the parent uCalc instance can be retrieved even from an empty Matches collection.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// NOTE: We do NOT call t.Find(), so the matches collection is empty.

var m = t.@Matches();

wl("Match count: ", m.Count())

// Even with no matches, the parent context should be accessible
var parent_uc = m.@uCalc();

wl("Parent uCalc is valid: ", bool(parent_uc.@MemoryIndex() == uc.@MemoryIndex()))
```

**Output:**
```
Match count: 0
Parent uCalc is valid: True
```

---

---

## uCalc.Rule - ID: 228
/doc/reference/classes/ucalc.rule/

**Description:** Class for rules

---

## Introduction - ID: 967
/doc/reference/classes/ucalc.rule/introduction/

**Description:** An overview of the Rule object, the core component representing a compiled pattern and its behavioral properties in the Transformer.

**Remarks:**

# 🎯 The Rule Object: A Compiled Pattern

The `Rule` class is the fundamental building block of the uCalc [Transformer](/Reference/uCalcBase/Transformer/Constructor). It represents a single, compiled search pattern and its associated action, such as a replacement string or a callback. When you define a pattern with methods like [FromTo()](/Reference/uCalcBase/Transformer/FromTo) or [Pattern()](/Reference/uCalcBase/Transformer/Pattern), the [Transformer](/Reference/uCalcBase/Transformer/Constructor) creates a `Rule` object internally.

By obtaining a handle to this `Rule` object, you gain powerful, granular control over its behavior at runtime.

---

## ⚙️ Core Concepts

*   **Stateful, Configurable Objects**: Unlike a simple Regex pattern (which is just a string), a `Rule` is a stateful object with a rich set of properties. You can programmatically control its behavior after it has been created, toggling features like case sensitivity, whitespace handling, or its active state.

*   **Precedence and Order (LIFO)**: When a [Transformer](/Reference/uCalcBase/Transformer/Constructor) has multiple rules, their precedence is determined by a **Last-In, First-Out (LIFO)** order. The most recently defined rule is checked first. This allows you to build a base of general rules and then add more specific, higher-precedence rules on top of them.

*   **Hierarchical Parsing**: Rules can be nested using the [LocalTransformer](/Reference/uCalcBase/Rule/LocalTransformer) property. This allows you to create parent-child relationships where a set of "child" rules only applies to the text captured by a "parent" rule, enabling sophisticated parsing of structured, nested data.

---

## 📖 Member List

| Member | Description |
| :--- | :--- |
| [`Active`](/Reference/uCalcBase/Rule/Active) | Gets or sets whether the rule is active and will be considered during pattern matching. |
| [`BracketSensitive`](/Reference/uCalcBase/Rule/BracketSensitive) | Controls whether the rule respects balanced bracket pairs. |
| [`CaseSensitive`](/Reference/uCalcBase/Rule/CaseSensitive) | Controls whether pattern matching for the rule is case-sensitive. |
| [`Description`](/Reference/uCalcBase/Rule/Description) | Gets or sets a user-defined text description for metadata and debugging. |
| [`Focusable`](/Reference/uCalcBase/Rule/Focusable) | Flags a rule's matches for inclusion/exclusion from filtered result sets. |
| [`GlobalMaximum`](/Reference/uCalcBase/Rule/GlobalMaximum) | Sets a global match limit; if exceeded, the entire transformation pass is invalidated. |
| [`GlobalMinimum`](/Reference/uCalcBase/Rule/GlobalMinimum) | Sets a global minimum match requirement; if not met, the entire pass is invalidated. |
| [`HasLocalTransformer`](/Reference/uCalcBase/Rule/HasLocalTransformer) | Checks if the rule has a nested local transformer without creating one. |
| [`IsChildRule`](/Reference/uCalcBase/Rule/IsChildRule) | Determines if the rule belongs to a nested (local) transformer. |
| [`LocalTransformer`](/Reference/uCalcBase/Rule/LocalTransformer) | Gets a nested Transformer scoped exclusively to the text matched by this rule. |
| [`Matches`](/Reference/uCalcBase/Rule/Matches) | Retrieves the collection of matches found exclusively by this rule. |
| [`Maximum`](/Reference/uCalcBase/Rule/Maximum) | Sets a rule-specific match limit; if exceeded, only this rule's matches are invalidated. |
| [`Minimum`](/Reference/uCalcBase/Rule/Minimum) | Sets a rule-specific minimum match requirement; if not met, only this rule's matches are invalidated. |
| [`Name`](/Reference/uCalcBase/Rule/Name) | Gets the programmatic name of the rule, derived from its pattern. |
| [`NextOverload`](/Reference/uCalcBase/Rule/NextOverload) | Retrieves the next rule in a sequence of rules that share the same starting anchor. |
| [`ParentTransformer`](/Reference/uCalcBase/Rule/ParentTransformer) | Retrieves the parent Transformer that owns this rule. |
| [`Pattern`](/Reference/uCalcBase/Rule/Pattern) | Gets the original pattern string that defines the rule's matching criteria. |
| [`Precedence`](/Reference/uCalcBase/Rule/Precedence) | Gets or sets the rule's precedence level. |
| [`QuoteSensitive`](/Reference/uCalcBase/Rule/QuoteSensitive) | Controls whether the rule respects quoted strings as atomic units. |
| [`Release`](/Reference/uCalcBase/Rule/Release) | Permanently removes the rule from the transformer. |
| [`Replacement`](/Reference/uCalcBase/Rule/Replacement) | Gets or sets the replacement string for the rule. |
| [`RewindOnChange`](/Reference/uCalcBase/Rule/RewindOnChange) | Controls whether the transformer re-scans text after a replacement, enabling recursive transformations. |
| [`StartAfter`](/Reference/uCalcBase/Rule/StartAfter) | Sets the number of matches to skip before including results. |
| [`StatementSensitive`](/Reference/uCalcBase/Rule/StatementSensitive) | Controls whether the rule respects statement separators (like semicolons or newlines). |
| [`StopAfter`](/Reference/uCalcBase/Rule/StopAfter) | Sets the maximum number of matches this rule will find before stopping. |
| [`Tag`](/Reference/uCalcBase/Rule/Tag) | Gets or sets a user-defined integer for fast, programmatic identification. |
| [`uCalc`](/Reference/uCalcBase/Rule/uCalc) | Retrieves the root uCalc instance that provides the execution context. |
| [`Verbatim`](/Reference/uCalcBase/Rule/Verbatim) | Controls whether variable captures are treated as verbatim blocks, preventing nested matching. |
| [`WhitespaceSensitive`](/Reference/uCalcBase/Rule/WhitespaceSensitive) | Controls whether whitespace is treated as a significant token. |

---

## ⚖️ Comparative Analysis

*   **vs. Regular Expressions**:
    *   **Stateful vs. Static**: A Regex pattern is typically a static string, often with global flags (`/i`, `/g`). To change its behavior, you must recompile it. A uCalc `Rule` is a dynamic object whose properties ([`CaseSensitive`](/Reference/uCalcBase/Rule/CaseSensitive), [`Active`](/Reference/uCalcBase/Rule/Active), etc.) can be toggled at runtime without recompiling the pattern.
    *   **Context-Awareness**: A `Rule` inherits the token-aware nature of the [Transformer](/Reference/uCalcBase/Transformer/Constructor). It understands language constructs like quotes and brackets, a level of structural awareness that is difficult and fragile to achieve with pure regex.

**Examples:**

### Example ID: 985

**Description:** Finding all occurrences of a letter except for the first one.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("a b c a d e a f g");
var ruleA = t.FromTo("a", "[MATCH]");

// Skip the first 'a' that is found
ruleA.@StartAfter(1);

wl(t.Transform())
```

**Output:**
```
a b c [MATCH] d e [MATCH] f g
```

---

### Example ID: 981

**Description:** Applies `RewindOnChange` to a default rule set to enable complex, multi-rule transformations for a custom `Average` function.

**Code:**
```pseudocode
var t = uc.@ExpressionTransformer();

// Enable rewind for all subsequent rules in this transformer.
t.@DefaultRuleSet().SetRewindOnChange(true);

// Define the recursive rules.
t.FromTo("AddUp({x})", "{x}");
t.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

t.FromTo("ArgCount({x})", "1");
t.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))");

// The main rule that combines the others.
t.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})");

var expression = "Average(1, 2, 3, 4)";
wl("Input: ", expression)
wl("Transform: ", t.Transform(expression))
wl("Eval: ", uc.Eval(expression))
```

**Output:**
```
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
```

---

---

## (Constructor) - ID: 654
/doc/reference/classes/ucalc.rule/-constructor/

**Remarks:**

[Maybe have a StartPos and EndPos that would limit the range of text to work with]

In C++, an additional last argument that can be used is a Boolean true or false that represents whether the expression will automatically be released.  In C#, use "using" (IDisposable) instead for that.

---

## Active = [bool] - ID: 230
/doc/reference/classes/ucalc.rule/active-=-[bool]/

**Description:** Gets or sets a value indicating whether the rule is active and will be considered during pattern matching operations.

**Remarks:**

The `Active` property provides a way to enable or disable a [Rule](/Reference/uCalcBase/Rule/Constructor) at runtime without permanently deleting it. When a rule is inactive (`false`), the [Transformer](/Reference/uCalcBase/Transformer/Constructor) will completely ignore it during a [Find()](/Reference/uCalcBase/Transformer/Find), [Filter()](/Reference/uCalcBase/Transformer/Filter), or [Transform()](/Reference/uCalcBase/Transformer/Transform) operation.

This is a powerful feature for dynamically changing the behavior of a parser or for managing different sets of rules for different modes of operation.

### ⚙️ Getter and Setter Behavior

This property functions as both a getter and a setter:

*   **Getter**: [pseudocode]`var isActive = myRule.@Active();`
    Returns `true` if the rule is active (the default), and `false` if it has been disabled.

*   **Setter**: [pseudocode]`myRule.@Active(false);`
    Sets the active state of the rule. This (`SetActive()` method in VB and C#, or `Active()` in C++) returns the [Rule](/Reference/uCalcBase/Rule/Constructor) object itself, allowing for a fluent, chainable syntax.

### ⚠️ Re-evaluation is Required

It is crucial to understand that changing a rule's `Active` state does **not** immediately affect the results of a previous transformation. You must call [Find()](/Reference/uCalcBase/Transformer/Find), [Filter()](/Reference/uCalcBase/Transformer/Filter), or [Transform()](/Reference/uCalcBase/Transformer/Transform) again to re-evaluate the input text with the updated rule set.

### `Active` vs. `Release()` vs. `Focusable()`

Choose the right tool for managing a rule's lifecycle:

| Method | Purpose | State | Reversibility |
| :--- | :--- | :--- | :--- |
| **`@Active(false)`** | **Temporarily disable** a rule. | The rule's definition is preserved in memory. | Fully reversible by calling `@Active(true)`. |
| **`Release()`** | **Permanently delete** a rule. | The rule is removed from memory and its resources are freed. | Irreversible. The rule must be redefined. |
| **`@Focusable(false)`** | **Visually filter** a rule's matches from the result list. | The rule remains active and participates in matching, but its results can be hidden. | Fully reversible. Does *not* require a re-scan. |

### 💡 Why uCalc? (Comparative Analysis)

In most regex-based systems, "disabling" a pattern is not a built-in feature. A developer would typically have to:

1.  Store regex patterns as strings.
2.  Programmatically build a final "master" regex string by concatenating only the active patterns.
3.  Recompile the entire master regex object whenever the active set changes.

This is verbose, inefficient, and error-prone, especially when dealing with complex patterns.

uCalc's `Active` property provides a declarative, high-performance alternative. You define all your rules once, and then simply toggle their state with a boolean flag. The engine handles the complexity of ignoring inactive rules efficiently, leading to cleaner, more maintainable, and more dynamic code.

**Examples:**

### Example ID: 862

**Description:** Demonstrates the basic toggle functionality of the Active property.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var(string, UserText) = "The cat saw another cat.";
t.@Text(UserText);

// Define a rule and hold its handle
var catRule = t.FromTo("cat", "dog");

w("1. Rule Active (Default): ")
wl(t.Transform())

// Deactivate the rule
catRule.@Active(false);

// Re-run the transform to see the change
w("2. Rule Inactive: ")
t.@Text(UserText);
wl(t.Transform())

// Reactivate the rule
catRule.@Active(true);
w("3. Rule Reactivated: ")
wl(t.Transform())
```

**Output:**
```
1. Rule Active (Default): The dog saw another dog.
2. Rule Inactive: The cat saw another cat.
3. Rule Reactivated: The dog saw another dog.
```

---

### Example ID: 120

**Description:** How to dynamically enable or disable transformation rules using the Active property.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b>");

var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();


wl(t.@Matches().@Text())
wl("")

BoldTag.@Active(false);
wl("BoldTag.Active(): ", bool(BoldTag.@Active()))
wl("-----------------------")
t.Find();
wl(t.@Matches().@Text())
wl("")

BoldTag.@Active(true);
wl("BoldTag.Active(): ", bool(BoldTag.@Active()))
wl("----------------------")

t.Find();
wl(t.@Matches().@Text())
wl("")

```

**Output:**
```
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>

BoldTag.Active(): False
-----------------------
<h3>Title</h3>
<h3>Title B</h3>

BoldTag.Active(): True
----------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
```

---

### Example ID: 885

**Description:** Toggling a rule on and off.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var r = t.FromTo("Hello", "Hi");

// Disable
r.@Active(false);
wl(t.Transform("Hello").@Text()) // Output: Hello (No change)

// Enable
r.@Active(true);
wl(t.Transform("Hello").@Text()) // Output: Hi
```

**Output:**
```
Hello
Hi
```

---

---

## BracketSensitive = [bool] - ID: 233
/doc/reference/classes/ucalc.rule/bracketsensitive-=-[bool]/

**Description:** Controls whether a pattern rule respects balanced bracket pairs, preventing matches from crossing structural boundaries like parentheses or braces.

**Remarks:**

# 🛡️ Structural Integrity: The BracketSensitive Property

The `BracketSensitive` property controls whether a pattern is aware of nested, balanced bracket pairs. When enabled (the default), it prevents a variable capture from starting inside a bracketed block and ending outside of it, ensuring that structural units like function calls or code blocks are treated atomically.

This is a fundamental feature for safely parsing structured text and a key advantage over traditional regular expressions, which are not context-aware.

## ⚙️ How It Works

This property acts as a switch for a rule's parsing logic. The behavior can be set per-rule or globally via the [Transformer.DefaultRuleSet](/Reference/uCalcBase/Transformer/DefaultRuleSet).

| Setting | Behavior |
| :--- | :--- |
| `true` (Default) | **Structurally Aware**. The parser tracks the nesting depth of brackets. A pattern like `A {body} C` will not match `A (B C)` because the closing parenthesis is missing. It correctly matches `A (B) C`. |
| `false` | **Structurally Unaware**. Brackets (`()`, `[]`, `{}`) are treated like any other generic token. The parser will match across boundaries, which can be useful for certain kinds of text analysis but is generally less safe for structured data. |

By default, uCalc recognizes `()`, `[]`, and `{}` as bracket pairs. You can define your own custom pairs (e.g., `begin`/`end` or `<`/`>`) using [uCalc.Tokens.Add](/Reference/uCalcBase/Tokens/Add/Add(string, TokenType, string, int, RegExGrammar, int)).

## 💡 Why uCalc? (Comparative Analysis)

Regular expressions are notoriously poor at handling nested or recursive structures. A simple regex like `\((.*)\)` is greedy and will fail to correctly parse nested calls like `func(a, sub(b))`. While modern regex engines have features like recursive patterns (`(?R)`), they are complex, difficult to maintain, and can lead to "catastrophic backtracking" performance issues.

uCalc's `BracketSensitive` property solves this elegantly by leveraging its token-based architecture:

1.  **Tokenizer Awareness**: The tokenizer identifies opening and closing brackets first, understanding their relationship.
2.  **Parser State**: When `BracketSensitive` is `true`, the parser uses this token information to maintain a nesting level counter.
3.  **Safe Matching**: A pattern variable's capture is only considered complete if the bracket nesting level is the same at the end as it was at the start.

This makes parsing structured, nested data in uCalc both safer and more performant than using regex alone.

**Examples:**

### Example ID: 121

**Description:** BracketSensitive

**Code:**
```pseudocode
var t = uc.NewTransformer();
var Pattern = t.Pattern("< {etc} >");
t.Str("< a b c > d < (e f g) > h < (i) (j k) > l < m n o ( > p) q >");

// Note the difference in the final match

Pattern.@BracketSensitive(true); // true is the default
wl("BracketSensitive: ", bool(Pattern.@BracketSensitive()))
wl("----------------------")
t.Find();
wl(t.@Matches().@Text())
wl("")

Pattern.@BracketSensitive(false);
wl("BracketSensitive: ", bool(Pattern.@BracketSensitive()))
wl("-----------------------")

t.Find();
wl(t.@Matches().@Text())
wl("")

t.Str("( a b ( c ) d e )");
// Here parentheses are captured as regular tokens, not bracket pairs
var Pattern2a = t.Pattern("( {etc} (");
var Pattern2b = t.Pattern(") {etc} )");

wl("Brackets used as part of pattern")
wl("--------------------------------")
Pattern2a.@BracketSensitive(true);
Pattern2b.@BracketSensitive(true);
t.Find();
wl(t.@Matches().@Text())
wl("")
Pattern2a.@BracketSensitive(false);
Pattern2b.@BracketSensitive(false);
t.Find();
wl(t.@Matches().@Text())


```

**Output:**
```
BracketSensitive: True
----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( > p) q >

BracketSensitive: False
-----------------------
< a b c >
< (e f g) >
< (i) (j k) >
< m n o ( >

Brackets used as part of pattern
--------------------------------
( a b (
) d e )

( a b (
) d e )
```

---

---

## CaseSensitive = [bool] - ID: 236
/doc/reference/classes/ucalc.rule/casesensitive-=-[bool]/

**Description:** Gets or sets whether pattern matching for this specific rule is case-sensitive, overriding the transformer's default setting.

**Remarks:**

The `CaseSensitive` property allows you to control the case-sensitivity for an individual [Rule](/Reference/uCalcBase/Rule/Constructor), overriding the global setting inherited from the parent [Transformer](/Reference/uCalcBase/Transformer/Constructor).

By default, all pattern matching in uCalc is **case-insensitive**.

### ⚙️ Getter and Setter Behavior

This property functions as both a getter and a setter:

*   **Getter**: [pseudocode]`var isSensitive = myRule.@CaseSensitive();`
    Returns `true` if the rule is case-sensitive; otherwise, `false`.

*   **Setter**: [pseudocode]`myRule.@CaseSensitive(true);`
    Sets the case-sensitivity for the rule. The method returns the `Rule` object itself, allowing for a fluent, chainable syntax.

### Overriding the Default

This setting provides granular, per-rule control. It overrides the default case-sensitivity behavior defined in the parent transformer's [DefaultRuleSet](/Reference/uCalcBase/Transformer/DefaultRuleSet). This allows you to create a transformer that is case-insensitive by default but contains a few specific rules that must match case exactly.

## 💡 Why uCalc? (Comparative Analysis)

In most traditional Regex engines, case-insensitivity is a global flag applied to the entire pattern at compile time (e.g., the `/i` flag in JavaScript or `RegexOptions.IgnoreCase` in .NET). This is often an all-or-nothing choice.

uCalc's key advantage is its **granularity**. It allows you to mix case-sensitive and case-insensitive rules within the same `Transformer` and have them operate concurrently. This is extremely powerful for parsing languages or data formats where keywords might be case-insensitive (`SELECT`, `select`), but string literals or identifiers are case-sensitive (`"MyVar"` vs. `"myvar"`). This per-rule control provides a level of precision that is difficult to achieve with standard Regex libraries.

**Examples:**

### Example ID: 122

**Description:** CaseSensitive

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("start x y z finish, StArT a b c FinISH, START 1 2 3 FINISH");
var Pattern = t.Pattern("StArT {etc} FinISH");

Pattern.@CaseSensitive(true);
wl("CaseSensitive: ", bool(Pattern.@CaseSensitive()))
wl("-------------------")
t.Find();
wl(t.@Matches().@Text())
wl("")

Pattern.@CaseSensitive(false);
wl("CaseSensitive: ", bool(Pattern.@CaseSensitive()))
wl("--------------------")
t.Find();
wl(t.@Matches().@Text())
```

**Output:**
```
CaseSensitive: True
-------------------
StArT a b c FinISH

CaseSensitive: False
--------------------
start x y z finish
StArT a b c FinISH
START 1 2 3 FINISH
```

---

---

## Description = [string] - ID: 530
/doc/reference/classes/ucalc.rule/description-=-[string]/

**Description:** Gets or sets a user-defined text description for a Transformer rule, useful for attaching metadata and for debugging.

**Remarks:**

The `Description` property provides a way to attach arbitrary string metadata to a [Transformer](/Reference/uCalcBase/Transformer/Constructor) [Rule](/Reference/uCalcBase/Rule/Constructor). This is invaluable for debugging, creating self-documenting configurations, and identifying which rule generated a specific [Match](/Reference/uCalcBase/Matches/Match/Constructor) at runtime.

### ⚙️ Getter and Setter Behavior

This property functions as both a getter and a setter:

*   **Getter**: When called with no arguments, [pseudocode]`myRule.@Description()` returns the current description of the rule. If no description has been set, it returns an empty string.
*   **Setter**: When called with a string argument, [pseudocode]`myRule.@Description("your text")` sets the rule's description. The setter supports a **fluent interface**, meaning it returns the [Rule](/Reference/uCalcBase/Rule/Constructor) object itself, allowing you to chain method calls.

### 🎯 Core Use Cases

*   **Debugging**: When iterating through a list of matches, you can retrieve the rule for each match and print its description. This tells you exactly *why* a segment of text was matched, which is far more direct than trying to interpret a complex pattern string.
*   **Self-Documentation**: Store human-readable notes directly on the rule to explain its purpose or logic. This keeps the documentation tightly coupled with the code it describes.
*   **Runtime Identification**: Use descriptions to tag and identify specific rules for programmatic processing, such as enabling or disabling groups of rules based on their metadata.

### 💡 Comparative Analysis

Without an integrated `Description` property, developers often resort to less ideal solutions for tracking metadata:

*   **External Dictionaries**: Managing a `Dictionary<Rule, string>` is cumbersome. It requires manual synchronization, and if a [Rule](/Reference/uCalcBase/Rule/Constructor) is released, the dictionary entry can become a memory leak.
*   **Wrapper Classes**: Creating a custom class just to add a description field adds significant boilerplate code.

`uCalc`'s approach is superior because the metadata is tightly coupled with the object itself and is consistently available across the object model. This creates a unified, easy-to-use system for runtime introspection.

**Examples:**

### Example ID: 871

**Description:** How to set a description on a rule and then retrieve it.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var myRule = t.FromTo("Hello", "Hi");
myRule.@Description("Simple greeting replacement");

wl("Rule Pattern: ", myRule.@Pattern())
w("Rule Description: ", myRule.@Description())
```

**Output:**
```
Rule Pattern: Hello
Rule Description: Simple greeting replacement
```

---

### Example ID: 118

**Description:** How to assign and retrieve descriptions for specific transformation patterns using SetDescription().

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>").SetDescription("other kind of tag");
var BoldTag = t.Pattern("<b>{text}</b>").SetDescription("bold tag");
var H3Tag = t.Pattern("<h3>{text}</h3>").SetDescription("h3 tag");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text() + "   Description: " + match.@Rule().@Description())
end foreach
```

**Output:**
```
<h3>Title</h3>   Description: h3 tag
<b>Bold statement</b>   Description: bold tag
<h3>Title B</h3>   Description: h3 tag
<b>Other text</b>   Description: bold tag
<p>My paragraph</p>   Description: other kind of tag
```

---

---

## Focusable = [bool] - ID: 242
/doc/reference/classes/ucalc.rule/focusable-=-[bool]/

**Description:** Gets or sets a flag that allows a rule's matches to be included or excluded from a filtered result set, without deactivating the rule itself.

**Remarks:**

The `Focusable` property is a lightweight flag used to control the visibility of a rule's matches in the final result set. It provides a way to filter the output of a search without deactivating the rule or re-running the entire search operation.

### 🎯 What is `Focusable`?

Think of `Focusable` as a tag you can apply to a rule. When you retrieve matches using [Transformer.Matches()](/Reference/uCalcBase/Transformer/Matches) with the `MatchesOption::FocusableOnly` flag, only the matches from rules where `Focusable` is `true` will be included.

This is highly efficient because the `Find()` or `Transform()` operation still runs all active rules, but the final filtering of the results list is a fast, in-memory operation.

### Setter and Getter Behavior

This property functions as both a getter and a setter:

*   **Getter**: `var isFocusable = myRule.@Focusable();`
    Returns `true` if the rule's matches are intended to be included in a focused view; otherwise, `false`.

*   **Setter**: `myRule.@Focusable(true);`
    Sets the state. The method returns the [Rule](/Reference/uCalcBase/Rule/Constructor) object, allowing for a fluent, chainable syntax.

### `Focusable(false)` vs. `Active(false)` vs. `Release()`

It is crucial to understand the difference between these three methods:

| Method | Purpose | Effect on Matching | Reversibility | Performance Cost to Change | 
| :--- | :--- | :--- | :--- | :--- |
| **`@Focusable(false)`** | Hide from filtered results | Rule still runs and participates in `Transform`. | Reversible. | **None**. No re-scan needed. |
| **[`@Active(false)`](/Reference/uCalcBase/Rule/Active)** | Temporarily disable rule | Rule does **not** run or produce matches. | Reversible. | **High**. Requires re-running `Find()`/`Transform()`. |
| **[`Release()`](/Reference/uCalcBase/Rule/Release)** | Permanently delete rule | Rule is gone and cannot run. | Irreversible. | **High**. Requires re-running `Find()`/`Transform()`. |

### 💡 Primary Use Case: UI Highlighting

`Focusable` is ideal for applications like code editors or log viewers where the user might want to toggle highlighting for different types of syntax. For example, a user could check a box to "Highlight all comments." Your code would simply loop through all comment-related rules and set `@Focusable(true)`, then refresh the display using `Matches(MatchesOption::FocusableOnly)` without needing to re-parse the entire document.

### ⚖️ Comparative Analysis

In a standard Regex library, achieving similar functionality would require significant application-side logic:

1.  Run all Regex patterns against the text.
2.  Store all `Match` objects in a list.
3.  For each match, determine which original pattern generated it (often requiring complex group naming or separate searches).
4.  Filter this list in your application code based on external flags.

`uCalc` streamlines this process by integrating the `Focusable` flag directly into the `Rule` object and providing a built-in filtering mechanism with `MatchesOption::FocusableOnly`. This is not only cleaner and less error-prone but also more performant as the filtering logic is handled within the optimized core engine.

**Examples:**

### Example ID: 874

**Description:** A basic demonstration of toggling the Focusable flag to filter a list of matches.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("A B C");

var ruleA = t.Pattern("A").SetFocusable(true);
var ruleB = t.Pattern("B").SetFocusable(true);
var ruleC = t.Pattern("C").SetFocusable(false); // C is not focusable
t.Find();

wl("--- All Matches ---")
wl(t.GetMatches(MatchesOption::All).@Text())

w("--- Focusable Matches ---")
// This list will exclude the match for 'C'.
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
```

**Output:**
```
--- All Matches ---
A
B
C
--- Focusable Matches ---A
B
```

---

### Example ID: 123

**Description:** Focusable to toggle pattern matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b>");

var BoldTag = t.Pattern("<b>{text}</b>").SetFocusable(true);
var H3Tag = t.Pattern("<h3>{text}</h3>").SetFocusable(true);
t.Find();

wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")

BoldTag.@Focusable(false);
wl("BoldTag.Focusable(): ", bool(BoldTag.@Focusable()))
wl("--------------------------")
// t.Find(); // A Find operation does not have to be executed again
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")

BoldTag.@Focusable(true);
wl("BoldTag.Focusable(): ", bool(BoldTag.@Focusable()))
wl("--------------------------")

//t.Find(); // A Find operation does not have to be executed again
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")
```

**Output:**
```
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>

BoldTag.Focusable(): False
--------------------------
<h3>Title</h3>
<h3>Title B</h3>

BoldTag.Focusable(): True
--------------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
```

---

### Example ID: 139

**Description:** Focusable to select only patterns from local transformer

**Code:**
```pseudocode
var t = uc.NewTransformer();
var FruitsXML =
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <!-- <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' /> -->
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <!-- <Fruit CommonName='Mango' ScientificName='Mangifera indica' /> -->
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <!-- <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' /> -->
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <!-- <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' /> -->
</Fruits>
[/verbatim];

// List names of fruit within comment, not the whole comment as well
t.@Text(FruitsXML);
var CommentedFruits = t.Pattern("<!-- {comment} -->").SetFocusable(false);
var CommentedFruitsTr = CommentedFruits.@LocalTransformer();
CommentedFruitsTr.FromTo("CommonName={@string:text}", "{text}").@Focusable(true);

t.Filter();
wl("With Focusable()")
wl("----------------")
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")

// Note: The displayed Fruit element is modified by CommentedFruitsTr.FromTo()
wl("Without Focusable()")
wl("-------------------")
wl(t.@Matches().@Text())
```

**Output:**
```
With Focusable()
----------------
Grapes
Mango
Rambutan
Watermelon

Without Focusable()
-------------------
<!-- <Fruit Grapes ScientificName='Vitis vinifera' /> -->
Grapes
<!-- <Fruit Mango ScientificName='Mangifera indica' /> -->
Mango
<!-- <Fruit Rambutan ScientificName='Nephelium lappaceum' /> -->
Rambutan
<!-- <Fruit Watermelon ScientificName='Citrullus lanatus' /> -->
Watermelon
```

---

---

## FromTo - ID: 247
/doc/reference/classes/ucalc.rule/fromto/

**Description:** Defines a transformer rule

**Syntax:** FromTo(string, string)
**Parameters:**
FromStr - string - Pattern that describes the text to match
ToStr - string [default = ""] - New text that the match should be changed to
**Return:** Rule - Object for rule being defined
**Remarks:**

[revisit]
Whenever a piece of text matches the pattern described in FromStr, it is replaced with the text found in ToStr.

---

## GetMatches - ID: 261
/doc/reference/classes/ucalc.rule/getmatches/

**Description:** Retrieves the collection of matches found specifically by this rule, with options to filter the results.

**Syntax:** GetMatches(MatchesOption, bool)
**Parameters:**
options - MatchesOption [default = MatchesOption::SameAsBefore] - Specifies the subset of matches to return, such as all, focusable only, or only the root/innermost level.
Map_UTF16 - bool [default = false] - Internal use only. Controls UTF-16 character mapping for .NET environments.
**Return:** Matches - A `Matches` object containing the collection of matches found by this rule, filtered according to the provided options.
**Remarks:**

# 🎯 Rule.GetMatches Property

Retrieves the collection of matches generated exclusively by this specific `Rule`, providing a more granular view than the global [Transformer.Matches](/Reference/uCalcBase/Transformer/Matches) property.

This property is your primary tool for inspecting the results of a single pattern. While [pseudocode]`myTransformer.@Matches()` returns a collection of all matches found by *all* active rules, [pseudocode]`myRule.@Matches()` returns only the subset of those matches that were found by `myRule`.

---
## ⚙️ Filtering with `MatchesOption`

The optional `options` parameter allows you to refine the returned list based on the structure and properties of the matches, using members of the [MatchesOption](/Reference/Enums/MatchesOption) enum:

*   `MatchesOption::All` (Default): Returns all matches found by this rule.
*   `MatchesOption::FocusableOnly`: Returns only those matches if this rule was marked as focusable (e.g., with [pseudocode]`myRule.@Focusable(true)`).
*   `MatchesOption::RootLevelOnly`: In a set of nested matches (created by a [LocalTransformer](/Reference/uCalcBase/Rule/LocalTransformer)), this returns only the top-level (parent) matches from this rule.
*   `MatchesOption::InnermostOnly`: The opposite of `RootLevelOnly`; returns only the most deeply nested (child) matches from this rule.

This filtering is a performance optimization, as it allows you to get different views of the results without re-running the initial `Find()` or `Transform()` operation.

---
## 💡 Why uCalc? (Comparative Analysis)

In other environments, such as using LINQ in C#, you would typically get a single large list of all results and then filter it manually.

**Typical C# LINQ Approach:**
```csharp
// Get all matches and then filter by rule reference
var ruleSpecificMatches = allMatches.Where(m => m.Rule == mySpecificRule).ToList();
```

While functional, this approach performs the filtering in the host application after retrieving all the data. uCalc's design is more efficient:

*   **Engine-Side Filtering**: By passing the `options` and calling the property on a specific `Rule`, the filtering logic is executed inside the highly optimized uCalc engine.
*   **Direct Access**: It provides a more direct and declarative way to ask, "Show me just the results for this pattern," leading to cleaner and more readable code.

**Examples:**

### Example ID: 876

**Description:** The difference between counting all matches versus matches for a specific rule.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("A B C A B C");

var ruleA = t.Pattern("A");
var ruleB = t.Pattern("B");

t.Find();

wl("Total matches (all rules): ", t.@Matches().Count())
wl("Matches for Rule A only: ", ruleA.@Matches().Count())
wl("Matches for Rule B only: ", ruleB.@Matches().Count())
```

**Output:**
```
Total matches (all rules): 4
Matches for Rule A only: 2
Matches for Rule B only: 2
```

---

### Example ID: 877

**Description:** A practical example using `MatchesOption::FocusableOnly` to retrieve results only from rules marked as focusable.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("ID:100, Name:Admin, ID:200");

// Mark 'ID' rules as focusable, but 'Name' rules as secondary.
var idRule = t.Pattern("ID:{@Number}").SetFocusable(true);
var nameRule = t.Pattern("Name:{@Alpha}").SetFocusable(false);
t.Find();

// Get the matches for the 'idRule' specifically, filtered to only focusable results.
var focusableIdMatches = idRule.GetMatches(MatchesOption::FocusableOnly);

wl("Focusable 'ID' matches found: ", focusableIdMatches.Count())
wl(focusableIdMatches.@Text())
```

**Output:**
```
Focusable 'ID' matches found: 2
ID:100
ID:200
```

---

### Example ID: 112

**Description:** Filters matches by rule; FilterByRule, Matches.Str, Matches.Count

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

wl("All matches -- count = ", t.@Matches().Count())
wl("----------------------")
wl(t.@Matches())
wl("")

wl("Only BoldTag matches -- count = ", BoldTag.@Matches().Count())
wl("-------------------------------")
wl(BoldTag.@Matches())
wl("")

wl("Only H3Tag matches -- count = ", H3Tag.@Matches().Count())
wl("-----------------------------")
wl(H3Tag.@Matches())
```

**Output:**
```
All matches -- count = 5
----------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
<p>My paragraph</p>

Only BoldTag matches -- count = 2
-------------------------------
<b>Bold statement</b>
<b>Other text</b>

Only H3Tag matches -- count = 2
-----------------------------
<h3>Title</h3>
<h3>Title B</h3>
```

---

### Example ID: 113

**Description:** Using IndexOf() in Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");
//     ^             ^                    ^               ^                ^
//     012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50        60        70        80
// Carrets (^) point to Start locations of the matches

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

wl("IndexOf   StartPos   Match")
wl("")

wl("All Matches")
wl("-----------")
foreach(var match in t.@Matches()) 
   wl(t.@Matches().IndexOf(match.@StartPosition()), "         ", match.@StartPosition(), "          ", match.@Text())
end for
wl("")

wl("Bold Matches")
wl("------------")
foreach(var BoldMatch in BoldTag.@Matches()) 
   wl(t.@Matches().IndexOf(BoldMatch.@StartPosition()), "         ", BoldMatch.@StartPosition(), "          ", BoldMatch.@Text())
end for
wl("")

wl("H3 Matches")
wl("----------")
foreach(var H3Match in H3Tag.@Matches()) 
   wl(t.@Matches().IndexOf(H3Match.@StartPosition()), "         ", H3Match.@StartPosition(), "          ", H3Match.@Text())
end for
wl("")

wl("Other Matches")
wl("-------------")
foreach(var AnyOtherMatch in AnyOtherTag.@Matches()) 
   wl(t.@Matches().IndexOf(AnyOtherMatch.@StartPosition()), "         ", AnyOtherMatch.@StartPosition(), "          ", AnyOtherMatch.@Text())
end for
```

**Output:**
```
IndexOf   StartPos   Match

All Matches
-----------
0         0          <h3>Title</h3>
1         14          <b>Bold statement</b>
2         35          <h3>Title B</h3>
3         51          <b>Other text</b>
4         68          <p>My paragraph</p>

Bold Matches
------------
1         14          <b>Bold statement</b>
3         51          <b>Other text</b>

H3 Matches
----------
0         0          <h3>Title</h3>
2         35          <h3>Title B</h3>

Other Matches
-------------
4         68          <p>My paragraph</p>
```

---

---

## GlobalMaximum = [int] - ID: 267
/doc/reference/classes/ucalc.rule/globalmaximum-=-[int]/

**Description:** Gets or sets the maximum number of matches a rule can find before invalidating the entire transformation pass.

**Remarks:**

The `GlobalMaximum` property defines a validation threshold for a [Rule](/Reference/uCalcBase/Rule). If the number of matches found by this specific rule exceeds the `GlobalMaximum` value, the entire [Transformer](/Reference/uCalcBase/Transformer) operation (e.g., [Find](/Reference/uCalcBase/Transformer/Find), [Transform](/Reference/uCalcBase/Transformer/Transform)) is immediately invalidated, and no matches are returned for *any* rule in that pass.

This provides a powerful mechanism for enforcing structural rules, such as ensuring a specific keyword or block appears at most 'N' times in a document.

### `GlobalMaximum` vs. `Maximum`

Understanding the difference between `GlobalMaximum` and the standard [Maximum](/Reference/uCalcBase/Rule/Maximum) property is crucial.

| Property | Scope of Invalidation | Effect when Exceeded |
| :--- | :--- | :--- |
| **[Maximum](/Reference/uCalcBase/Rule/Maximum)** | **Rule-Level** | Only the matches for *this specific rule* are discarded. Other rules are unaffected. |
| **`GlobalMaximum`** | **Transformer-Level** | All matches for **all rules** within the current transformer pass are discarded. The operation returns zero matches. |

By default, `GlobalMaximum` is set to -1 (or the maximum value for an unsigned integer), which signifies no limit.

### Scope and Limitations

The invalidation effect of `GlobalMaximum` is limited to the local [Transformer](/Reference/uCalcBase/Transformer) instance or pass it is defined in. It does not propagate to parent transformers or subsequent passes.

### 💡 Why uCalc? (Comparative Analysis)

Most regex-based systems do not have a built-in mechanism to fail a search based on the *count* of matches. A developer would typically need to perform a search, get all matches, and then write separate application logic to check if the count exceeds a threshold.

```cs
// Manual, multi-step approach without uCalc
var matches = MyRegex.Matches(text);
if (matches.Count > 2) {
  // Handle the error, discard all results
} else {
  // Process the valid matches
}
```

uCalc's `GlobalMaximum` property is declarative and more efficient. It integrates this validation directly into the parsing engine. The engine can often fail fast, stopping the search as soon as the limit is exceeded, rather than needing to find all possible matches first. This makes it a superior tool for building parsers with strict grammar and occurrence rules.

**Examples:**

### Example ID: 879

**Description:** Demonstrates how `GlobalMaximum` invalidates a search if a rule matches too many times.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var rule = t.FromTo("ERROR", "[ERR]");
rule.@GlobalMaximum(2);

// This input has 3 matches, which exceeds the maximum of 2.
var(string, input1) = "ERROR 1, ERROR 2, ERROR 3";
t.Transform(input1);
wl("Input 1 Match Count: ", t.@Matches().Count()) // Expect 0

// This input has 2 matches, which is within the limit.
var(string, input2) = "ERROR 1, ERROR 2";
t.Transform(input2);
wl("Input 2 Match Count: ", t.@Matches().Count()) // Expect 2
wl(t)
```

**Output:**
```
Input 1 Match Count: 0
Input 2 Match Count: 2
[ERR] 1, [ERR] 2
```

---

### Example ID: 881

**Description:** Internal Test: Compares the behavior of `Maximum` and `GlobalMaximum` at different thresholds to validate their distinct scopes of invalidation.

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
</Fruits>
[/verbatim];

New(uCalc::Transformer, t)
var fruitsTagRule = t.FromTo("<Fruits>", "List of fruits");
var fruitRule = t.FromTo("CommonName={@string:name}", "- {name}");

wl("--- Using Maximum (Rule-Level) ---")
fruitRule.@Maximum(3); // Rule fails if more than 3 fruits are found.
t.Filter(FruitsXML);
wl("Match count when fruit rule fails: ", t.@Matches().Count()) // The 'fruitsTagRule' still matches.
wl(t.@Matches().@Text())

wl("")
wl("--- Using GlobalMaximum (Transformer-Level) ---")
fruitRule.@Maximum(-1); // Reset local maximum
fruitRule.@GlobalMaximum(3); // Transformer fails if more than 3 fruits are found.
t.Filter(FruitsXML);
wl("Match count when global rule fails: ", t.@Matches().Count()) // All matches are invalidated.
wl(t.@Matches().@Text())
```

**Output:**
```
--- Using Maximum (Rule-Level) ---
Match count when fruit rule fails: 1
List of fruits

--- Using GlobalMaximum (Transformer-Level) ---
Match count when global rule fails: 0

```

---

### Example ID: 127

**Description:** Maximum, GlobalMaximum

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

uc.DefineVariable("x");
var t = uc.NewTransformer();
var FruitsTag = t.FromTo("<Fruits>", "List of fruits");
var Fruit = t.FromTo("CommonName={@string:name}", "{@Eval: x++}. {name}");

uc.Eval("x = 1");
Fruit.@Maximum(10);
t.Filter(FruitsXML);
wl("Maximum = ", Fruit.@Maximum())
wl("Matches count: ", t.@Matches().Count()) // 1 for FruitsTag occurrence 
wl("")
wl(t.@Matches())
wl("")
wl("===============")

uc.Eval("x = 1");
Fruit.@Maximum(20);
t.Filter(FruitsXML);
wl("Maximum = ", Fruit.@Maximum())
wl("Matches count: ", t.@Matches().Count()) // 1 for FruitsTag plus 12 fruits
wl("")
wl(t.@Matches())
wl("")
wl("===============")

uc.Eval("x = 1");
Fruit.@GlobalMaximum(10); // Notice "List of fruits" will not show
t.Filter(FruitsXML);
wl("MaximumAND = ", Fruit.@GlobalMaximum())
wl("Matches count: ", t.@Matches().Count()) // Even FruitsTage won't be counted
wl("")
wl(t.@Matches())
wl("===============")

uc.Eval("x = 1");
Fruit.@GlobalMaximum(20);
t.Filter(FruitsXML);
wl("MaximumAND = ", Fruit.@GlobalMaximum())
wl("Matches count: ", t.@Matches().Count())
wl("")
wl(t.@Matches())

```

**Output:**
```
Maximum = 10
Matches count: 1

List of fruits

===============
Maximum = 20
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon

===============
MaximumAND = 10
Matches count: 0


===============
MaximumAND = 20
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon
```

---

---

## GlobalMinimum = [int] - ID: 273
/doc/reference/classes/ucalc.rule/globalminimum-=-[int]/

**Description:** Gets or sets the minimum number of matches this rule must find for the entire transform operation to be considered valid.

**Remarks:**

# 🛡️ Global Match Threshold: GlobalMinimum

The `GlobalMinimum` property sets a "pass/fail" condition for an entire [Transformer](/Reference/uCalcBase/Transformer/Constructor) operation. If this rule does not find at least the specified minimum number of matches, the *entire* transform is invalidated, and no matches from *any* rule will be returned.

This is a powerful feature for validating document structure, ensuring that a file contains a required number of key elements before it is processed further.

---

## `GlobalMinimum` vs. `Minimum`

It is crucial to understand the difference in scope between these two properties.

| Property | Scope of Failure | Behavior | Use Case |
| :--- | :--- | :--- | :--- |
| `rule.@Minimum(n)` | **Rule-specific** | If this rule finds fewer than `n` matches, only the matches *for this rule* are discarded. Other rules are unaffected. | When a specific pattern is optional but, if present, must appear a certain number of times. |
| `rule.@GlobalMinimum(n)` | **Transformer-wide** | If this rule finds fewer than `n` matches, the entire `Find`, `Filter`, or `Transform` operation fails, returning zero matches for **all** rules. | When the presence of a certain number of `n` matches from this rule is a mandatory validation check for the entire document. |

---

## ⚠️ Performance Considerations

To enable this "all or nothing" behavior, the [Transformer](/Reference/uCalcBase/Transformer/Constructor) must store a backup of the original string. If the `GlobalMinimum` is not met, the engine discards the results and reverts to this backup. This consumes more memory than a standard transformation.

---

## 💡 Why uCalc? (Comparative Analysis)

In a standard Regex-based workflow, achieving this would require multiple steps:
1.  Run the regex search to get all matches.
2.  Count the number of matches found.
3.  Write an `if` statement in your host language (C#, C++, etc.) to check if the count meets your minimum.
4.  If it doesn't, manually discard all results.

uCalc's `GlobalMinimum` is **declarative**. You state your requirement directly on the rule, and the engine handles the validation logic internally. This leads to cleaner, more expressive, and less error-prone code by keeping the validation logic tightly coupled with the pattern it applies to.

**Examples:**

### Example ID: 882

**Description:** Demonstrates the pass/fail behavior of GlobalMinimum. If the rule doesn't find at least 3 'a's, the entire transform fails.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var ruleA = t.FromTo("a", "A");
var ruleB = t.FromTo("b", "B");
ruleA.@GlobalMinimum(3);

// Case 1: Fails (only 2 'a's)
wl("--- Case 1: Fails ---")
t.@Text("a b a b");
t.Transform();
wl("Matches Found: ", t.@Matches().Count()) // Should be 0
wl("Result: ", t)

// Case 2: Succeeds (3 'a's)
wl("")
wl("--- Case 2: Succeeds ---")
t.@Text("a b a b a");
t.Transform();
wl("Matches Found: ", t.@Matches().Count()) // Should be 5 (3 'A's and 2 'B's)
wl("Result: ", t)
```

**Output:**
```
--- Case 1: Fails ---
Matches Found: 0
Result: a b a b

--- Case 2: Succeeds ---
Matches Found: 5
Result: A B A B A
```

---

### Example ID: 143

**Description:** Minimum, GlobalMinimum

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

uc.DefineVariable("x = 1");
var t = uc.NewTransformer();
var FruitsTag = t.FromTo("<Fruits>", "List of fruits");
var Fruit = t.FromTo("CommonName={@string:name}", "{@Eval: x++}. {name}");

Fruit.@Minimum(20);
t.Filter(FruitsXML);
wl("Minimum = ", Fruit.@Minimum())
wl("Matches count: ", t.@Matches().Count()) // 1 for FruitsTag occurrence 
wl("")
wl(t.@Matches())
wl("")
wl("===============")

uc.Eval("x = 1");
Fruit.@Minimum(10);
t.Filter(FruitsXML);
wl("Minimum = ", Fruit.@Minimum())
wl("Matches count: ", t.@Matches().Count()) // 1 for FruitsTag plus 12 fruits
wl("")
wl(t.@Matches())
wl("")
wl("===============")

uc.Eval("x = 1");
Fruit.@GlobalMinimum(20); // Notice "List of fruits" will not show
t.Filter(FruitsXML);
wl("MinimumAND = ", Fruit.@GlobalMinimum())
wl("Matches count: ", t.@Matches().Count()) // Even FruitsTage won't be counted
wl("")
wl(t.@Matches())
wl("===============")

uc.Eval("x = 1");
Fruit.@GlobalMinimum(10);
t.Filter(FruitsXML);
wl("MinimumAND = ", Fruit.@GlobalMinimum())
wl("Matches count: ", t.@Matches().Count())
wl("")
wl(t.@Matches())

```

**Output:**
```
Minimum = 20
Matches count: 1

List of fruits

===============
Minimum = 10
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon

===============
MinimumAND = 20
Matches count: 0


===============
MinimumAND = 10
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon
```

---

---

## Handle - ID: 248
/doc/reference/classes/ucalc.rule/handle/

**Description:** Returns the handle of an object

**Syntax:** Handle()
**Return:** Rule - 
**Remarks:**

Mostly for internal use.

Each object has a handle, which is used to communicate with the uCalc library.  It may not have other uses cases beyond troubleshooting.

---

## HasLocalTransformer = [bool] - ID: 249
/doc/reference/classes/ucalc.rule/haslocaltransformer-=-[bool]/

**Description:** Checks if a rule has an associated local transformer without creating one if it doesn't exist.

**Remarks:**

# 🧐 A Non-Destructive Check: HasLocalTransformer

The `HasLocalTransformer` property is a read-only check to determine if a [Rule](/Reference/uCalcBase/Rule/Constructor) has an associated [local transformer](/Reference/uCalcBase/Rule/LocalTransformer) without the side effect of creating one.

### The Critical Distinction: `HasLocalTransformer` vs. `LocalTransformer`

This property's primary purpose is to provide a safe way to query the state of a rule, which is crucial for performance and predictable behavior. Understanding the difference between these two methods is essential:

*   **`HasLocalTransformer` (This Property)**: This is a **query**. It simply returns `true` or `false`. It does **not** allocate memory or change the state of the rule.

*   **[`LocalTransformer()`](/Reference/uCalcBase/Rule/LocalTransformer)**: This is a **get-or-create** operation. If a local transformer already exists, it returns it. If one does not exist, it **creates a new one on the fly**. This has a performance cost and modifies the rule object.

Therefore, you should always use `HasLocalTransformer` when you only need to check for the existence of nested logic, as it avoids the unnecessary overhead of creating a new `Transformer` instance.

### 💡 Why uCalc? (Comparative Analysis)

This design pattern, separating a 'has' check from a 'get-or-create' method, is a best practice in API design that promotes clarity and avoids hidden side effects. It is similar to patterns seen in other frameworks:

*   **vs. C# `Dictionary.TryGetValue`**: In C#, calling `myDict[key]` will throw an exception if the key doesn't exist. The `TryGetValue` pattern provides a safe way to check for and retrieve a value without exceptions. Similarly, `HasLocalTransformer` allows you to check for a local transformer without the side effect of creating one.

By providing both `HasLocalTransformer` and `LocalTransformer`, uCalc gives developers explicit control. You can safely inspect a rule's structure without accidentally altering it, which is crucial for building robust and performant introspection tools or debuggers.

**Examples:**

### Example ID: 126

**Description:** LocalTransformer, HasLocalTransformer, IsChildRule

**Code:**
```pseudocode
// Note the change in section/div/h2
var t = uc.NewTransformer();

var rule = t.Pattern("<section>{body}</section>").SetStatementSensitive(false);
var section = rule.@LocalTransformer();
section.FromTo("<h2>{text}</h2>", "<h1>====> {@Eval: UCase(text)} <====</h1>");
section.SkipOver("&{entity};");
var ch = section.FromTo("<p>{text}</p>", "<p>SELECTED: {text}</p>");

wl("Has a local transformer: ", bool(rule.@HasLocalTransformer()))
wl("rule is a child rule: ", bool(rule.@IsChildRule()))
wl("ch is a child rule: ", bool(ch.@IsChildRule()))

var HtmlText = 
[verbatim]
<div class="article" data-id="1">
  <h2>Article One</h2>
  <p>This is the first article.</p>
</div>

<div class="article" data-id="2">
  <h2>Article Two</h2>
  <p>This is the second article.</p>
</div>

<section>
  <div class="article" data-id="3">
    <h2>Article Three</h2>
    <p>This one is inside a &lt;section&gt;.</p>
  </div>
</section>

<div class="article" data-id="4">
  <h2>Article Four</h2>
  <p>This is the fourth article.</p>
</div>
[/verbatim];

t.@Text(HtmlText);
t.Transform();
wl(t.@Text())


```

**Output:**
```
Has a local transformer: True
rule is a child rule: False
ch is a child rule: True

<div class="article" data-id="1">
  <h2>Article One</h2>
  <p>This is the first article.</p>
</div>

<div class="article" data-id="2">
  <h2>Article Two</h2>
  <p>This is the second article.</p>
</div>

<section>
  <div class="article" data-id="3">
    <h1>====> ARTICLE THREE <====</h1>
    <p>SELECTED: This one is inside a &lt;section&gt;.</p>
  </div>
</section>

<div class="article" data-id="4">
  <h2>Article Four</h2>
  <p>This is the fourth article.</p>
</div>
```

---

---

## IsChildRule = [bool] - ID: 256
/doc/reference/classes/ucalc.rule/ischildrule-=-[bool]/

**Description:** Determines if a rule belongs to a nested (local) transformer rather than the main (root) transformer.

**Remarks:**

## 🌳 Understanding Rule Hierarchy

The `IsChildRule` property is a boolean flag that indicates whether a rule is part of a nested parsing context. It returns `true` if the rule was defined on a 'local' transformer—one obtained from another rule's [`LocalTransformer`](/Reference/uCalcBase/Rule/LocalTransformer) property. This is a key introspection tool for understanding the scope and hierarchy of your transformation logic.

*   **Parent Rule (Root)**: A rule defined directly on a main [`Transformer`](/Reference/uCalcBase/Transformer/Constructor) object. For these rules, `IsChildRule` returns `false`.
*   **Child Rule (Local)**: A rule defined on the `Transformer` object returned by another rule's `@LocalTransformer()` property. For these rules, `IsChildRule` returns `true`.

This property allows you to distinguish between top-level patterns and sub-patterns that only execute within the scope of a specific parent match. This is crucial for debugging complex, nested parsing logic or for writing generic functions that behave differently based on a rule's scope.

## 💡 Why uCalc? (Comparative Analysis)

*   **vs. Regular Expressions**: Standard regex engines have a 'flat' model; there is no concept of a rule hierarchy. Achieving nested parsing requires complex and often fragile recursive patterns or lookarounds. uCalc's `LocalTransformer` creates a true hierarchical parsing model, and `IsChildRule` is the built-in tool to inspect this structure. It provides a level of architectural clarity that is absent in traditional regex.

*   **vs. Parser Generators (ANTLR, etc.)**: While parser generators define grammars with clear hierarchical rules (e.g., a `statement` contains an `expression`), this hierarchy is static and defined in a grammar file. uCalc's model is entirely dynamic and programmatic. You can build and query these parent-child relationships at runtime, and `IsChildRule` is the primary way to do so.

**Examples:**

### Example ID: 937

**Description:** Basic distinction between a root rule and a child rule.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var rootRule = t.Pattern("root");
var localTransformer = rootRule.@LocalTransformer();
var childRule = localTransformer.Pattern("child");

wl("Is 'rootRule' a child? ", bool(rootRule.@IsChildRule()))
wl("Is 'childRule' a child? ", bool(childRule.@IsChildRule()))
```

**Output:**
```
Is 'rootRule' a child? False
Is 'childRule' a child? True
```

---

### Example ID: 938

**Description:** Internal Test: Verifies that any rule not on the root transformer is considered a child, regardless of nesting depth.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var grandParentRule = t.Pattern("grandparent");

// Create a child
var parentTransformer = grandParentRule.@LocalTransformer();
var parentRule = parentTransformer.Pattern("parent");

// Create a grandchild
var childTransformer = parentRule.@LocalTransformer();
var childRule = childTransformer.Pattern("child");

wl("Grandparent is child: ", bool(grandParentRule.@IsChildRule()))
wl("Parent is child: ", bool(parentRule.@IsChildRule()))
wl("Child (grandchild) is child: ", bool(childRule.@IsChildRule()))
```

**Output:**
```
Grandparent is child: False
Parent is child: True
Child (grandchild) is child: True
```

---

### Example ID: 126

**Description:** LocalTransformer, HasLocalTransformer, IsChildRule

**Code:**
```pseudocode
// Note the change in section/div/h2
var t = uc.NewTransformer();

var rule = t.Pattern("<section>{body}</section>").SetStatementSensitive(false);
var section = rule.@LocalTransformer();
section.FromTo("<h2>{text}</h2>", "<h1>====> {@Eval: UCase(text)} <====</h1>");
section.SkipOver("&{entity};");
var ch = section.FromTo("<p>{text}</p>", "<p>SELECTED: {text}</p>");

wl("Has a local transformer: ", bool(rule.@HasLocalTransformer()))
wl("rule is a child rule: ", bool(rule.@IsChildRule()))
wl("ch is a child rule: ", bool(ch.@IsChildRule()))

var HtmlText = 
[verbatim]
<div class="article" data-id="1">
  <h2>Article One</h2>
  <p>This is the first article.</p>
</div>

<div class="article" data-id="2">
  <h2>Article Two</h2>
  <p>This is the second article.</p>
</div>

<section>
  <div class="article" data-id="3">
    <h2>Article Three</h2>
    <p>This one is inside a &lt;section&gt;.</p>
  </div>
</section>

<div class="article" data-id="4">
  <h2>Article Four</h2>
  <p>This is the fourth article.</p>
</div>
[/verbatim];

t.@Text(HtmlText);
t.Transform();
wl(t.@Text())


```

**Output:**
```
Has a local transformer: True
rule is a child rule: False
ch is a child rule: True

<div class="article" data-id="1">
  <h2>Article One</h2>
  <p>This is the first article.</p>
</div>

<div class="article" data-id="2">
  <h2>Article Two</h2>
  <p>This is the second article.</p>
</div>

<section>
  <div class="article" data-id="3">
    <h1>====> ARTICLE THREE <====</h1>
    <p>SELECTED: This one is inside a &lt;section&gt;.</p>
  </div>
</section>

<div class="article" data-id="4">
  <h2>Article Four</h2>
  <p>This is the fourth article.</p>
</div>
```

---

---

## LocalTransformer = [Transformer] - ID: 260
/doc/reference/classes/ucalc.rule/localtransformer-=-[transformer]/

**Description:** Gets a nested Transformer instance scoped exclusively to the text matched by this rule, enabling hierarchical parsing.

**Remarks:**

# 🎯 Nested Parsing with LocalTransformer

The `LocalTransformer` property provides access to a powerful nested parsing engine. It returns a new [Transformer](/Reference/uCalcBase/Transformer/Constructor) instance whose scope is limited exclusively to the text segment matched by the parent [Rule](/Reference/uCalcBase/Rule/Constructor). This allows you to "zoom in" on a match and perform a second, independent set of find or transform operations on just that content.

This creates a hierarchical or multi-pass parsing model, which is essential for structured data formats like HTML, XML, or nested configuration files.

## ⚙️ Key Behaviors

### Scope Isolation
A local transformer operates in a sandbox. It sees only the text captured by its parent rule's pattern and is completely unaware of the surrounding document.

### Settings Inheritance
For convenience, a local transformer automatically inherits the settings of its parent, including:
*   The full set of [token](/Reference/Patterns/Introduction/Tokens) definitions.
*   Default rule properties like [StatementSensitive](/Reference/uCalcBase/Rule/StatementSensitive), [CaseSensitive](/Reference/uCalcBase/Rule/CaseSensitive), etc.

This means you don't have to reconfigure the entire parsing environment for each nested level. For example, if you set `.StatementSensitive(false)` on the parent, the local transformer will also treat newlines as whitespace.

### Nested Match Results
Matches found by a local transformer are considered "child" matches. The [Matches](/Reference/uCalcBase/Matches/Constructor) collection stores this hierarchy, allowing you to filter the results view using members of the [MatchesOption](/Reference/Enums/MatchesOption) enum:
*   **`MatchesOption::All`**: Shows all matches, both parent and child.
*   **`MatchesOption::RootLevelOnly`**: Shows only the top-level matches from the parent transformer.
*   **`MatchesOption::InnermostOnly`**: Shows only the final, most deeply nested matches.

To check if a rule is part of a local transformer, you can use the [IsChildRule](/Reference/uCalcBase/Rule/IsChildRule) property.

## 💡 Why uCalc? (Comparative Analysis)

### vs. Regular Expressions
Traditional regex has no built-in concept of hierarchical parsing. To achieve a similar result, you would need to:
1.  Write a regex to find and capture the outer content block.
2.  Extract the captured string into a new variable in your application code.
3.  Write and execute a *second* regex against that new string.
4.  Manually stitch the results together, keeping track of original offsets if needed.

This multi-step, imperative process is verbose and error-prone.

uCalc's `LocalTransformer` integrates this entire workflow into a single, declarative model. You define the parent-child relationship between rules, and the engine handles the substring extraction, nested searching, and result hierarchy automatically. This leads to code that is significantly cleaner, more robust, and easier to maintain.

**Examples:**

### Example ID: 939

**Description:** A simple example showing how to extract a value from a nested configuration block.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("Config { setting = 123; }");

// 1. Define the parent rule to capture the content inside the braces.
var parentRule = t.Pattern("Config '{' {body} '}'").SetStatementSensitive(false);

// 2. Get the local transformer for the parent rule.
var local_t = parentRule.@LocalTransformer();

// 3. Define a rule that operates ONLY on the text captured by '{body}'.
local_t.FromTo("setting = {val}", "Found Value: {val}");

// 4. Perform the transformation.
// The local rule will run on the text " setting = 123; ".
t.Transform();

wl(t.@Text())
```

**Output:**
```
Config { Found Value: 123; }
```

---

### Example ID: 940

**Description:** A practical example of parsing a specific HTML section and applying transformations only to the elements within it.

**Code:**
```pseudocode
// Note the change in section/div/h2
var t = uc.NewTransformer();

// The parent rule will find the <section> block and make its content available to a local transformer.
// StatementSensitive(false) is needed so the multiline content is captured.
var parentRule = t.Pattern("<section>{body}</section>");
parentRule.@StatementSensitive(false);

// Get the local transformer for the <section> block.
var section_t = parentRule.@LocalTransformer();

// These rules will ONLY run on the content inside the <section> tag.
section_t.FromTo("<h2>{text}</h2>", "<h1>====> {@Eval: UCase(text)} <====</h1>");
section_t.FromTo("<p>{text}</p>", "<p>SELECTED: {text}</p>");

var sourceHtml = 
[verbatim]
<div>
  <h2>Article One</h2>
  <p>This is NOT in the section.</p>
</div>

<section>
  <div>
    <h2>Article Two</h2>
    <p>This one IS inside the section.</p>
  </div>
</section>
[/verbatim];

t.@Text(sourceHtml);
t.Transform();
wl(t.@Text())
```

**Output:**
```
<div>
  <h2>Article One</h2>
  <p>This is NOT in the section.</p>
</div>

<section>
  <div>
    <h1>====> ARTICLE TWO <====</h1>
    <p>SELECTED: This one IS inside the section.</p>
  </div>
</section>
```

---

### Example ID: 941

**Description:** Internal Test: Verifies the filtering of nested matches using RootLevelOnly and InnermostOnly options.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "<p id='aa'>xyz</p><p id='bb'>Hello</p ><p id='cc'>World</p>";
t.@Text(txt);

// Parent rule matches the <p> tag. Its local transformer then extracts the 'id' attribute.
var parentRule = t.Pattern("<p {etc}>");
parentRule.@LocalTransformer().FromTo("id={@string:id}", "{id}");
t.Filter();

wl("--- All Matches (Parent and Child) ---")
wl(t.GetMatches(MatchesOption::All).@Text())
wl("")

wl("--- RootLevelOnly (Parent Matches) ---")
wl(t.GetMatches(MatchesOption::RootLevelOnly).@Text())
wl("")

wl("--- InnermostOnly (Child Matches) ---")
wl(t.GetMatches(MatchesOption::InnermostOnly).@Text())
```

**Output:**
```
--- All Matches (Parent and Child) ---
<p aa>
aa
<p bb>
bb
<p cc>
cc

--- RootLevelOnly (Parent Matches) ---
<p aa>
<p bb>
<p cc>

--- InnermostOnly (Child Matches) ---
aa
bb
cc
```

---

### Example ID: 126

**Description:** LocalTransformer, HasLocalTransformer, IsChildRule

**Code:**
```pseudocode
// Note the change in section/div/h2
var t = uc.NewTransformer();

var rule = t.Pattern("<section>{body}</section>").SetStatementSensitive(false);
var section = rule.@LocalTransformer();
section.FromTo("<h2>{text}</h2>", "<h1>====> {@Eval: UCase(text)} <====</h1>");
section.SkipOver("&{entity};");
var ch = section.FromTo("<p>{text}</p>", "<p>SELECTED: {text}</p>");

wl("Has a local transformer: ", bool(rule.@HasLocalTransformer()))
wl("rule is a child rule: ", bool(rule.@IsChildRule()))
wl("ch is a child rule: ", bool(ch.@IsChildRule()))

var HtmlText = 
[verbatim]
<div class="article" data-id="1">
  <h2>Article One</h2>
  <p>This is the first article.</p>
</div>

<div class="article" data-id="2">
  <h2>Article Two</h2>
  <p>This is the second article.</p>
</div>

<section>
  <div class="article" data-id="3">
    <h2>Article Three</h2>
    <p>This one is inside a &lt;section&gt;.</p>
  </div>
</section>

<div class="article" data-id="4">
  <h2>Article Four</h2>
  <p>This is the fourth article.</p>
</div>
[/verbatim];

t.@Text(HtmlText);
t.Transform();
wl(t.@Text())


```

**Output:**
```
Has a local transformer: True
rule is a child rule: False
ch is a child rule: True

<div class="article" data-id="1">
  <h2>Article One</h2>
  <p>This is the first article.</p>
</div>

<div class="article" data-id="2">
  <h2>Article Two</h2>
  <p>This is the second article.</p>
</div>

<section>
  <div class="article" data-id="3">
    <h1>====> ARTICLE THREE <====</h1>
    <p>SELECTED: This one is inside a &lt;section&gt;.</p>
  </div>
</section>

<div class="article" data-id="4">
  <h2>Article Four</h2>
  <p>This is the fourth article.</p>
</div>
```

---

### Example ID: 148

**Description:** MatchesOption: RootLevelOnly and InnermostOnly

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "<p id='aa'>xyz</p><p id='bb'>Hello</p ><p id='cc'>World</p>";
t.Str(txt);

t.Pattern("<p {etc}>").@LocalTransformer().FromTo("id={@string:id}", "{id}");
t.Filter();


wl("All matches")
wl("-----------")
wl(t.GetMatches(MatchesOption::All).@Text()) // All is the default
wl("")

wl("RootLevelOnly")
wl("-------------")
wl(t.GetMatches(MatchesOption::RootLevelOnly).@Text())
wl("")

wl("InnermostOnly")
wl("-------------")
wl(t.GetMatches(MatchesOption::InnermostOnly).@Text())
wl("")
```

**Output:**
```
All matches
-----------
<p aa>
aa
<p bb>
bb
<p cc>
cc

RootLevelOnly
-------------
<p aa>
<p bb>
<p cc>

InnermostOnly
-------------
aa
bb
cc
```

---

---

## Matches = [Matches] - ID: 862
/doc/reference/classes/ucalc.rule/matches-=-[matches]/

**Description:** Retrieves the collection of matches found exclusively by this rule, allowing for a filtered view of a transformation's results.

**Remarks:**

# 🎯 Rule.Matches Property

Retrieves the collection of matches generated exclusively by this specific `Rule`, providing a more granular view than the global [Transformer.Matches](/Reference/uCalcBase/Transformer/Matches) property.

This property is your primary tool for inspecting the results of a single pattern. While [pseudocode]`myTransformer.@Matches()` returns a collection of all matches found by *all* active rules, [pseudocode]`myRule.@Matches()` returns only the subset of those matches that were found by `myRule`.

---
## 💡 Why uCalc? (Comparative Analysis)

In other environments, such as using LINQ in C#, you would typically get a single large list of all results and then filter it manually.

**Typical C# LINQ Approach:**
```csharp
// Get all matches and then filter by rule reference
var ruleSpecificMatches = allMatches.Where(m => m.Rule == mySpecificRule).ToList();
```

While functional, this approach performs the filtering in the host application after retrieving all the data. uCalc's design is more efficient:

*   **Engine-Side Filtering**: By passing the `options` and calling the property on a specific `Rule`, the filtering logic is executed inside the highly optimized uCalc engine.
*   **Direct Access**: It provides a more direct and declarative way to ask, "Show me just the results for this pattern," leading to cleaner and more readable code.

**Examples:**

### Example ID: 112

**Description:** Filters matches by rule; FilterByRule, Matches.Str, Matches.Count

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

wl("All matches -- count = ", t.@Matches().Count())
wl("----------------------")
wl(t.@Matches())
wl("")

wl("Only BoldTag matches -- count = ", BoldTag.@Matches().Count())
wl("-------------------------------")
wl(BoldTag.@Matches())
wl("")

wl("Only H3Tag matches -- count = ", H3Tag.@Matches().Count())
wl("-----------------------------")
wl(H3Tag.@Matches())
```

**Output:**
```
All matches -- count = 5
----------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
<p>My paragraph</p>

Only BoldTag matches -- count = 2
-------------------------------
<b>Bold statement</b>
<b>Other text</b>

Only H3Tag matches -- count = 2
-----------------------------
<h3>Title</h3>
<h3>Title B</h3>
```

---

### Example ID: 113

**Description:** Using IndexOf() in Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");
//     ^             ^                    ^               ^                ^
//     012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50        60        70        80
// Carrets (^) point to Start locations of the matches

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

wl("IndexOf   StartPos   Match")
wl("")

wl("All Matches")
wl("-----------")
foreach(var match in t.@Matches()) 
   wl(t.@Matches().IndexOf(match.@StartPosition()), "         ", match.@StartPosition(), "          ", match.@Text())
end for
wl("")

wl("Bold Matches")
wl("------------")
foreach(var BoldMatch in BoldTag.@Matches()) 
   wl(t.@Matches().IndexOf(BoldMatch.@StartPosition()), "         ", BoldMatch.@StartPosition(), "          ", BoldMatch.@Text())
end for
wl("")

wl("H3 Matches")
wl("----------")
foreach(var H3Match in H3Tag.@Matches()) 
   wl(t.@Matches().IndexOf(H3Match.@StartPosition()), "         ", H3Match.@StartPosition(), "          ", H3Match.@Text())
end for
wl("")

wl("Other Matches")
wl("-------------")
foreach(var AnyOtherMatch in AnyOtherTag.@Matches()) 
   wl(t.@Matches().IndexOf(AnyOtherMatch.@StartPosition()), "         ", AnyOtherMatch.@StartPosition(), "          ", AnyOtherMatch.@Text())
end for
```

**Output:**
```
IndexOf   StartPos   Match

All Matches
-----------
0         0          <h3>Title</h3>
1         14          <b>Bold statement</b>
2         35          <h3>Title B</h3>
3         51          <b>Other text</b>
4         68          <p>My paragraph</p>

Bold Matches
------------
1         14          <b>Bold statement</b>
3         51          <b>Other text</b>

H3 Matches
----------
0         0          <h3>Title</h3>
2         35          <h3>Title B</h3>

Other Matches
-------------
4         68          <p>My paragraph</p>
```

---

### Example ID: 148

**Description:** MatchesOption: RootLevelOnly and InnermostOnly

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "<p id='aa'>xyz</p><p id='bb'>Hello</p ><p id='cc'>World</p>";
t.Str(txt);

t.Pattern("<p {etc}>").@LocalTransformer().FromTo("id={@string:id}", "{id}");
t.Filter();


wl("All matches")
wl("-----------")
wl(t.GetMatches(MatchesOption::All).@Text()) // All is the default
wl("")

wl("RootLevelOnly")
wl("-------------")
wl(t.GetMatches(MatchesOption::RootLevelOnly).@Text())
wl("")

wl("InnermostOnly")
wl("-------------")
wl(t.GetMatches(MatchesOption::InnermostOnly).@Text())
wl("")
```

**Output:**
```
All matches
-----------
<p aa>
aa
<p bb>
bb
<p cc>
cc

RootLevelOnly
-------------
<p aa>
<p bb>
<p cc>

InnermostOnly
-------------
aa
bb
cc
```

---

---

## Maximum = [int] - ID: 264
/doc/reference/classes/ucalc.rule/maximum-=-[int]/

**Description:** Gets or sets the maximum number of matches a rule is allowed to find; if exceeded, this rule's own matches are invalidated.

**Remarks:**

# 🎯 Rule-Level Match Limit: Maximum

The `Maximum` property sets a validation threshold for an individual [Rule](/Reference/uCalcBase/Rule/Constructor). If the number of matches found by this specific rule exceeds the `Maximum` value, the operation continues, but all matches found by *this rule* are invalidated and discarded from the final results. This provides a powerful way to enforce structural constraints on a per-pattern basis.

By default, `Maximum` is set to -1 (or the maximum value for an unsigned integer), which signifies no limit.

### `Maximum` vs. `GlobalMaximum` vs. `StopAfter`

Choosing the correct property to limit matches is crucial. This table clarifies their distinct behaviors:

| Property                                                      | Effect when Limit is Exceeded                                        | Use Case                                                                              |
| :------------------------------------------------------------ | :------------------------------------------------------------------- | :------------------------------------------------------------------------------------ |
| **`@Maximum(n)`** (This Property)                             | Only matches from **this rule** are invalidated. Other rules are unaffected. | When a pattern should be ignored entirely if it appears too many times.               |
| **[`@GlobalMaximum(n)`](/Reference/uCalcBase/Rule/GlobalMaximum)** | **All matches** from **all rules** are invalidated. The operation fails. | When a pattern's count is a critical validation check for the entire document.       |
| **[`@StopAfter(n)`](/Reference/uCalcBase/Rule/StopAfter)**         | Matching for this rule stops after `n` matches. The first `n` matches are kept. | When you only care about the first few occurrences of a pattern and want to stop early. |

### ⚠️ Performance Note

To enable this "all or nothing" behavior for a rule, the [Transformer](/Reference/uCalcBase/Transformer/Constructor) must store a backup of the original string. If the `Maximum` count is exceeded, the engine discards the results, deactivates the rule, and re-scans the text from the backup. This consumes more memory and time than a standard transformation. For simple match limiting without invalidation, [`@StopAfter`](/Reference/uCalcBase/Rule/StopAfter) is more performant.

### 💡 Why uCalc? (Comparative Analysis)

In a standard regex workflow, you would have to perform these steps manually:

1.  Run the regex search to get all matches for a pattern.
2.  Get the count of the matches.
3.  Write an `if` statement in your application code to check if the count exceeds a threshold.
4.  If it does, manually filter those matches out of your final result set.

uCalc's `@Maximum` property is **declarative**. You state the constraint directly on the rule, and the engine handles the validation and invalidation logic internally. This leads to cleaner, more expressive code by keeping the validation logic tightly coupled with the pattern it applies to.

**Examples:**

### Example ID: 945

**Description:** A basic demonstration of how the Maximum threshold invalidates a rule's matches.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var ruleA = t.FromTo("a", "A");

// Case 1: Limit is 2, but 3 'a's are present. The rule is invalidated.
t.Transform("a b a c a");
ruleA.@Maximum(2);
wl("--- Maximum = 2 (Rule Fails) ---")
w("Result: ")
wl(t.Transform("a b a c a"))

// Case 2: Limit is 3. The rule passes and matches are kept.
ruleA.@Maximum(3);
wl("")
wl("--- Maximum = 3 (Rule Succeeds) ---")
w("Result: ")
wl(t.Transform("a b a c a"))
```

**Output:**
```
--- Maximum = 2 (Rule Fails) ---
Result: a b a c a

--- Maximum = 3 (Rule Succeeds) ---
Result: A b A c A
```

---

### Example ID: 946

**Description:** Practical: Validating log file entries. If more than 2 'WARNING' entries exist, they are ignored, but 'ERROR' entries are still processed.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var log = "WARNING: low disk. ERROR: service down. WARNING: high CPU. WARNING: queue full.";

var warningRule = t.FromTo("WARNING: {msg}.", "[WARN] {msg}.");
var errorRule = t.FromTo("ERROR: {msg}.", "[ERR] {msg}.");

// Set a rule-specific limit for warnings.
warningRule.@Maximum(2);

t.Filter(log);
wl(t.@Matches().@Text())
```

**Output:**
```
[ERR] service down.
```

---

### Example ID: 947

**Description:** Internal Test: Compares the behavior of Maximum (rule-level) and GlobalMaximum (transformer-level) invalidation.

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' />
  <Fruit CommonName='Banana' />
  <Fruit CommonName='Orange' />
  <Fruit CommonName='Grapes' />
</Fruits>
[/verbatim];

New(uCalc::Transformer, t)
var fruitsTagRule = t.FromTo("<Fruits>", "List of fruits");
var fruitRule = t.FromTo("CommonName={@string:name}", "- {name}");

wl("--- Using Maximum (Rule-Level Invalidation) ---")
// The fruitRule will fail because there are 4 fruits, exceeding the max of 3.
fruitRule.@Maximum(3);
t.Filter(FruitsXML);
wl("Match count: ", t.@Matches().Count()) // The 'fruitsTagRule' still matches and is counted.
wl(t.@Matches().@Text())

wl("")
wl("--- Using GlobalMaximum (Transformer-Level Invalidation) ---")
fruitRule.@Maximum(-1); // Reset local maximum to default (unlimited).
fruitRule.@GlobalMaximum(3); // The entire transformer will fail if more than 3 fruits are found.
t.Filter(FruitsXML);
wl("Match count: ", t.@Matches().Count()) // All matches (including fruitsTagRule) are invalidated.
wl(t.@Matches().@Text())
```

**Output:**
```
--- Using Maximum (Rule-Level Invalidation) ---
Match count: 1
List of fruits

--- Using GlobalMaximum (Transformer-Level Invalidation) ---
Match count: 0

```

---

### Example ID: 127

**Description:** Maximum, GlobalMaximum

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

uc.DefineVariable("x");
var t = uc.NewTransformer();
var FruitsTag = t.FromTo("<Fruits>", "List of fruits");
var Fruit = t.FromTo("CommonName={@string:name}", "{@Eval: x++}. {name}");

uc.Eval("x = 1");
Fruit.@Maximum(10);
t.Filter(FruitsXML);
wl("Maximum = ", Fruit.@Maximum())
wl("Matches count: ", t.@Matches().Count()) // 1 for FruitsTag occurrence 
wl("")
wl(t.@Matches())
wl("")
wl("===============")

uc.Eval("x = 1");
Fruit.@Maximum(20);
t.Filter(FruitsXML);
wl("Maximum = ", Fruit.@Maximum())
wl("Matches count: ", t.@Matches().Count()) // 1 for FruitsTag plus 12 fruits
wl("")
wl(t.@Matches())
wl("")
wl("===============")

uc.Eval("x = 1");
Fruit.@GlobalMaximum(10); // Notice "List of fruits" will not show
t.Filter(FruitsXML);
wl("MaximumAND = ", Fruit.@GlobalMaximum())
wl("Matches count: ", t.@Matches().Count()) // Even FruitsTage won't be counted
wl("")
wl(t.@Matches())
wl("===============")

uc.Eval("x = 1");
Fruit.@GlobalMaximum(20);
t.Filter(FruitsXML);
wl("MaximumAND = ", Fruit.@GlobalMaximum())
wl("Matches count: ", t.@Matches().Count())
wl("")
wl(t.@Matches())

```

**Output:**
```
Maximum = 10
Matches count: 1

List of fruits

===============
Maximum = 20
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon

===============
MaximumAND = 10
Matches count: 0


===============
MaximumAND = 20
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon
```

---

---

## MemoryIndex = [int] - ID: 609
/doc/reference/classes/ucalc.rule/memoryindex-=-[int]/

**Description:** Returns the unique index value associated with the object

**Remarks:**

Mostly for internal use.

Each object has an integer index value that is unique to the object within the class.  Unlike the [topic: Handle] value that may change each time you run uCalc, the MemoryIndex value is predictable.

This function may not have other uses cases beyond troubleshooting.

---

## Minimum = [int] - ID: 270
/doc/reference/classes/ucalc.rule/minimum-=-[int]/

**Description:** Gets or sets the minimum number of matches a rule must find for its results to be considered valid.

**Remarks:**

# 🛡️ Rule-Level Match Threshold: Minimum

The `@Minimum` property sets a "pass/fail" condition for an individual [Rule](/Reference/uCalcBase/Rule/Constructor). If the rule does not find at least the specified minimum number of matches, its results are **invalidated and discarded**. This does not affect the results of any other rules.

This property is a powerful tool for enforcing structural validation, ensuring that a pattern appears a certain number of times before its matches are considered part of the final result set.

---

## `Minimum` vs. `GlobalMinimum`

It is crucial to understand the difference in scope between these two validation properties.

| Property | Scope of Failure | Behavior | Use Case |
| :--- | :--- | :--- | :--- |
| `rule.@Minimum(n)` (This Property) | **Rule-specific** | If this rule finds fewer than `n` matches, only the matches *for this rule* are discarded. Other rules are unaffected. | When a specific pattern is optional, but if present, must appear at least `n` times to be valid. |
| `rule.@GlobalMinimum(n)` | **Transformer-wide** | If this rule finds fewer than `n` matches, the entire `Find`, `Filter`, or `Transform` operation fails, returning **zero matches for all rules**. | When the presence of at least `n` matches from this rule is a mandatory validation check for the entire document. |

---

## ⚠️ Performance Considerations

To enable this validation, the [Transformer](/Reference/uCalcBase/Transformer/Constructor) may need to store a backup of the original string. If the `@Minimum` is not met, the engine discards the rule's results and may re-scan the text with the rule deactivated. This can consume more memory and time than a standard transformation.

---

## 💡 Why uCalc? (Comparative Analysis)

In a standard Regex-based workflow, achieving this would require multiple steps in your application code:

1.  Run the regex search to get all matches for a specific pattern.
2.  Count the number of matches found.
3.  Write an `if` statement in your host language (C#, C++, etc.) to check if the count meets your minimum.
4.  If it doesn't, manually discard the results for that pattern.

uCalc's `@Minimum` property is **declarative**. You state your requirement directly on the rule, and the engine handles the validation logic internally. This leads to cleaner, more expressive, and less error-prone code by keeping the validation logic tightly coupled with the pattern it applies to.

**Default value:** 0

**Examples:**

### Example ID: 948

**Description:** How a rule fails if it doesn't meet the minimum match count.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var ruleA = t.FromTo("a", "A");
ruleA.@Minimum(3);

wl("--- Case 1: Fails (only 2 'a's) ---")
t.Transform("a b a b c");
wl("Result: ", t)
wl("Matches Found: ", t.@Matches().Count())

wl("")
wl("--- Case 2: Succeeds (3 'a's) ---")
t.Transform("a b a b a c");
wl("Result: ", t)
wl("Matches Found: ", t.@Matches().Count())
```

**Output:**
```
--- Case 1: Fails (only 2 'a's) ---
Result: a b a b c
Matches Found: 0

--- Case 2: Succeeds (3 'a's) ---
Result: A b A b A c
Matches Found: 3
```

---

### Example ID: 949

**Description:** A practical example where a 'data' rule is invalidated if it appears too few times, while a 'header' rule is unaffected.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var document = [verbatim]
Header: Section 1
Data: A
Data: B
Header: Section 2
Data: C
[/verbatim];
t.@Text(document);

var dataRule = t.Pattern("Data: {val}");
var headerRule = t.Pattern("Header: {val}");

dataRule.@Minimum(2);
wl("--- Find with Minimum(2) ---")
t.Find();
wl("Total Matches: ", t.@Matches().Count())
wl("Data Matches: ", dataRule.@Matches().Count())
wl("Header Matches: ", headerRule.@Matches().Count())

dataRule.@Minimum(4);
wl("")
wl("--- Find with Minimum(4) ---")
t.Find();
wl("Total Matches: ", t.@Matches().Count())
wl("Data Matches: ", dataRule.@Matches().Count())
wl("Header Matches: ", headerRule.@Matches().Count())
```

**Output:**
```
--- Find with Minimum(2) ---
Total Matches: 5
Data Matches: 3
Header Matches: 2

--- Find with Minimum(4) ---
Total Matches: 2
Data Matches: 0
Header Matches: 2
```

---

### Example ID: 950

**Description:** Internal Test: Clearly contrasts the rule-level invalidation of `Minimum` with the transformer-level invalidation of `GlobalMinimum`.

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' />
  <Fruit CommonName='Banana' />
  <Fruit CommonName='Orange' />
</Fruits>
[/verbatim];

New(uCalc::Transformer, t)
t.@Text(FruitsXML);
var fruitsTagRule = t.Pattern("<Fruits>");
var fruitRule = t.Pattern("CommonName={@string:name}");

wl("--- Using Minimum (Rule-Level Invalidation) ---")
fruitRule.@Minimum(4); // Rule fails if fewer than 4 fruits are found.
t.Find();
wl("Match count when fruit rule fails: ", t.@Matches().Count())
wl("Matches found:")
foreach(var m in t.@Matches())
    wl("  ", m.@Text())
end foreach;

wl("")
wl("--- Using GlobalMinimum (Transformer-Level Invalidation) ---")
fruitRule.@Minimum(0); // Reset local minimum
fruitRule.@GlobalMinimum(4); // Transformer fails if fewer than 4 fruits are found.
t.Find();
wl("Match count when global rule fails: ", t.@Matches().Count())
wl("Matches found:")
foreach(var m in t.@Matches())
    wl("  ", m.@Text())
end foreach;
```

**Output:**
```
--- Using Minimum (Rule-Level Invalidation) ---
Match count when fruit rule fails: 1
Matches found:
  <Fruits>

--- Using GlobalMinimum (Transformer-Level Invalidation) ---
Match count when global rule fails: 0
Matches found:
```

---

### Example ID: 143

**Description:** Minimum, GlobalMinimum

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

uc.DefineVariable("x = 1");
var t = uc.NewTransformer();
var FruitsTag = t.FromTo("<Fruits>", "List of fruits");
var Fruit = t.FromTo("CommonName={@string:name}", "{@Eval: x++}. {name}");

Fruit.@Minimum(20);
t.Filter(FruitsXML);
wl("Minimum = ", Fruit.@Minimum())
wl("Matches count: ", t.@Matches().Count()) // 1 for FruitsTag occurrence 
wl("")
wl(t.@Matches())
wl("")
wl("===============")

uc.Eval("x = 1");
Fruit.@Minimum(10);
t.Filter(FruitsXML);
wl("Minimum = ", Fruit.@Minimum())
wl("Matches count: ", t.@Matches().Count()) // 1 for FruitsTag plus 12 fruits
wl("")
wl(t.@Matches())
wl("")
wl("===============")

uc.Eval("x = 1");
Fruit.@GlobalMinimum(20); // Notice "List of fruits" will not show
t.Filter(FruitsXML);
wl("MinimumAND = ", Fruit.@GlobalMinimum())
wl("Matches count: ", t.@Matches().Count()) // Even FruitsTage won't be counted
wl("")
wl(t.@Matches())
wl("===============")

uc.Eval("x = 1");
Fruit.@GlobalMinimum(10);
t.Filter(FruitsXML);
wl("MinimumAND = ", Fruit.@GlobalMinimum())
wl("Matches count: ", t.@Matches().Count())
wl("")
wl(t.@Matches())

```

**Output:**
```
Minimum = 20
Matches count: 1

List of fruits

===============
Minimum = 10
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon

===============
MinimumAND = 20
Matches count: 0


===============
MinimumAND = 10
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon
```

---

---

## Name = [string] - ID: 531
/doc/reference/classes/ucalc.rule/name-=-[string]/

**Description:** Gets the programmatic name of a rule, which is automatically derived from the first non-variable token in its pattern definition.

**Remarks:**

### 🎯 The Rule's Identifier: Name

The `Name` property provides runtime access to the programmatic name of a [Rule](/Reference/uCalcBase/Rule/Constructor). This identifier is not set manually; instead, it is automatically derived from the structure of the pattern string used to define the rule.

### ⚙️ How the Name is Derived

The name is determined by the first token in the pattern that is **not** a variable or a special directive. This makes the name a predictable and meaningful representation of the rule's primary anchor.

*   For a pattern like `"Hello {name}"`, the name will be `"hello"`.
*   For `"<{tag}>;{content}</{tag}>"`, the name will be `"<"`.
*   For `"{@Number}: {value}"`, the name will be `":"`.

**Case Normalization**: By default, the derived name is converted to **lowercase**. This ensures that lookups and comparisons are case-insensitive, providing consistent and predictable behavior regardless of the casing used in the original pattern definition.

### 💡 Primary Use Cases

*   **Debugging & Introspection**: When iterating through a `Transformer`'s collection of rules or a list of [Matches](/Reference/uCalcBase/Matches/Constructor), you can retrieve a rule's name to log or display which pattern was responsible for a specific action.
*   **Dynamic Rule Management**: Retrieve a specific rule by its derived name from the `Transformer`'s rule collection to modify or inspect it programmatically.

### 🆚 Comparative Analysis

This feature provides a unique advantage over traditional Regex engines.

*   **vs. Regex Named Capture Groups**: In Regex, you must explicitly name parts of your pattern (e.g., `(?<myGroup>...)`). uCalc's `Rule.Name` is different; it's an automatically generated identifier for the **rule itself**, derived from its structure. This provides a zero-effort way to get a meaningful handle for every pattern you define, simplifying debugging and introspection.


**Examples:**

### Example ID: 951

**Description:** A simple demonstration of how a rule's name is derived from the first token in its pattern.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

var rule1 = t.FromTo("Hello {name}", "Hi {name}");
var rule2 = t.Pattern("<h1>{title}</h1>");

wl("Rule 1 Name: '", rule1.@Name(), "'")
wl("Rule 2 Name: '", rule2.@Name(), "'")
```

**Output:**
```
Rule 1 Name: 'hello'
Rule 2 Name: '<'
```

---

### Example ID: 952

**Description:** A practical example showing how to iterate through all matches and print the name of the rule that generated each one for debugging.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("Log: INFO, Data: 123, Log: WARN");

// Define two rules with different starting anchors
t.Pattern("Log: {@Alpha}");
t.Pattern("Data: {@Number}");
t.Find();

wl("--- Match Analysis ---")
foreach (var match in t.@Matches())
    wl("Match '", match.@Text(), "' was found by rule '", match.@Rule().@Name(), "'")
end foreach
```

**Output:**
```
--- Match Analysis ---
Match 'Log: INFO' was found by rule 'log'
Match 'Data: 123' was found by rule 'data'
Match 'Log: WARN' was found by rule 'log'
```

---

### Example ID: 130

**Description:** Rule Name

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<b>(5+4)</b> this and that etc");
var a = t.Pattern("<{tg}>");
var b = t.Pattern("This {body} That");
var c = t.Pattern("etc");
var d = t.Pattern("({expr})");

t.Filter();
wl("--- Matches ---")
wl(t.@Matches().@Text())
wl("--- Pattern names ---")
wl(a.@Name())
wl(b.@Name())
wl(c.@Name())
wl(d.@Name())
wl("--- Pattern defs ---")
wl(a.@Pattern())
wl(b.@Pattern())
wl(c.@Pattern())
wl(d.@Pattern())
```

**Output:**
```
--- Matches ---
<b>
(5+4)
</b>
this and that
etc
--- Pattern names ---
<
this
etc
(
--- Pattern defs ---
<{tg}>
This {body} That
etc
({expr})
```

---

---

## NextOverload - ID: 532
/doc/reference/classes/ucalc.rule/nextoverload/

**Description:** Retrieves the next rule in a sequence of rules that share the same starting pattern anchor, allowing for traversal of the overload chain.

**Syntax:** NextOverload()
**Return:** Rule - Returns the next `Rule` object in the overload chain. If there are no more overloads, it returns an empty `Rule` for which `NotEmpty()` is false.
**Remarks:**

# 🚶‍♂️ Traversing Rule Precedence with NextOverload

The `NextOverload` method provides a way to traverse the chain of [Rules](/Reference/uCalcBase/Rule/Constructor) that share the same starting anchor text. When multiple rules are defined with patterns that could match at the same position, they form an implicit, stack-like list based on their definition order. This method acts as an iterator to walk through that list.

### ⚙️ Core Concept: The Overload Chain (LIFO)

Think of rules with the same anchor as a linked list where the head is the most recently defined rule:

1.  **Head of the List**: Retrieving a rule (e.g., from [FromTo()](/Reference/uCalcBase/Transformer/FromTo)) gives you the most recently defined rule for that pattern—the head of the chain.
2.  **Walking the Chain**: Calling `.NextOverload()` on that rule returns the previously defined rule that shares the same starting anchor.
3.  **End of the Chain**: When no more rules with that name exist, `NextOverload()` returns an empty [Rule](/Reference/uCalcBase/Rule/Constructor) object. You can check for this termination condition using [NotEmpty()](/Reference/uCalcBase/Item/IsProperty) or `IsProperty(ItemIs::NotFound)`.

This mechanism is essential for introspection and for understanding the precedence of transformation rules.

### 🎯 Primary Use Cases

*   **Inspecting `FromTo` Rule Precedence**: The most common use case is to programmatically discover all defined rules that compete for the same starting text and verify their order of application. The LIFO (Last-In, First-Out) order means the rule returned by `NextOverload` has a *lower* priority than the one it was called on.
*   **Debugging Complex Transformations**: When a transformation isn't behaving as expected, you can use this method to walk the chain of rules associated with a problematic anchor to see which one is being applied and which ones are being overshadowed.

### 💡 Why uCalc? (Comparative Analysis)

This feature provides a significant advantage over traditional regular expression engines.

*   **vs. Regex Alternation (`|`)**: In regex, precedence is determined by the left-to-right order within an alternation group (e.g., `(cat|catch)`). This is static and cannot be inspected or modified at runtime. uCalc's model is dynamic; rules can be added at any time, and `NextOverload` provides a programmatic way to inspect the resulting precedence chain.

*   **vs. Function Overloading**: In compiled languages like C# or C++, function overloading is a **compile-time** concept. The compiler selects the correct method, and there is no built-in mechanism to programmatically iterate through all available overloads at **runtime**. `NextOverload` gives uCalc powerful runtime introspection capabilities, a feature more common in highly dynamic languages.

**Examples:**

### Example ID: 954

**Description:** Demonstrates the basic LIFO (Last-In, First-Out) behavior of NextOverload with two simple rules.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("This is a test.");

// Rule 1 (defined first, lower priority)
var rule1 = t.FromTo("is", "[IS_1]");

// Rule 2 (defined second, higher priority)
var rule2 = t.FromTo("is", "[IS_2]");

wl("--- Applying transform (Rule 2 has precedence) ---")
wl(t.Transform())
wl("")

wl("--- Using NextOverload ---")
// Get the rule that comes after rule2
var nextRule = rule2.NextOverload();

wl("Rule 2 pattern: ", rule2.@Pattern())
wl("Next rule's pattern: ", nextRule.@Pattern())

// Verify that the next rule is indeed rule1
wl("Next rule is rule1: ", bool(nextRule.Handle() == rule1.Handle()))
```

**Output:**
```
--- Applying transform (Rule 2 has precedence) ---
This [IS_2] a test.

--- Using NextOverload ---
Rule 2 pattern: is
Next rule's pattern: is
Next rule is rule1: True
```

---

### Example ID: 955

**Description:** Iterates through a chain of rules with the same anchor to inspect their different replacement patterns.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// Define multiple rules with the same anchor ("Log:")
t.FromTo("Log: {msg}", "DEFAULT: {msg}");
t.FromTo("Log: ERROR {msg}", "CRITICAL: {msg}");
var lastRule = t.FromTo("Log: INFO {msg}", "INFO: {msg}"); // This has the highest priority

wl("--- Overload Chain for 'Log:' anchor ---")
var currentRule = lastRule;
do
   wl("Pattern: '", currentRule.@Pattern(), "' -> Replacement: '", currentRule.@Replacement(), "'")
   currentRule = currentRule.NextOverload();
loop while (currentRule.NotEmpty())
```

**Output:**
```
--- Overload Chain for 'Log:' anchor ---
Pattern: 'Log: INFO {msg}' -> Replacement: 'INFO: {msg}'
Pattern: 'Log: ERROR {msg}' -> Replacement: 'CRITICAL: {msg}'
Pattern: 'Log: {msg}' -> Replacement: 'DEFAULT: {msg}'
```

---

### Example ID: 956

**Description:** Internal Test: Verifies precedence and traversal of rules with different patterns but the same starting anchor ('Testing').

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("Testing (a b c) Testing x y z! Testing 1 2 3.");

var Pattern1 = t.Pattern("Testing {etc}.").SetTag(111);
var Pattern2 = t.Pattern("Testing {etc}!").SetTag(222);
var Pattern3 = t.Pattern("Testing ({etc})").SetTag(333);

t.Find();
wl("--- Matches ---")
wl(t.@Matches().@Text())
wl("--- Patterns ---")
wl(Pattern1.@Pattern())
wl(Pattern2.@Pattern())
wl(Pattern3.@Pattern())
wl("---- Tags ----")
wl(Pattern1.@Tag())
wl(Pattern2.@Tag())
wl(Pattern3.@Tag())
wl("-- Overload Tags --")
// Note that most recently defined patterns come first
wl(Pattern3.NextOverload().@Tag())
wl(Pattern2.NextOverload().@Tag())
wl(Pattern1.NextOverload().@Tag())
```

**Output:**
```
--- Matches ---
Testing (a b c)
Testing x y z!
Testing 1 2 3.
--- Patterns ---
Testing {etc}.
Testing {etc}!
Testing ({etc})
---- Tags ----
111
222
333
-- Overload Tags --
222
111
0
```

---

### Example ID: 131

**Description:** Rule NextOverload and Tag

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("Testing (a b c) Testing x y z! Testing 1 2 3.");

var Pattern1 = t.Pattern("Testing {etc}.").SetTag(111);
var Pattern2 = t.Pattern("Testing {etc}!").SetTag(222);
var Pattern3 = t.Pattern("Testing ({etc})").SetTag(333);

t.Find();
wl("--- Matches ---")
wl(t.@Matches().@Text())
wl("--- Patterns ---")
wl(Pattern1.@Pattern())
wl(Pattern2.@Pattern())
wl(Pattern3.@Pattern())
wl("---- Tags ----")
wl(Pattern1.@Tag())
wl(Pattern2.@Tag())
wl(Pattern3.@Tag())
wl("-- Overload Tags --")
// Note that most recently defined patterns come first
wl(Pattern3.NextOverload().@Tag())
wl(Pattern2.NextOverload().@Tag())
wl(Pattern1.NextOverload().@Tag())


```

**Output:**
```
--- Matches ---
Testing (a b c)
Testing x y z!
Testing 1 2 3.
--- Patterns ---
Testing {etc}.
Testing {etc}!
Testing ({etc})
---- Tags ----
111
222
333
-- Overload Tags --
222
111
0
```

---

---

## Owned - ID: 743
/doc/reference/classes/ucalc.rule/owned/

**Description:** Marks a Rule object for automatic memory release when it goes out of scope, enabling RAII-style lifetime management in C++.

**Syntax:** Owned()
**Return:** Rule - Returns the current Rule instance to allow for method chaining.
**Remarks:**

## 🛡️ Object Ownership and Automatic Release

The `Owned()` method is a crucial memory management tool, primarily for C++, that flags a uCalc object for automatic release when its corresponding variable goes out of scope. This aligns with the C++ RAII (Resource Acquisition Is Initialization) paradigm, preventing memory leaks by ensuring resources are cleaned up deterministically.

This method returns the current [Rule](/Reference/uCalcBase/Rule/Constructor) instance, enabling a fluent, chainable syntax.

## ⚙️ How It Works

By default, creating a uCalc object (like an [Item](/Reference/uCalcBase/Item/Constructor), [Expression](/Reference/uCalcBase/Expression/Constructor), or [Rule](/Reference/uCalcBase/Rule/Constructor)) allocates resources that persist until you explicitly call [Release()](/Reference/uCalcBase/Rule/Release). This is true even if the variable holding the object goes out of scope.

Calling `Owned()` on an object changes this behavior. The uCalc engine marks the object as "owned" by its current scope. When the scope is exited, the object's destructor is called, which in turn automatically calls [Release()](/Reference/uCalcBase/Rule/Release).

## Platform-Specific Usage: `Owned()` vs. `using`

The need for `Owned()` is specific to C++'s memory model. Other languages achieve the same result with different syntax:

*   **C++**: Use `Owned()` on a stack-allocated object or in conjunction with smart pointers.
    ```pseudocode
    [cpp]
    {
       // The rule 'r' is created on the stack
       uCalc::Rule r = t.FromTo("a", "b");
       r.Owned(); 
       // r will be released automatically at the end of this scope
    }
    [/cpp]
    ```

*   **C# / VB.NET**: Use the `using` statement (which relies on the `IDisposable` interface).
    ```pseudocode
    [cs]
    // The 'using' statement ensures myRule.Release() is called automatically.
    using (var myRule = t.FromTo("a", "b"))
    {
        // ... use myRule here ...
    } // myRule is released here.
    [/cs]
    ```

## ⚖️ Comparative Analysis

### `Owned()` vs. Standard C++ RAII
In native C++, you would typically wrap a raw pointer in a smart pointer like `std::unique_ptr` or `std::shared_ptr` to manage its lifetime. uCalc's `Owned()` method provides a similar, built-in mechanism that is simpler and more direct for uCalc objects. It avoids the need for boilerplate smart pointer declarations.

### `Owned()` vs. C# `IDisposable`
The concept is identical. `Owned()` is uCalc's C++-idiomatic way of achieving what `IDisposable` and `using` do in .NET. It provides developers with a consistent cross-platform mental model for resource management, even if the syntax differs.

**Best Practice**: In C++, always call `Owned()` on stack-allocated uCalc objects or objects whose lifetime is tied to a specific scope to prevent resource leaks. For heap-allocated objects that need to persist beyond their initial scope, manual [Release()](/Reference/uCalcBase/Rule/Release) is still required.

**Examples:**

---

## ParentTransformer = [Transformer] - ID: 275
/doc/reference/classes/ucalc.rule/parenttransformer-=-[transformer]/

**Description:** Retrieves the parent Transformer instance that owns this rule, providing a navigational link back to the rule's execution context.

**Remarks:**

# 🧭 Navigating the Hierarchy: ParentTransformer

Every [Rule](/Reference/uCalcBase/Rule/Constructor) object exists within the context of a parent [Transformer](/Reference/uCalcBase/Transformer/Constructor) that owns it. The `ParentTransformer` property provides the crucial link back to this owner, allowing you to navigate "up" the object hierarchy from a specific rule to its container.

This is essential for introspection and for writing context-aware transformation logic, especially when dealing with nested transformers.

## 🎯 Primary Use Cases

1.  **Contextual Introspection**: When you retrieve a `Rule` from a [Match](/Reference/uCalcBase/Matches/Match/Constructor) object, you can use `ParentTransformer` to access the state of the `Transformer` that found the match. This allows you to read its [Description](/Reference/uCalcBase/Transformer/Description), check its other rules, or inspect its token set.

2.  **Distinguishing Local vs. Global Context**: When using a [LocalTransformer](/Reference/uCalcBase/Rule/LocalTransformer) for nested parsing, this property is the primary way to determine which level of the hierarchy a rule belongs to. A rule inside a `LocalTransformer` will have that `LocalTransformer` as its parent, not the main, top-level `Transformer`.

## 💡 Why uCalc? (Comparative Analysis)

This parent-child relationship is a common design pattern for creating navigable object trees.

*   **vs. DOM (Document Object Model)**: The relationship between a `Rule` and its `ParentTransformer` is analogous to an HTML element and its `parentElement` in the DOM. It provides a structured, predictable way to traverse the hierarchy of your parsing logic. Just as you might walk up the DOM tree from a specific `<div>` to find its container, you can walk up from a `Rule` to its owning `Transformer`.

*   **vs. Ad-Hoc Rule Management**: Without this built-in link, you would need to manually track which `Transformer` owns which `Rule`, likely using external dictionaries or wrapper classes. This is complex and error-prone. By making `ParentTransformer` a first-class property, uCalc provides a clean, reliable, and integrated solution for managing the relationship between rules and their execution context.

**Examples:**

### Example ID: 960

**Description:** Verifies the direct parent-child relationship between a Transformer and its Rule.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var myRule = t.FromTo("A", "B");

// Get the parent from the rule
var parent = myRule.@ParentTransformer();

// Check if the parent is the original transformer using its unique memory index
wl(bool(parent.@MemoryIndex() == t.@MemoryIndex()))
```

**Output:**
```
True
```

---

### Example ID: 961

**Description:** Iterates through matches, retrieves the rule for each, and uses ParentTransformer to get the transformer's description for context.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Description("My Main Transformer");
t.@Text("apple banana apple");

var appleRule = t.FromTo("apple", "APPLE");
var bananaRule = t.FromTo("banana", "BANANA");

t.Find();

foreach(var match in t.@Matches())
    var rule = match.@Rule();
    var parent = rule.@ParentTransformer();
    wl("Match '", match.@Text(), "' found by rule '", rule.@Name(), "' in transformer '", parent.@Description(), "'")
end foreach
```

**Output:**
```
Match 'apple' found by rule 'apple' in transformer 'My Main Transformer'
Match 'banana' found by rule 'banana' in transformer 'My Main Transformer'
Match 'apple' found by rule 'apple' in transformer 'My Main Transformer'
```

---

### Example ID: 962

**Description:** Internal Test: Verifies that the correct parent is returned when using a nested LocalTransformer, confirming hierarchical integrity.

**Code:**
```pseudocode
New(uCalc::Transformer, main_t)
main_t.@Description("Main Transformer");

// Create an outer rule in the main transformer
var outerRule = main_t.Pattern("OUTER({body})");

// Get a local transformer for the outer rule
var local_t = outerRule.@LocalTransformer();
local_t.@Description("Local Transformer");

// Create an inner rule inside the local transformer
var innerRule = local_t.FromTo("INNER", "inner_match");

// Verify the parent of the outer rule is the main transformer
wl("Outer rule's parent: ", outerRule.@ParentTransformer().@Description())

// Verify the parent of the inner rule is the local transformer
wl("Inner rule's parent: ", innerRule.@ParentTransformer().@Description())
```

**Output:**
```
Outer rule's parent: Main Transformer
Inner rule's parent: Local Transformer
```

---

### Example ID: 132

**Description:** ParentTransformer

**Code:**
```pseudocode
var Txt = "Test a b c. x y z";

var FirstTransform = uc.NewTransformer().SetText(Txt).SetDescription("First Transformer");
var aaa = FirstTransform.FromTo("Test {etc}.", "[{etc}]");

var SecondTransform = uc.NewTransformer().SetDescription("Second Transformer");
var bbb = SecondTransform.FromTo("Test {etc}.", "({etc})");

wl(aaa.@ParentTransformer().@Description())
wl(FirstTransform.Transform().@Text())
wl("")

wl(SecondTransform.@Description())
wl(bbb.@ParentTransformer().Transform(Txt).@Text())
```

**Output:**
```
First Transformer
[a b c] x y z

Second Transformer
(a b c) x y z
```

---

---

## Pattern = [string] - ID: 245
/doc/reference/classes/ucalc.rule/pattern-=-[string]/

**Description:** Retrieves or sets the pattern string that defines a rule's matching criteria.

**Remarks:**

The `Pattern` property provides runtime access to the "source code" of a [Rule's](/Reference/uCalcBase/Rule/Constructor) pattern definition. This allows for powerful introspection into the logic of a [Transformer](/Reference/uCalcBase/Transformer/Constructor) at runtime.

This property applies to rules created with both the [Pattern()](/Reference/uCalcBase/Transformer/Pattern) and [FromTo()](/Reference/uCalcBase/Transformer/FromTo) methods, returning the pattern string from either.

### ⚙️ Getter and Setter Behavior

*   **Getter**: When called without arguments, `myRule.@Pattern()` retrieves the original string that defines the rule's matching logic.
*   **Setter**: When called with a string argument, `myRule.@Pattern("new pattern")` is intended to modify the rule's pattern at runtime. **Note**: This functionality is not yet fully implemented and may not have any effect.

### 🎯 Core Use Cases

*   **Debugging**: When iterating through a collection of [Matches](/Reference/uCalcBase/Matches/Constructor), you can retrieve the `Rule` for each [Match](/Reference/uCalcBase/Matches/Match/Constructor) and then use this property to log the exact pattern that generated it. This is invaluable for understanding why a particular piece of text was matched.
*   **Dynamic UI and Tooling**: Build IDE-like features, such as a property inspector that can display the pattern for a selected rule.
*   **Metaprogramming**: Analyze the structure of one rule's pattern to dynamically generate or modify another.

### 💡 Comparative Analysis

In compiled languages like C# or C++, reflection can provide metadata about a method—such as its name and parameters—but it cannot retrieve the original source code. `Rule.Pattern` is fundamentally different because the uCalc engine retains the complete definition string.

This capability bridges the gap between a compiled, executable rule and its human-readable source, making uCalc an exceptionally powerful tool for dynamic and interactive applications.

**Examples:**

### Example ID: 963

**Description:** How to retrieve the pattern string from a defined rule.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var rule = t.FromTo("Hello {name}", "Greetings, {name}!");

wl("Rule pattern is: '", rule.@Pattern(), "'")
```

**Output:**
```
Rule pattern is: 'Hello {name}'
```

---

### Example ID: 964

**Description:** A practical debugging example that identifies which pattern string generated each match.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("An apple and a car.");

// Define two separate rules
t.FromTo("apple", "[FRUIT]");
t.FromTo("car", "[VEHICLE]");

t.Find();

var matches = t.@Matches();
wl("Found ", matches.Count(), " matches:")
foreach(var match in matches)
    var rule = match.@Rule();
    wl("- Matched '", match.@Text(), "' using pattern: '", rule.@Pattern(), "'")
end foreach
```

**Output:**
```
Found 2 matches:
- Matched 'apple' using pattern: 'apple'
- Matched 'car' using pattern: 'car'
```

---

### Example ID: 965

**Description:** Internal Test: Verifies that the correct pattern string is returned for rules created with both FromTo() and Pattern(), including complex syntax.

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Rule created with FromTo
var rule1 = t.FromTo("Key: {@Number:val}", "{val}");

// Rule created with Pattern
var rule2 = t.Pattern("<{tag}>{content}</{tag}>");

wl("Rule 1 Pattern: ", rule1.@Pattern())
wl("Rule 2 Pattern: ", rule2.@Pattern())
```

**Output:**
```
Rule 1 Pattern: Key: {@Number:val}
Rule 2 Pattern: <{tag}>{content}</{tag}>
```

---

### Example ID: 130

**Description:** Rule Name

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<b>(5+4)</b> this and that etc");
var a = t.Pattern("<{tg}>");
var b = t.Pattern("This {body} That");
var c = t.Pattern("etc");
var d = t.Pattern("({expr})");

t.Filter();
wl("--- Matches ---")
wl(t.@Matches().@Text())
wl("--- Pattern names ---")
wl(a.@Name())
wl(b.@Name())
wl(c.@Name())
wl(d.@Name())
wl("--- Pattern defs ---")
wl(a.@Pattern())
wl(b.@Pattern())
wl(c.@Pattern())
wl(d.@Pattern())
```

**Output:**
```
--- Matches ---
<b>
(5+4)
</b>
this and that
etc
--- Pattern names ---
<
this
etc
(
--- Pattern defs ---
<{tg}>
This {body} That
etc
({expr})
```

---

### Example ID: 131

**Description:** Rule NextOverload and Tag

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("Testing (a b c) Testing x y z! Testing 1 2 3.");

var Pattern1 = t.Pattern("Testing {etc}.").SetTag(111);
var Pattern2 = t.Pattern("Testing {etc}!").SetTag(222);
var Pattern3 = t.Pattern("Testing ({etc})").SetTag(333);

t.Find();
wl("--- Matches ---")
wl(t.@Matches().@Text())
wl("--- Patterns ---")
wl(Pattern1.@Pattern())
wl(Pattern2.@Pattern())
wl(Pattern3.@Pattern())
wl("---- Tags ----")
wl(Pattern1.@Tag())
wl(Pattern2.@Tag())
wl(Pattern3.@Tag())
wl("-- Overload Tags --")
// Note that most recently defined patterns come first
wl(Pattern3.NextOverload().@Tag())
wl(Pattern2.NextOverload().@Tag())
wl(Pattern1.NextOverload().@Tag())


```

**Output:**
```
--- Matches ---
Testing (a b c)
Testing x y z!
Testing 1 2 3.
--- Patterns ---
Testing {etc}.
Testing {etc}!
Testing ({etc})
---- Tags ----
111
222
333
-- Overload Tags --
222
111
0
```

---

---

## Precedence = [int] - ID: 277
/doc/reference/classes/ucalc.rule/precedence-=-[int]/

**Description:** Returns the precedence level for a rule

**Remarks:**

Returns the precedence level for a rule.

setter
 [Revisit]
                                 Patterns that start (and/or end) with a pattern variable instead of a token or identifier can (and probably should) be assigned a precedence level.  You can choose any arbitrary numerical value.  The meaning of the precedence level depends on whether the value is greater, equal, or less than adjacent patterns with a precedence level.  It works similarly to precedence levels for operators.  For instance, if you define:

                                 FromTo("{a} + {b}", "({a} + {b})").Precedence(10); FromTo("{a} * {b}", "({a} * {b})").Precedence(20);

                                 Then

                                 "1 + 2 * 3 + 4" transforms into "(1 + (2 * 3) + 4)" "1 * 2 + 3 * 4" transforms into "(1 * 2) + (3 * 4)"
                              

**Examples:**

---

## QuoteSensitive = [bool] - ID: 281
/doc/reference/classes/ucalc.rule/quotesensitive-=-[bool]/

**Description:** Controls whether a pattern rule respects quoted strings as atomic units, preventing matches from occurring inside them.

**Remarks:**

# 🛡️ Structural Integrity: The QuoteSensitive Property

The `QuoteSensitive` property controls whether a pattern is aware of quoted strings, treating them as atomic, unbreakable units. When enabled (the default), it prevents a pattern from matching text that is inside a string literal, ensuring that transformations do not accidentally corrupt user data.

This is a fundamental feature for safely parsing structured text and a key advantage over traditional regular expressions, which are not context-aware.

## ⚙️ How It Works

This property acts as a switch for an individual rule's parsing logic, overriding the global setting inherited from the [Transformer's](/Reference/uCalcBase/Transformer/DefaultRuleSet) `DefaultRuleSet`.

| Setting | Behavior |
| :--- | :--- |
| `true` (Default) | **Structurally Aware**. The tokenizer identifies a quoted string (e.g., `"Hello World"`) as a single, atomic `Literal` token. The pattern matching engine will not look "inside" this token, preventing partial matches. |
| `false` | **Structurally Unaware**. Quote characters (`'` and `"`) are treated like any other generic punctuation. The pattern matching engine will scan the text, allowing matches to occur inside string literals. |

By default, uCalc recognizes single (`'`) and double (`"`) quotes. You can define your own custom quote tokens using [uCalc.Tokens.Add](/Reference/uCalcBase/Tokens/Add).

While the default `true` behavior is a powerful safety feature, you must disable it when your pattern needs to capture a block of text that can contain its own quotes. This is common when defining custom delimited blocks, such as a `[code]...[/code]` tag, where the content between the tags must be captured literally, regardless of any quote characters it contains. The practical example below demonstrates this scenario.

## 💡 Why uCalc? (Comparative Analysis)

Matching around, but not inside, quoted strings is notoriously difficult with regular expressions. It requires complex negative lookbehind/lookahead assertions that are hard to write, read, and debug.

**A Typical Regex Problem:**
Imagine you want to replace the variable `x` with `y` in the code `var x = "The value of x is 10";`. A simple regex `\bx\b` would incorrectly change both, resulting in `var y = "The value of y is 10";`.

uCalc's `QuoteSensitive` property solves this elegantly and by default:

1.  **Tokenizer Awareness**: The tokenizer runs first and identifies `"The value of x is 10"` as a single, opaque `String` token.
2.  **Safe Matching**: When the [Transformer](/Reference/uCalcBase/Transformer) processes the token stream, a rule looking for the alphanumeric token `x` will match the first one but will skip over the `String` token entirely, leaving its contents untouched.

This "safe by default" behavior makes uCalc far more robust and reliable for code transformation and structured data parsing than pure regex solutions. You only disable `QuoteSensitive` when you explicitly *need* to operate on the content inside strings.

**Examples:**

### Example ID: 970

**Description:** Demonstrates the default `QuoteSensitive(true)` behavior, where a pattern match is ignored inside a string literal.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("fox", "CAT");

// The 'fox' inside the quotes is not replaced.
wl(t.Transform("The quick brown fox jumps over the 'lazy fox'."))
```

**Output:**
```
The quick brown CAT jumps over the 'lazy fox'.
```

---

### Example ID: 971

**Description:** Practical: Creates a custom code block parser. `@QuoteSensitive(false)` is essential to allow the capture of content that contains its own quotes.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var source = [verbatim]Some text... [code]print("Hello, World!") // Quoted with "
var x = 'test';[/code] ...more text.[/verbatim];

// This rule must disable QuoteSensitive and StatementSensitive to correctly
// capture the multi-line block containing single and double quotes.
var rule = t.FromTo("'['code']'{content}'['/code']'", [verbatim]```
{content}
```[/verbatim]);
rule.@QuoteSensitive(false);
rule.@StatementSensitive(false);

wl(t.Transform(source))
```

**Output:**
```
Some text... ```
print("Hello, World!") // Quoted with "
var x = 'test';
``` ...more text.
```

---

### Example ID: 144

**Description:** QuoteSensitive

**Code:**
```pseudocode
var t = uc.NewTransformer().SetText("Test1 'a b c' a b c Test2 'a b c' a b c");

var Test1 = t.FromTo("Test1 {txt} b", "[{txt}]"); // defaults to QuoteSensitive = true
var Test2 = t.FromTo("Test2 {txt} b", "({txt})").SetQuoteSensitive(false);
t.Transform();

wl("Test1 QuoteSensitive = ", bool(Test1.@QuoteSensitive()))
wl("Test2 QuoteSensitive = ", bool(Test2.@QuoteSensitive()))

wl(t)
```

**Output:**
```
Test1 QuoteSensitive = True
Test2 QuoteSensitive = False
['a b c' a] c ('a) c' a b c
```

---

---

## Release - ID: 283
/doc/reference/classes/ucalc.rule/release/

**Description:** Permanently removes a defined Transformer rule, freeing its resources and making it unavailable for future operations.

**Syntax:** Release()
**Return:** void - This method does not return a value.
**Remarks:**

The `Release` method is the primary mechanism for manual memory management of uCalc symbols. When an item such as a [function](/reference/functions_and_operators/functions/math), [variable](/reference/ucalc/definevariable), or [transformer rule](/reference/patterns/rules) is no longer needed, calling `Release()` removes it from the uCalc instance, frees its associated resources, and makes its name available for reuse.

--- 

## 💡 Key Use Cases

While its main purpose is resource management, `Release()` enables several powerful patterns:

*   **Standard Cleanup**: The most common use is to free memory by removing temporary variables, expressions, or rules at the end of a process. This prevents memory leaks in long-running applications.

*   **Un-shadowing Definitions**: uCalc allows multiple definitions for the same name, creating a stack where the newest definition *shadows* older ones. Releasing the newest `Item` pops it from the stack, automatically restoring the previous definition. This is a powerful feature for managing layered configurations or temporary overrides.

*   **Deactivating Rules and Aliases**: Releasing an `Item` that represents a [Transformer](/Reference/uCalcBase/Transformer/Constructor) rule, a `Format` rule, or an [Alias](/reference/ucalc/alias) effectively deactivates that specific behavior without affecting other definitions.

--- 

## 🗑️ Manual vs. Automatic Release

There are two primary ways an `Item`'s resources are reclaimed:

1.  **Manual Release (Explicit)**
    Calling [pseudocode]`myItem.Release()` directly gives you precise control over the lifetime of an object.

2.  **Automatic Release (Implicit)**
    *   **Parent Release**: Releasing a parent container object automatically releases all of its children. For example, calling `Release()` on a [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance will release every function, variable, and expression defined within it.
    *   **Scoped Release**: uCalc objects can be configured for automatic release when they go out of scope, using language-specific constructs like `using` in C# or using [Owned](/ucalc/item/owned) in C++. For more details, see the [uCalc.Constructor](/reference/ucalc/constructor) topic.

--- 

## 🆚 `Release()` vs. `Active(false)`

It is crucial to understand the difference between permanently removing a rule and temporarily deactivating it.

| Action | `myRule.Release()` | `myRule.Active(false)` |
| :--- | :--- | :--- |
| **Effect** | **Permanent Deletion**. The rule's definition is removed from memory. | **Temporary Deactivation**. The rule's definition is preserved. |
| **Reversibility** | Irreversible. The rule must be redefined. | Reversible by calling `myRule.Active(true)`. |
| **Use Case** | Cleaning up resources for a rule that is no longer needed. | Temporarily disabling a rule for a specific operation. |


## ⚖️ Comparative Analysis

uCalc's memory model is distinct from both standard garbage collection (GC) and native C++ RAII.

*   **vs. Garbage Collection (C#)**: The C# `Item` object is a lightweight handle to a more substantial object inside the core uCalc engine. Even if the C# handle is garbage collected, the underlying engine object **will not be released**. You must call `Release()` or use `using` to free the engine's resources. Failure to do so can lead to memory leaks within the uCalc instance, even in a managed environment.

*   **vs. C++ Destructors**: Similarly, a C++ `Item` object going out of scope does not automatically release the underlying engine resource unless it is explicitly configured as `Owned`. `Release()` provides deterministic cleanup.

**Idempotency Note**: `Release()` is idempotent. Calling it multiple times on the same (already released) `Item` handle is safe and has no effect.

**Examples:**

### Example ID: 975

**Description:** Internal Test: Verifies that releasing a rule correctly 'un-shadows' a previously defined rule with the same pattern.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("The quick brown fox.");

// 1. Define the original rule
var ruleV1 = t.FromTo("brown", "BROWN_V1");
wl("Initial transform: ", t.Transform())

// 2. Define a new rule with the same pattern, shadowing the original
t.@Text("The quick brown fox.");
var ruleV2 = t.FromTo("brown", "BROWN_V2");
wl("After shadowing: ", t.Transform())

// 3. Release the new rule. The original rule should become active again.
t.@Text("The quick brown fox.");
ruleV2.Release();
wl("After release (reverted): ", t.Transform())
```

**Output:**
```
Initial transform: The quick BROWN_V1 fox.
After shadowing: The quick BROWN_V2 fox.
After release (reverted): The quick BROWN_V1 fox.
```

---

### Example ID: 145

**Description:** How to define and then permanently remove a rule.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var(string, text) = "(this and that) <this or that>";
t.@Text(text);

// Define two rules
var rule1 = t.FromTo("({txt})", "#{txt}#");
var rule2 = t.FromTo("<{txt}>", "${txt}$");

// Transform with both rules active
wl(t.Transform())

// Release the first rule
rule1.Release();

// Re-run the transformation; only the second rule applies
t.@Text(text);
wl(t.Transform())
```

**Output:**
```
#this and that# $this or that$
(this and that) $this or that$
```

---

---

## Replacement = [string] - ID: 284
/doc/reference/classes/ucalc.rule/replacement-=-[string]/

**Description:** Gets or sets the replacement string of a rule, which defines the output text for a pattern match.

**Remarks:**

# 🎯 The "To" in "From-To": Defining Replacement Logic

The `Replacement` property provides runtime access to the "source code" of a rule's replacement string—the part of the rule that defines the output. It allows you to programmatically inspect or even modify what a matched text segment will be transformed into.

This property applies to rules created with both [`FromTo()`](/Reference/uCalcBase/Transformer/FromTo) and [`Pattern()`](/Reference/uCalcBase/Transformer/Pattern).

### ⚙️ Getter and Setter Behavior

This property can be used to both read and write a rule's replacement logic:

*   **Getter**: [pseudocode]`myRule.@Replacement()` retrieves the literal string that defines the rule's output.
*   **Setter**: [pseudocode]`myRule.@Replacement("new replacement text")` modifies the rule at runtime. This change affects all subsequent `Transform()` operations.

### ✨ Implicit Behavior: `Pattern()` vs. `FromTo()`

Understanding the default replacement behavior is crucial:

*   For rules created with [`FromTo("pattern", "replacement")`](/Reference/uCalcBase/Transformer/FromTo), this property returns the exact `"replacement"` string you provided.
*   For rules created with [`Pattern("pattern")`](/Reference/uCalcBase/Transformer/Pattern), which have no explicit replacement, this property returns the special keyword **`{@Self}`**. This keyword instructs the transformer to re-insert the matched text without any changes, which is the default behavior for a find-only `Pattern` rule.

### 🧩 Components of a Replacement String

A replacement string is more than just literal text. It can contain dynamic components:

*   **Literals**: Plain text that is inserted as-is.
*   **Variable Placeholders**: `{varName}` inserts the text captured by a variable in the pattern.
*   **Pattern Methods**: Directives like [`{@Eval}`](/Reference/Patterns/Pattern-Methods/{@Eval}) or `{@File}` can execute logic, perform calculations, or load content during the replacement phase. For more details, see [Pattern Methods](/Reference/Patterns/Pattern-Methods/Introduction).

### 💡 Why uCalc? (Comparative Analysis)

Traditional regex engines typically use a simple, string-based replacement model with numeric or named backreferences.

*   **Standard Regex**: A replacement might look like `Hi, $2 $1` to reorder captured groups. This is functional but limited.
*   **uCalc's `Replacement`**: uCalc's model is far more powerful:
    *   **Readability**: Uses descriptive names (`{lastName}, {firstName}`) instead of cryptic indices.
    *   **Embedded Logic**: Natively supports conditional replacements (`{var:text-if-found}`) and can execute complex logic directly within the string using [pseudocode]`{@Eval: {var} * 1.1}`, capabilities that would require a separate callback function in most other engines.
    *   **Runtime Modification**: The ability to programmatically change a rule's replacement text at runtime provides a level of dynamism not available in statically compiled regex patterns.

**Examples:**

### Example ID: 134

**Description:** Replacement()

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("aaa bbb xyz 123");
var aaa = t.FromTo("aaa", "111");
var xyz = t.Pattern("xyz");
t.Filter();
wl(t.@Matches().@Text())

wl("-----")
wl(aaa.@Replacement())
wl(xyz.@Replacement())

```

**Output:**
```
111
xyz
-----
111
{@Self}
```

---

---

## RewindOnChange = [bool] - ID: 286
/doc/reference/classes/ucalc.rule/rewindonchange-=-[bool]/

**Description:** Controls whether the transformer re-scans text from the beginning of a match after a replacement, enabling recursive or cascading transformations.

**Remarks:**

# 🔄 Recursive Transformations with RewindOnChange

The `RewindOnChange` property controls the [Transformer](/Reference/uCalcBase/Transformer/Constructor)'s behavior after it successfully applies a rule. It allows you to create powerful recursive or cascading transformations that would otherwise require complex, multi-pass logic.

*   **`false` (Default)**: After a replacement, the [Transformer](/Reference/uCalcBase/Transformer/Constructor) continues scanning from the position *after* the newly inserted text. It will not re-evaluate the text that was just modified.

*   **`true`**: After a replacement, the [Transformer](/Reference/uCalcBase/Transformer/Constructor) "rewinds" its cursor to the *start* of the original match location and re-scans the text. This allows other rules—or even the same rule—to find new matches within the just-transformed text.

## 🎯 Core Use Case: Recursive and Cascading Rules

This property is the key to creating rules that expand recursively. A common use case is implementing variadic functions in a pre-processing step. Consider a pattern to expand `Add(1, 2, 3)` into `(1 + (2 + 3))`.

```pseudocode
// Without Rewind, only the first match is found.
New(uCalc::Transformer, t)
t.FromTo("Add({x}, {y})", "({x} + Add({y}))");
wl(t.Transform("Add(1,2,3)"))
// Output: (1 + Add(2,3)) - The inner Add(2,3) is not expanded.

// With Rewind, the expansion continues until no matches are left.
t.Reset();
t.FromTo("Add({x}, {y})", "({x} + Add({y}))").@RewindOnChange(true);
wl(t.Transform("Add(1,2,3)"))
// Output: (1 + (2 + 3))
```

This works because after the first transform, the string becomes `(1 + Add(2,3))`. The rewind causes the parser to re-scan this, find `Add(2,3)`, and apply the rule again.

## ⚠️ Infinite Loop Warning

Use `@RewindOnChange` with caution. If your rules can transform text in a cyclical manner, you will create an infinite loop.

**Example of an Infinite Loop:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("A", "B").SetRewindOnChange(true);
t.FromTo("B", "A").SetRewindOnChange(true);

// This will cause an infinite loop: A -> B -> A -> B ...
// t.Transform("A"); 
```

To prevent this, ensure your transformation rules are always reducing the input towards a final, non-matching state, or use a [Maximum](/Reference/uCalcBase/Rule/Maximum) match count to terminate the process.

## 💡 Why uCalc? (Comparative Analysis)

In a traditional regex-based workflow, achieving a recursive transformation requires manual, imperative code:

```csharp
// Manual approach without uCalc
string text = "Add(1,2,3)";
while (text.Contains("Add(")) {
    text = Regex.Replace(text, "Add\\((.*?),(.*)\\)", "($1 + Add($2))");
}
```
This approach is slow, brittle, and mixes transformation logic with control flow. uCalc's `@RewindOnChange(true)` is **declarative**. You simply state your intent on the rule, and the engine handles the complex looping and re-scanning logic internally in a highly optimized manner.

## Per-Rule vs. Global Setting

You can set this property on an individual [Rule](/Reference/uCalcBase/Rule/Constructor) for granular control, or you can set it on the [Transformer.DefaultRuleSet](/Reference/uCalcBase/Transformer/DefaultRuleSet) to have it apply to all subsequently defined rules in that transformer.

**Examples:**

### Example ID: 979

**Description:** The cascading effect of enabling `RewindOnChange`.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Rule 1: Replace 'A' with 'B'. Rewind is off by default.
t.FromTo("A", "B");
// Rule 2: Replace 'B' with 'C'.
t.FromTo("B", "C");

wl("--- Rewind Disabled ---")
// The 'A' becomes 'B', but the scan continues *after* the 'B', so rule 2 is not triggered.
wl(t.Transform("Start A End"))
t.Reset();

// Now, enable rewind on the first rule.
t.FromTo("A", "B").@RewindOnChange(true);
t.FromTo("B", "C");

wl("")
wl("--- Rewind Enabled ---")
// The 'A' becomes 'B', rewind occurs, the 'B' is re-scanned and becomes 'C'.
wl(t.Transform("Start A End"))
```

**Output:**
```
--- Rewind Disabled ---
Start B End

--- Rewind Enabled ---
Start C End
```

---

### Example ID: 980

**Description:** Demonstrates using `RewindOnChange` to create a recursive `AddUp` function within the expression transformer.

**Code:**
```pseudocode
var t = uc.@ExpressionTransformer();  // Transformer used for Eval() and Evaluate()

var p1 = t.FromTo("AddUp({x})", "{x}"); // Base case
var p2 = t.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))").SetRewindOnChange(true); // Recursive step

wl("p1 RewindOnChange: ", bool(p1.@RewindOnChange()))
wl("p2 RewindOnChange: ", bool(p2.@RewindOnChange()))

wl("")
wl("Input: ", "AddUp(1,2,3,4)")
wl("Transform: ", t.Transform("AddUp(1,2,3,4)"))
wl("Eval: ", uc.Eval("AddUp(1,2,3,4)"))
```

**Output:**
```
p1 RewindOnChange: False
p2 RewindOnChange: True

Input: AddUp(1,2,3,4)
Transform: (1 + (2 + (3 + 4)))
Eval: 10
```

---

### Example ID: 981

**Description:** Applies `RewindOnChange` to a default rule set to enable complex, multi-rule transformations for a custom `Average` function.

**Code:**
```pseudocode
var t = uc.@ExpressionTransformer();

// Enable rewind for all subsequent rules in this transformer.
t.@DefaultRuleSet().SetRewindOnChange(true);

// Define the recursive rules.
t.FromTo("AddUp({x})", "{x}");
t.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

t.FromTo("ArgCount({x})", "1");
t.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))");

// The main rule that combines the others.
t.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})");

var expression = "Average(1, 2, 3, 4)";
wl("Input: ", expression)
wl("Transform: ", t.Transform(expression))
wl("Eval: ", uc.Eval(expression))
```

**Output:**
```
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
```

---

### Example ID: 73

**Description:** Using ExpressionTransformer to transform expressions before they are parsed

**Code:**
```pseudocode
var ExprT = uc.@ExpressionTransformer();  // Transformer used for Eval() and Evaluate()

var p1 = ExprT.FromTo("AddUp({x})", "{x}"); // RewindOnChange False by default
var p2 = ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))").SetRewindOnChange(true);

wl("p1 RewindOnChange: ", bool(p1.@RewindOnChange()))
wl("p2 RewindOnChange: ", bool(p2.@RewindOnChange()))

wl("")

wl("Input: ", "AddUp(1,2,3,4)")
wl("Transform: ", ExprT.Transform("AddUp(1,2,3,4)"))
wl("Eval: ", uc.Eval("AddUp(1,2,3,4)"))
```

**Output:**
```
p1 RewindOnChange: False
p2 RewindOnChange: True

Input: AddUp(1,2,3,4)
Transform: (1 + (2 + (3 + 4)))
Eval: 10
```

---

### Example ID: 152

**Description:** RewindOnChange

**Code:**
```pseudocode
var ExprT = uc.@ExpressionTransformer();  // Transformer used for Eval() and Evaluate()

ExprT.@DefaultRuleSet().@RewindOnChange(true);

ExprT.FromTo("AddUp({x})", "{x}");
ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

ExprT.FromTo("ArgCount({x})", "1");
ExprT.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))");

ExprT.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})");

var Expression = "Average(1, 2, 3, 4)";
wl("Input: ", Expression)
wl("Transform: ", ExprT.Transform(Expression))
wl("Eval: ", uc.Eval(Expression))
```

**Output:**
```
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
```

---

---

## RightToLeft = [bool] - ID: 289
/doc/reference/classes/ucalc.rule/righttoleft-=-[bool]/

**Description:** Lets you know the associativity property of a rule get/set

**Remarks:**

[revisit]
Lets you know the associativity property of a rule; true means it goes right to left; false means it's left to right (default)
getter setter

**Examples:**

---

## StartAfter = [int] - ID: 295
/doc/reference/classes/ucalc.rule/startafter-=-[int]/

**Description:** Gets or sets the number of matches a rule must find and ignore before it starts including subsequent matches in the results.

**Remarks:**

# 🎯 Skipping Initial Matches: StartAfter

The `StartAfter` property sets a zero-based offset for a rule's results, instructing the [Transformer](/Reference/uCalcBase/Transformer/Constructor) to find and discard a specified number of initial matches before including any subsequent matches in the final collection. This is a powerful tool for pagination, skipping headers, or ignoring a known number of preliminary patterns.

The default value is `0`, meaning no matches are skipped.

### ⚙️ Getter and Setter Behavior

This property functions as both a getter and a setter:

*   **Getter**: [pseudocode]`var offset = myRule.@StartAfter();`
    Returns the current number of matches to be skipped.
*   **Setter**: [pseudocode]`myRule.@StartAfter(2);` property or `SetStartAfter()` method.
    Sets the number of matches to skip. This method supports a **fluent interface**, returning the [Rule](/Reference/uCalcBase/Rule/Constructor) object to allow for method chaining.

### `StartAfter` vs. `StopAfter` vs. `Minimum`

Choosing the correct property to limit matches is crucial. This table clarifies their distinct behaviors:

| Property                                                      | Behavior                                                                      | Use Case                                                          |
| :------------------------------------------------------------ | :---------------------------------------------------------------------------- | :---------------------------------------------------------------- |
| **`@StartAfter(n)`** (This Property)                          | Skips the first `n` matches and keeps the rest.                               | Skipping a known number of initial items (like a header).         |
| **[`@StopAfter(n)`](/Reference/uCalcBase/Rule/StopAfter)**         | Keeps the first `n` matches and discards the rest.                            | Limiting a search to the first few occurrences of a pattern.      |
| **[`@Minimum(n)`](/Reference/uCalcBase/Rule/Minimum)**             | **Validates**. If fewer than `n` matches are found, **all** matches for this rule are discarded. | Ensuring a pattern appears a certain number of times to be valid. |

### 💡 Why uCalc? (Comparative Analysis)

In a standard data processing workflow, like using LINQ in C#, you would achieve this imperatively:

```csharp
// C# LINQ example
var resultsToProcess = allMatches.Skip(2);
```

This approach requires you to first collect all possible matches and then filter them in your application code.

uCalc's `@StartAfter` is **declarative**. You state the requirement directly on the [Rule](/Reference/uCalcBase/Rule/Constructor), and the engine handles the logic internally. This can be more efficient, as the engine can potentially discard the skipped matches as it finds them, reducing the memory overhead of storing a complete match list before filtering.

**Examples:**

### Example ID: 985

**Description:** Finding all occurrences of a letter except for the first one.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("a b c a d e a f g");
var ruleA = t.FromTo("a", "[MATCH]");

// Skip the first 'a' that is found
ruleA.@StartAfter(1);

wl(t.Transform())
```

**Output:**
```
a b c [MATCH] d e [MATCH] f g
```

---

### Example ID: 986

**Description:** A practical example that processes a list of tasks but skips the first two high-priority items.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var taskList = "Task:1 Task:2 Task:3 Task:4 Task:5";
t.@Text(taskList);

var taskRule = t.FromTo("Task:{@Number:id}", "Processed Task {id}");

// Skip the first two tasks in the list
taskRule.@StartAfter(2);

wl(t.Transform())
```

**Output:**
```
Task:1 Task:2 Processed Task 3 Processed Task 4 Processed Task 5
```

---

### Example ID: 138

**Description:** Rule StartAfter()

**Code:**
```pseudocode
var t = uc.NewTransformer();
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

var Fruit = t.FromTo("CommonName={@string:name}", "{name}");

// StopAfter()
Fruit.@StopAfter(4);
t.Filter(FruitsXML);
wl("*** Stop after: ", Fruit.@StopAfter(), " ***")
wl(t.@Matches().@Text())
Fruit.@StopAfter(-1); // Resets back to infinity (default) for next example
wl("")

// StartAfter()
Fruit.@StartAfter(6);
t.Filter(FruitsXML);
wl("*** Start after: ", Fruit.@StartAfter(), " ***")
wl(t.@Matches().@Text())
Fruit.@StartAfter(0); // Resets back to 0 (default) for next example
wl("")


// Both StartAfter() and StopAfter()
Fruit.SetStartAfter(2).SetStopAfter(5);
t.Filter(FruitsXML);
wl("*** Between ", Fruit.@StartAfter() + 1, " and ", Fruit.@StopAfter(), " ***")
wl(t.@Matches().@Text())
wl("")

// All
uc.DefineVariable("x = 1");
Fruit = t.FromTo("CommonName={@string:name}", "{@Eval: x++}. {name}");
t.Filter(FruitsXML);
wl("*** All ***")
wl(t.@Matches().@Text())
```

**Output:**
```
*** Stop after: 4 ***
Apple
Banana
Orange
Grapes

*** Start after: 6 ***
Mango
Blueberry
Rambutan
Salak (Snake Fruit)
Jabuticaba
Watermelon

*** Between 3 and 5 ***
Orange
Grapes
Strawberry

*** All ***
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon
```

---

---

## StatementSensitive = [bool] - ID: 298
/doc/reference/classes/ucalc.rule/statementsensitive-=-[bool]/

**Description:** Controls whether a pattern rule respects statement separators (like semicolons or newlines), preventing matches from crossing structural boundaries.

**Remarks:**

# 🛡️ Structural Integrity: The StatementSensitive Property

The `StatementSensitive` property controls whether a pattern is aware of **statement separators**, preventing a variable capture from spanning across multiple distinct statements. When enabled (the default), it acts as a crucial safety feature, ensuring that a pattern like `"start {body} end"` doesn't accidentally consume an entire file if the "end" token is missing.

This property provides per-rule control, overriding the global setting inherited from the [Transformer's](/Reference/uCalcBase/Transformer/DefaultRuleSet) `DefaultRuleSet`.

## ⚙️ How It Works

This property acts as a switch for an individual rule's parsing logic.

| Setting | Behavior |
| :--- | :--- |
| `true` (Default) | **Structurally Aware**. The parser treats tokens categorized as `TokenType::StatementSep` (by default, newlines and semicolons) as hard boundaries for variable captures. A pattern like `if {etc}` will match only up to the end of the line or the next semicolon. |
| `false` | **Structurally Unaware**. Statement separators are treated like any other generic token. This is essential for parsing multi-line content such as HTML/XML blocks or free-form text where newlines are simply formatting. |

By default, the uCalc expression engine defines the newline (`_token_newline`) and semicolon (`_token_semicolon`) tokens as statement separators. You can customize this by modifying the token definitions using the [Transformer.Tokens](/Reference/uCalcBase/Transformer/Tokens) property.

## 💡 Why uCalc? (Comparative Analysis)

In traditional regular expressions, handling multi-line text is notoriously tricky.

*   The dot `.` meta-character, by default, does not match newlines. To match across lines, you often have to enable a special "dotall" or "single-line" mode (e.g., the `/s` flag). This is a global switch for the entire regex.
*   Alternatively, you must use complex character classes like `[\s\S]` to match any character including newlines.

This is a blunt, all-or-nothing approach that lacks structural awareness.

uCalc's `StatementSensitive` property is more sophisticated because it is based on the **semantic role** of tokens, not just character types:

1.  **Tokenizer Awareness**: The tokenizer runs first and identifies tokens with the `TokenType::StatementSep` property.
2.  **Safe Matching by Default**: When `StatementSensitive` is `true`, the parser respects these separators as boundaries, preventing greedy variable captures from "leaking" across statements. This provides a much safer default behavior for parsing structured code or data.
3.  **Granular Control**: You can disable this safety feature on a per-rule basis, allowing you to have some rules that respect statement boundaries and others that don't, all within the same `Transformer` and running concurrently.

This gives you the flexibility to parse complex, mixed-content documents in a way that is far more robust and maintainable than with regex alone.

**Examples:**

### Example ID: 988

**Description:** Demonstrates the difference in variable capture behavior when StatementSensitive is enabled versus disabled.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var(string, txt) = "start one; two end";

// Default behavior is StatementSensitive(true), so {body} stops at the semicolon
// and the 'end' anchor is never found. The transform fails.
var rule = t.FromTo("start {body} end", "[{body}]");
wl("Sensitive (default): ", t.Transform(txt))

rule.@StatementSensitive(false);
// With StatementSensitive(false), {body} captures across the semicolon.
wl("Insensitive: ", t.Transform(txt))
```

**Output:**
```
Sensitive (default): start one; two end
Insensitive: [one; two]
```

---

### Example ID: 989

**Description:** Practical: Shows how disabling statement sensitivity is essential for parsing multi-line HTML/XML blocks.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var source = [verbatim]<data>
  content spans
  multiple lines
</data>[/verbatim];

// This rule must disable StatementSensitive to capture the multi-line body,
// otherwise the first newline would terminate the {body} variable.
var rule = t.FromTo("<data>{body}</data>", "Body: [{body}]");
rule.@StatementSensitive(false);

wl(t.Transform(source))
```

**Output:**
```
Body: [
  content spans
  multiple lines
]
```

---

### Example ID: 125

**Description:** Using SkipOver() to ignore XML-style comments

**Code:**
```pseudocode
// StatementSensitive() is set to false so that ";" and newline are not treated as special

var t = uc.NewTransformer();
wl("StatementSensitive: ", bool(t.@DefaultRuleSet().@StatementSensitive()))
wl("Setting StatementSensitive to False")

t.@DefaultRuleSet().@StatementSensitive(false); // so that newline does not behave as a statement separator

wl("StatementSensitive: ", bool(t.@DefaultRuleSet().@StatementSensitive()))
wl("")

var Content =
[verbatim]
<nav aria-label="Main navigation">
  <ul>
    <li><a href="#intro">Intro</a></li>
    <li><a href="#examples">Examples</a></li>
    <!-- <li><a href="#contact">Contact</a></li> -->
  </ul>
</nav>

<!-- 
<h2>Ingredients</h2>
<ul>
  <li>3 cups flour</li>
  <li>1.5 cups water</li>
  <li>1 tsp salt</li>
</ul>
-->

<nav aria-label="Chapter navigation">
    <ul>
      <li><a href="#one">One</a></li>
      <li><a href="#two">Two</a></li>
      <li><a href="#three">Three</a></li>
    </ul>
</nav>
[/verbatim];

t.Str(Content);
var Pattern = t.Pattern("<li>{item}</li>");
t.Find();
wl(t.@Matches().@Text())
wl("")

wl("<!-- Skip over commented lines -->")
wl("----------------------------------")
t.SkipOver("<!-- {comment} -->");
t.Find();
wl(t.@Matches().@Text())
wl("")

```

**Output:**
```
StatementSensitive: True
Setting StatementSensitive to False
StatementSensitive: False

<li><a href="#intro">Intro</a></li>
<li><a href="#examples">Examples</a></li>
<li><a href="#contact">Contact</a></li>
<li>3 cups flour</li>
<li>1.5 cups water</li>
<li>1 tsp salt</li>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>

<!-- Skip over commented lines -->
----------------------------------
<li><a href="#intro">Intro</a></li>
<li><a href="#examples">Examples</a></li>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>
```

---

### Example ID: 140

**Description:** StatementSensitive()

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("x = 1; if (true) func1(3+4); else func2(x*y); y = x + 2");
var p = t.Pattern("if {etc}");

wl("Input: ", t.@Text())
wl("Pattern: ", p.@Pattern())
wl("")

t.Find();
wl("StatementSensitive: ", bool(t.@DefaultRuleSet().@StatementSensitive()))
wl(t.@Matches().@Text())
wl("")

t.@DefaultRuleSet().@StatementSensitive(false);
t.Find();
wl("StatementSensitive: ", bool(t.@DefaultRuleSet().@StatementSensitive()))
wl(t.@Matches().@Text())
```

**Output:**
```
Input: x = 1; if (true) func1(3+4); else func2(x*y); y = x + 2
Pattern: if {etc}

StatementSensitive: True
if (true) func1(3+4)

StatementSensitive: False
if (true) func1(3+4); else func2(x*y); y = x + 2
```

---

---

## StopAfter = [int] - ID: 301
/doc/reference/classes/ucalc.rule/stopafter-=-[int]/

**Description:** Gets or sets the maximum number of matches a rule will find and keep, ignoring all subsequent matches for that rule.

**Remarks:**

# 🎯 Limiting Matches with StopAfter

The `@StopAfter` property sets a limit on the number of matches a rule can find. Once the specified number of matches has been found, the [Transformer](/Reference/uCalcBase/Transformer/Constructor) stops searching for any more matches *for that specific rule*. This is an efficient way to limit results when you only need the first few occurrences of a pattern.

The default value is `-1` (or the maximum value for an unsigned integer), which signifies no limit.

### ⚙️ Getter and Setter Behavior

This property functions as both a getter and a setter:

*   **Getter**: [pseudocode]`var limit = myRule.@StopAfter();`
    Returns the current match limit for the rule.

*   **Setter**: [pseudocode]`myRule.@StopAfter(5);` or `SetStopAfter()` method.
    Sets the match limit. This method supports a **fluent interface**, returning the [Rule](/Reference/uCalcBase/Rule/Constructor) object to allow for method chaining.

### `StopAfter` vs. `StartAfter` vs. `Maximum`

Choosing the correct property to limit matches is crucial. This table clarifies their distinct behaviors:

| Property                                                      | Behavior                                                                      | Use Case                                                                              |
| :------------------------------------------------------------ | :---------------------------------------------------------------------------- | :------------------------------------------------------------------------------------ |
| **`@StopAfter(n)`** (This Property)                          | Keeps the first `n` matches found and ignores all subsequent ones.           | Getting the first few results of a search ("take first n").                           |
| **[`@StartAfter(n)`](/Reference/uCalcBase/Rule/StartAfter)**     | Skips the first `n` matches found and keeps all subsequent ones.                | Skipping a known header or preamble ("skip first n").                                  |
| **[`@Maximum(n)`](/Reference/uCalcBase/Rule/Maximum)**             | **Validates**. If more than `n` matches are found, **all** matches for this rule are invalidated and discarded. | Enforcing a "max N allowed" structural rule. Fails if the limit is exceeded.       |
| **[`@GlobalMaximum(n)`](/Reference/uCalcBase/Rule/GlobalMaximum)** | **Validates globally**. If more than `n` matches are found, **all** matches for **all rules** are invalidated. | Failing the entire transform if a critical structural rule is violated.               |

You can combine `@StartAfter` and `@StopAfter` to retrieve a "page" of results. The `@StopAfter` limit is applied first during the scan, and then `@StartAfter` filters that result set. For example, `@StartAfter(10).@StopAfter(20)` will find the first 20 matches, then discard the first 10, resulting in matches 11 through 20.

### 💡 Why uCalc? (Comparative Analysis)

In a standard data processing workflow, like using LINQ in C#, you would achieve this imperatively after collecting all results:

```csharp
// C# LINQ example
var firstFiveResults = allMatches.Take(5);
```

uCalc's `@StopAfter` is **declarative** and can be more performant. You state the limit directly on the rule, and the engine can often stop its search early once the limit is reached, avoiding the work of finding all possible matches in a large document. This makes it a highly efficient tool for processing large-scale text.

**Examples:**

### Example ID: 991

**Description:** Finds and transforms only the first three occurrences of a pattern, ignoring any subsequent ones.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("a b c a d e a f g a h i");
var ruleA = t.FromTo("a", "[A]");

// Only find and transform the first 3 occurrences of 'a'.
ruleA.@StopAfter(3);

wl(t.Transform())
```

**Output:**
```
[A] b c [A] d e [A] f g a h i
```

---

### Example ID: 992

**Description:** Processes a log file but stops after finding the first error message to focus on the initial problem.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var logText = "ERROR: Fail 1. INFO: OK. ERROR: Fail 2. ERROR: Fail 3.";
t.@Text(logText);

var errorRule = t.Pattern("ERROR: {msg}.");
// Stop after finding the first error to focus on the initial problem.
errorRule.@StopAfter(1);
t.Find();

wl("First error found: ", t.@Matches().@Text())
```

**Output:**
```
First error found: ERROR: Fail 1.
```

---

### Example ID: 993

**Description:** Internal Test: Combines `@StartAfter` and `@StopAfter` to retrieve a specific 'page' of results (matches 3 through 7).

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("1 2 3 4 5 6 7 8 9 10 11 12");
var rule = t.Pattern("{@Number}");

// Get a "page" of results: matches 3 through 7.
// The engine will stop finding numbers after the 7th match is found.
// Then, it will skip the first 2 matches from that set.
rule.@StartAfter(2); // Skip first 2
rule.@StopAfter(7);  // Find up to 7

t.Find();

wl("Matches found:")
wl(t.@Matches().@Text())
```

**Output:**
```
Matches found:
3
4
5
6
7
```

---

### Example ID: 138

**Description:** Rule StartAfter()

**Code:**
```pseudocode
var t = uc.NewTransformer();
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

var Fruit = t.FromTo("CommonName={@string:name}", "{name}");

// StopAfter()
Fruit.@StopAfter(4);
t.Filter(FruitsXML);
wl("*** Stop after: ", Fruit.@StopAfter(), " ***")
wl(t.@Matches().@Text())
Fruit.@StopAfter(-1); // Resets back to infinity (default) for next example
wl("")

// StartAfter()
Fruit.@StartAfter(6);
t.Filter(FruitsXML);
wl("*** Start after: ", Fruit.@StartAfter(), " ***")
wl(t.@Matches().@Text())
Fruit.@StartAfter(0); // Resets back to 0 (default) for next example
wl("")


// Both StartAfter() and StopAfter()
Fruit.SetStartAfter(2).SetStopAfter(5);
t.Filter(FruitsXML);
wl("*** Between ", Fruit.@StartAfter() + 1, " and ", Fruit.@StopAfter(), " ***")
wl(t.@Matches().@Text())
wl("")

// All
uc.DefineVariable("x = 1");
Fruit = t.FromTo("CommonName={@string:name}", "{@Eval: x++}. {name}");
t.Filter(FruitsXML);
wl("*** All ***")
wl(t.@Matches().@Text())
```

**Output:**
```
*** Stop after: 4 ***
Apple
Banana
Orange
Grapes

*** Start after: 6 ***
Mango
Blueberry
Rambutan
Salak (Snake Fruit)
Jabuticaba
Watermelon

*** Between 3 and 5 ***
Orange
Grapes
Strawberry

*** All ***
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon
```

---

---

## Tag = [int] - ID: 254
/doc/reference/classes/ucalc.rule/tag-=-[int]/

**Description:** Gets or sets a user-defined integer value, allowing for fast, programmatic identification and categorization of rules at runtime.

**Remarks:**

# 🏷️ Tagging Rules for Programmatic Identification

The `Tag` property allows you to associate a custom integer identifier with any [Rule](/Reference/uCalcBase/Rule/Constructor). This is a powerful mechanism for categorizing rules and identifying which pattern generated a specific [Match](/Reference/uCalcBase/Matches/Match/Constructor) at runtime, without relying on slower string comparisons.

### ⚙️ Getter and Setter Behavior

This property functions as both a getter and a setter, following the standard property syntax:

*   **Getter**: [pseudocode]`var myTag = myRule.@Tag();`
    Retrieves the integer tag associated with the rule. If no tag has been set, it defaults to `0`.

*   **Setter**: [pseudocode]`myRule.@Tag(123);`
    Assigns an integer tag to the rule. The setter `SetTag()` function supports a **fluent interface**, returning the `Rule` object itself to allow for method chaining.

### 🎯 Primary Use Cases

`Tag` is the preferred method for programmatically identifying rules because comparing integers is significantly faster than comparing strings from [Name()](/Reference/uCalcBase/Rule/Name) or [Description()](/Reference/uCalcBase/Rule/Description).

*   **Syntax Highlighting**: In a code editor, you can create rules for keywords, strings, and comments, each with a unique tag (e.g., `1` for keyword, `2` for string). When processing matches, you can check the `Match.Rule().Tag()` to determine which color or style to apply.

*   **Building an Abstract Syntax Tree (AST)**: When building a custom parser, you can use tags to represent token types or node types in your grammar (e.g., `TAG_IDENTIFIER`, `TAG_OPERATOR`).

*   **State Machines**: In a multi-stage transformation, tags can represent different states, allowing you to easily identify which rule corresponds to which state transition.

### 💡 Why uCalc? (Comparative Analysis)

In a standard Regex-based system, there is no built-in way to attach metadata like a numeric tag to a pattern. A developer would need to manage this association externally, which is cumbersome and less efficient.

**Without uCalc:**
```csharp
// Manual, external mapping
var ruleMappings = new Dictionary<Regex, int>
{
    { new Regex(@"\b(if|else|for)\b"), 1 }, // Tag 1 for keywords
    { new Regex(@"""[^\"]*""""), 2 }        // Tag 2 for strings
};
// ... must then manually find which Regex produced a match ...
```

**With uCalc:**
```pseudocode
// Integrated, declarative approach
var keywordRule = t.Pattern("{if|else|for}").SetTag(1);
var stringRule = t.Pattern("{@String}").SetTag(2);
// ... later, simply check match.Rule().Tag() ...
```

uCalc's integrated `Tag` property provides a cleaner, more declarative, and higher-performance solution by keeping the identifying metadata tightly coupled with the rule itself.

**Examples:**

### Example ID: 994

**Description:** How to set and get tags for different rules.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var ruleA = t.Pattern("A").SetTag(10);
var ruleB = t.Pattern("B").SetTag(20);

wl("Tag for Rule A: ", ruleA.@Tag())
wl("Tag for Rule B: ", ruleB.@Tag())
```

**Output:**
```
Tag for Rule A: 10
Tag for Rule B: 20
```

---

### Example ID: 995

**Description:** A practical example using tags to build a simple syntax highlighter that categorizes matches.

**Code:**
```pseudocode
// Practical: Basic Syntax Highlighter
New(uCalc::Transformer, t)

// Define categories with integer tags
var TAG_KEYWORD = 1;
var TAG_STRING = 2;
var TAG_COMMENT = 3;

// Define rules and tag them
t.Pattern("{ if | else | for | while }").SetTag(TAG_KEYWORD);
t.Pattern("{@String}").SetTag(TAG_STRING);
t.Pattern("// {text}").SetTag(TAG_COMMENT);

t.@Text([verbatim]for (i=0; i<10; i++) { s = "hello"; // comment }[/verbatim]);
t.Find();

foreach (var match in t.@Matches())
    var tag = match.@Rule().@Tag();
    if (tag == TAG_KEYWORD)
        wl("TAG_KEYWORD: ", match.@Text())
    else if (tag == TAG_STRING)
        wl("TAG_STRING: ", match.@Text())
    else if (tag == TAG_COMMENT)
        wl("TAG_COMMENT: ", match.@Text())
    end if
end foreach
```

**Output:**
```
TAG_KEYWORD: for
TAG_STRING: "hello"
TAG_COMMENT: // comment 
```

---

### Example ID: 996

**Description:** Internal Test: Verifies rule precedence and tag retrieval by traversing the overload chain with NextOverload.

**Code:**
```pseudocode
// Internal Test: Verifies precedence and tag retrieval via NextOverload
New(uCalc::Transformer, t)
t.@Text("Testing (a b c) Testing x y z! Testing 1 2 3.");

// Rules defined last have higher precedence for the same anchor ("Testing")
var p1 = t.Pattern("Testing {etc}.").SetTag(111);
var p2 = t.Pattern("Testing {etc}!").SetTag(222);
var p3 = t.Pattern("Testing ({etc})").SetTag(333);

// Get the highest precedence rule via Pattern's return value
var highestPriorityRule = p3;
wl("Highest priority rule tag: ", highestPriorityRule.@Tag())

// Walk the overload chain
var midPriorityRule = highestPriorityRule.NextOverload();
wl("Mid priority rule tag: ", midPriorityRule.@Tag())

var lowPriorityRule = midPriorityRule.NextOverload();
wl("Low priority rule tag: ", lowPriorityRule.@Tag())

// The end of the chain should have a tag of 0 (default)
var endOfChain = lowPriorityRule.NextOverload();
wl("End of chain tag: ", endOfChain.@Tag())
```

**Output:**
```
Highest priority rule tag: 333
Mid priority rule tag: 222
Low priority rule tag: 111
End of chain tag: 0
```

---

### Example ID: 131

**Description:** Rule NextOverload and Tag

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("Testing (a b c) Testing x y z! Testing 1 2 3.");

var Pattern1 = t.Pattern("Testing {etc}.").SetTag(111);
var Pattern2 = t.Pattern("Testing {etc}!").SetTag(222);
var Pattern3 = t.Pattern("Testing ({etc})").SetTag(333);

t.Find();
wl("--- Matches ---")
wl(t.@Matches().@Text())
wl("--- Patterns ---")
wl(Pattern1.@Pattern())
wl(Pattern2.@Pattern())
wl(Pattern3.@Pattern())
wl("---- Tags ----")
wl(Pattern1.@Tag())
wl(Pattern2.@Tag())
wl(Pattern3.@Tag())
wl("-- Overload Tags --")
// Note that most recently defined patterns come first
wl(Pattern3.NextOverload().@Tag())
wl(Pattern2.NextOverload().@Tag())
wl(Pattern1.NextOverload().@Tag())


```

**Output:**
```
--- Matches ---
Testing (a b c)
Testing x y z!
Testing 1 2 3.
--- Patterns ---
Testing {etc}.
Testing {etc}!
Testing ({etc})
---- Tags ----
111
222
333
-- Overload Tags --
222
111
0
```

---

---

## uCalc = [uCalc] - ID: 534
/doc/reference/classes/ucalc.rule/ucalc-=-[ucalc]/

**Description:** Retrieves the parent uCalc instance that owns the rule, providing access to its full execution context.

**Remarks:**

# 🧭 Navigating the Hierarchy: Rule.uCalc

Every [Rule](/Reference/uCalcBase/Rule/Constructor) object exists within the context of a parent [Transformer](/Reference/uCalcBase/Transformer/Constructor), which in turn is owned by a specific [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance. This property provides the crucial link back to the root `uCalc` engine, allowing you to navigate "up" the object hierarchy from a specific rule to its ultimate execution context.

This is essential for introspection and for writing context-aware transformation logic.

## 🎯 Primary Use Cases

1.  **Contextual Operations**: The most common use is to perform another operation within the same context as the item. If you have a `Rule` object but not a direct reference to its parent `uCalc` instance, you can use this property to retrieve it and call methods like [Eval()](/Reference/uCalcBase/uCalc/Eval) or [DefineVariable()](/Reference/uCalcBase/uCalc/DefineVariable).

2.  **Instance Introspection**: It allows you to determine if two different rules belong to the same execution context, which is invaluable for debugging applications that manage multiple, isolated uCalc instances.

3.  **Accessing Sibling Items**: Once you retrieve the parent instance, you can use it to find other items within the same sandbox, for example: `myRule.@uCalc().ItemOf("SomeOtherVar")`.

## 💡 Why uCalc? (Comparative Analysis)

This parent-child relationship is a common design pattern for creating navigable object trees.

*   **vs. DOM (Document Object Model)**: The relationship between a [Rule](/Reference/uCalcBase/Rule/Constructor) and its parent `uCalc` instance is analogous to an HTML element and its `ownerDocument` property in the DOM. It provides a structured, predictable way to traverse the hierarchy of your parsing logic. Just as you might walk up the DOM tree from a specific `<div>` to find its container, you can walk up from a `Rule` to its owning `uCalc` engine.

*   **vs. Ad-Hoc Rule Management**: Without this built-in link, you would need to manually track which `Transformer` (and which `uCalc` instance) owns which `Rule`, likely using external dictionaries or wrapper classes. This is complex and error-prone. By making `uCalc()` a first-class property, uCalc provides a clean, reliable, and integrated solution for managing the relationship between rules and their execution context.

**Examples:**

### Example ID: 997

**Description:** How to retrieve a rule's parent uCalc instance and verify its identity.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var myRule = t.FromTo("A", "B");

// Get the parent uCalc from the rule
var parent_uc = myRule.@uCalc();

// Verify they are the same instance using their MemoryIndex
wl(bool(parent_uc.@MemoryIndex() == uc.@MemoryIndex()))
```

**Output:**
```
True
```

---

### Example ID: 998

**Description:** A practical example that uses a rule's parent context to define and evaluate an expression.

**Code:**
```pseudocode
// The transformer 't' belongs to the main 'uc' instance.
New(uCalc::Transformer, t(uc))

// Define a variable in the transformer's parent context.
t.@uCalc().DefineVariable("VarX = 123");

// This rule is created within 't' and will need to access VarX.
var myRule = t.FromTo("x", "{@Eval: VarX}");

// Get the rule's parent uCalc instance...
var parent_uc = myRule.@uCalc();

// ...and use it to evaluate an expression to prove we have the right context.
wl("Value of VarX in parent context: ", parent_uc.Eval("VarX"))

// Now, run the transformation. The {@Eval} in the rule
// correctly finds 'VarX' in its parent uCalc context.
wl(t.Transform("The value is: x"))
```

**Output:**
```
Value of VarX in parent context: 123
The value is: 123
```

---

### Example ID: 999

**Description:** Internal Test: Verifies that a rule defined in a nested LocalTransformer correctly resolves its parent to the root uCalc instance.

**Code:**
```pseudocode
New(uCalc, root_uc)
root_uc.@Description("Root uCalc Instance");

New(uCalc::Transformer, main_t(root_uc))

// Create a rule in the main transformer
var outerRule = main_t.Pattern("OUTER({body})");

// Get a local transformer for the outer rule
var local_t = outerRule.@LocalTransformer();
local_t.@Description("Local Transformer");

// Create an inner rule inside the local transformer
var innerRule = local_t.FromTo("INNER", "inner_match");

// Verify both rules resolve to the same root uCalc instance
var outerParent = outerRule.@uCalc();
var innerParent = innerRule.@uCalc();

wl("Outer rule's parent: ", outerParent.@Description())
wl("Inner rule's parent: ", innerParent.@Description())
wl("Both rules share the same root uCalc instance: ", bool(outerParent.Handle() == innerParent.Handle()))
```

**Output:**
```
Outer rule's parent: Root uCalc Instance
Inner rule's parent: Root uCalc Instance
Both rules share the same root uCalc instance: True
```

---

### Example ID: 141

**Description:** Rule uCalc

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("The value is: x");

uc.DefineVariable("VarX");
t.FromTo("x", "{@Eval: VarX}").@uCalc().Eval("VarX = 123");

t.Transform();
wl(t.@Text())
```

**Output:**
```
The value is: 123
```

---

---

## Verbatim = [bool] - ID: 251
/doc/reference/classes/ucalc.rule/verbatim-=-[bool]/

**Description:** Gets or sets whether a rule's variable captures are treated as verbatim blocks, preventing nested pattern matching within them.

**Remarks:**

## 🛡️ Verbatim Capture: Making Content Opaque

By default, uCalc is "nested match aware." When a variable like `{content}` captures text, it remains aware of all other active patterns. If it encounters text that could match another rule, it respects that boundary, ensuring that matches don't "cross streams" or partially consume other valid patterns.

The `Verbatim` property allows you to override this behavior. When set to `true`, it disables nested match awareness for all variables within that rule. The capture becomes a "bulldozer," grabbing text based only on its own termination criteria (e.g., the next anchor or a statement separator) and ignoring all other patterns. This makes the captured content **opaque** or **verbatim**.

This property is the programmatic equivalent of using the `~` postfix modifier on a variable in a pattern string (e.g., `{content~}`).

### 🎯 Primary Use Case

`Verbatim` is essential for capturing sections of text that must be preserved exactly as-is, protecting them from other global transformation rules. This is ideal for:

*   Code blocks in documentation (`<code>...</code>`, ` ```...``` `)
*   Raw data segments
*   Pre-formatted text where internal structure must not be altered

### `Verbatim` vs. `ImmediateTransform`

This property is the direct opposite of the `ImmediateTransform` property (and the `%` postfix). 

*   **`Verbatim(true)` (`~`)**: **Prevents** nested transformations inside the capture.
*   **[ImmediateTransform(true)](/Reference/uCalcBase/Rule/ImmediateTransform) (`%`)**: **Forces** nested transformations inside the capture.

For more details on the postfix modifier, see the [Verbatim Capture ~](/Reference/Patterns/Variable-Postfix-Modifiers/Verbatim-Capture/) topic.

**Examples:**

---

## WhitespaceSensitive = [bool] - ID: 307
/doc/reference/classes/ucalc.rule/whitespacesensitive-=-[bool]/

**Description:** Gets or sets whether pattern matching for this rule treats whitespace as a significant token, overriding the transformer's default setting.

**Remarks:**

# 📏 Controlling Whitespace Significance

The `WhitespaceSensitive` property controls how a pattern rule interprets horizontal whitespace (spaces and tabs). By default, uCalc is whitespace-insensitive, offering flexibility. This property allows you to enforce strict whitespace matching for specific rules.

This per-rule setting overrides the global behavior defined on the parent [Transformer's](/Reference/uCalcBase/Transformer/DefaultRuleSet) `DefaultRuleSet`.

## ⚙️ Behavior

| Setting | Behavior |
| :--- | :--- |
| `false` (Default) | **Insensitive**. Whitespace is ignored. A space in a pattern can match any amount of horizontal whitespace in the source text, including none. The engine focuses on non-whitespace tokens. |
| `true` | **Sensitive**. Whitespace becomes a significant token. A space in the pattern must match exactly one whitespace token in the source. This is crucial for formats where indentation or column alignment matters. |

## 💡 Why uCalc? (Comparative Analysis)

This property provides a level of granular control not easily achieved with standard regular expressions.

*   **vs. Regular Expressions**: In regex, handling variable spacing requires littering patterns with `\s+` or `\s*`. uCalc's default (`false`) behavior handles this automatically, making patterns cleaner and more readable. Enabling `WhitespaceSensitive(true)` is like making spaces in your pattern behave like `\s+` in regex, but on a token level. This is a declarative switch rather than an imperative pattern change.

*   **vs. Global Flags**: Many regex engines apply case-sensitivity or multi-line options to the entire pattern. uCalc allows you to mix whitespace-sensitive and -insensitive rules within the same [Transformer](/Reference/uCalcBase/Transformer/Constructor), letting them run concurrently. This is powerful for parsing hybrid documents that might have both structured (whitespace-sensitive) and unstructured (whitespace-insensitive) sections.

**Examples:**

### Example ID: 142

**Description:** WhitespaceSensitive()

**Code:**
```pseudocode
var t = uc.NewTransformer();
var Text = "This is a test.";
var p = t.FromTo("This {words:3}", "[{words}]");

wl("Input: ", Text)
wl("Pattern: ", p.@Pattern())
wl("")

wl("3 captured tokens are in brackets")
wl("")

wl("WhitespaceSensitive = ", bool(t.@DefaultRuleSet().@WhitespaceSensitive()))
wl(t.Transform(Text))
wl("")

t.@DefaultRuleSet().@WhitespaceSensitive(true);
wl("WhitespaceSensitive = ", bool(t.@DefaultRuleSet().@WhitespaceSensitive()))
wl(t.Transform(Text))

```

**Output:**
```
Input: This is a test.
Pattern: This {words:3}

3 captured tokens are in brackets

WhitespaceSensitive = False
[is a test].

WhitespaceSensitive = True
[ is ]a test.
```

---

---

## uCalc.String - ID: 309
/doc/reference/classes/ucalc.string/

**Description:** uCalc string library class

**Remarks:**

Message to GemeniAI: The entire section under uCalc.String needs to be redone.  So, I can use additional insight from AI.

---

## Introduction - ID: 968
/doc/reference/classes/ucalc.string/introduction/

**Description:** An overview of the uCalc.String class, a mutable, token-aware string object designed for high-performance, chainable text manipulation.

**Remarks:**

# ✨ uCalc.String: The Smart String Builder

The `uCalc.String` object is a powerful, mutable string class designed for high-performance text manipulation. It goes far beyond a standard `string` or `StringBuilder`, acting as a hybrid of three components in one:

1.  **A Mutable String Builder**: Efficiently modify, append, and replace text without the performance penalty of creating new string objects for every change.
2.  **A Lightweight Transformation Engine**: Perform token-aware find-and-replace operations using a fluent, chainable API.
3.  **A List Processor**: Treat a string's contents—or the results of a search—as a collection that can be iterated, filtered, and transformed.

Its core design philosophy is to provide a rich, fluent interface for single-string operations. For managing complex sets of reusable rules or multi-pass transformations, the more powerful [uCalc.Transformer](/Reference/uCalcBase/Transformer/Constructor) is the preferred tool.

---

## ⚙️ Core Concepts

### 1. ⚡ Mutability and Performance
Unlike native `string` types in C# and other languages, which are immutable, `uCalc.String` is designed to be modified **in-place**. This makes it highly efficient for building or manipulating strings in a loop, similar to a `StringBuilder` but with far more functionality.

### 2. 🧠 Token-Aware Operations
By default, all operations (like `SubString`, `After`, and `Before`) are **token-based**, not character-based. The string is first broken down into tokens (words, numbers, symbols), and operations are performed on this stream. This provides structural awareness, safely handling nested brackets, quotes, or user-defined constructs like comments.

### 3. ⛓️ Chaining and Live Views
Methods that extract a portion of a string (e.g., [SubString](/Reference/uCalcBase/String/SubString), [After](/Reference/uCalcBase/String/After), [Between](/Reference/uCalcBase/String/Between)) do not create a disconnected copy. Instead, they return a new `uCalc.String` object that is a **live, modifiable view** into the parent.

*   Operations are chained, flowing from parent to child.
*   Modifying a child string directly modifies the content of its parent.

This architecture enables powerful, non-destructive editing pipelines.

### 4. 📜 List-like Behavior
After a [Find()](/Reference/uCalcBase/String/Find) operation or by calling methods like [ListOfTokens()](/Reference/uCalcBase/String/ListOfTokens), the `uCalc.String` object begins to act like a collection of results. Subsequent chained operations are then applied to each item in that collection, enabling powerful batch processing with methods like [Map()](/Reference/uCalcBase/String/Map).

---

## 🆚 `uCalc.String` vs. `uCalc.Transformer`

It's important to choose the right tool for the job. While both share the same underlying tokenization engine, they offer different interfaces for different tasks:

*   **[uCalc.String](/Reference/uCalcBase/String/Constructor)**: Best for fluent, single-string "one-liner" transformations. Think of it as a scripting tool for quick modifications and data extraction on a single piece of text.

*   **[Transformer](/Reference/uCalcBase/Transformer/Constructor)**: Best for building a robust, rule-based system. It excels at managing a complex set of reusable rules or performing multi-pass transformations. Think of it as a compiler for text.

---

## 📖 Class Member Reference

Below is a list of members available on the `uCalc.String` class, grouped by functionality.

### 🧭 Navigation & Extraction
These methods return a new `uCalc.String` object that is a live view into a portion of the original.

| Member | Description |
| :--- | :--- |
| [After](/Reference/uCalcBase/String/After) | Creates a live, modifiable view of the substring that follows a specified pattern match. |
| [Before](/Reference/uCalcBase/String/Before) | Creates a live, modifiable view of the substring that precedes a specified pattern match. |
| [Between](/Reference/uCalcBase/String/Between) | Creates a live, modifiable view of the substring located between two specified patterns. |
| [BetweenInclusive](/Reference/uCalcBase/String/BetweenInclusive) | Creates a live, modifiable view of the substring that includes the text between two specified patterns and the patterns themselves. |
| [StartingFrom](/Reference/uCalcBase/String/StartingFrom) | Creates a live, modifiable view of the substring that begins with and includes a specified pattern match. |
| [SubString](/Reference/uCalcBase/String/SubString) | Extracts a substring of a specified length starting at a given token position. |
| [UpTo](/Reference/uCalcBase/String/UpTo) | Returns a substring with all text up to and including the matched pattern. |

### ✍️ Modification & Transformation
These methods modify the string's content in-place or change its representation.

| Member | Description |
| :--- | :--- |
| [Find](/Reference/uCalcBase/String/Find) | Searches for occurrences of a pattern, populating the internal match list. |
| [Remove](/Reference/uCalcBase/String/Remove) | Removes all occurrences of a specified pattern from the string. |
| [Replace](/Reference/uCalcBase/String/Replace) | Replaces all occurrences of a specified pattern with a new string. |
| [ToLower](/Reference/uCalcBase/String/ToLower) | Converts the string or a specified pattern match to lowercase. |
| [ToUpper](/Reference/uCalcBase/String/ToUpper) | Converts the string or a specified pattern match to uppercase. |
| [Map](/Reference/uCalcBase/String/Map) | Applies a transformation expression to each item in the string's internal list. |
| [Transform](/Reference/uCalcBase/String/Transform) | Applies the rules of a specified `Transformer` object to this string. |

### 🧐 Inspection & State
These members return information about the string's content or state.

| Member | Description |
| :--- | :--- |
| [Text](/Reference/uCalcBase/String/Text) | Gets or sets the full text content of the string object. |
| [Count](/Reference/uCalcBase/String/Count) | Gets the number of items in the string's current view (e.g., tokens, matches, lines). |
| [Parent](/Reference/uCalcBase/String/Parent) | Retrieves the parent `uCalc.String` object from which this view was created. |
| [Root](/Reference/uCalcBase/String/Root) | Retrieves the top-level `uCalc.String` object in a chain of views. |
| [uCalc](/Reference/uCalcBase/String/uCalc) | Retrieves the parent `uCalc` instance that provides the execution context. |
| [Description](/Reference/uCalcBase/String/Description) | Gets or sets a user-defined description for the object. |

**Examples:**

### Example ID: 1273

**Description:** A practical example of parsing a value from a simple key-value pair in a configuration string.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("User: admin; Role: user; Department: Sales;"))

// Extract the text between 'Department: ' and the trailing semicolon
var department = s.Between("Department: ", ";");

wl("Department is '", department, "'")
End Using
```

**Output:**
```
Department is ' Sales'
```

---

### Example ID: 1270

**Description:** Chains `Before` and `Replace` to modify only the scheme of a URL, demonstrating the live view concept.

**Code:**
```pseudocode
NewUsing(uCalc::String, url("http://example.com"))
wl("Original URL: ", url)
// Get a view of the scheme part
var schemeView = url.Before("://");
// Modify the view
schemeView.Replace("http", "https");
// The original string is updated
wl("Modified URL: ", url)
End Using
```

**Output:**
```
Original URL: http://example.com
Modified URL: https://example.com
```

---

---

## (Constructor) - ID: 655
/doc/reference/classes/ucalc.string/-constructor/

**Description:** A high-performance, mutable, token-aware string object for complex searching, manipulation, and chained transformations.

**Remarks:**

# ✨ uCalc.String: The Smart String Builder

The `uCalc.String` object is a powerful, mutable string class designed for high-performance text manipulation. It goes far beyond a standard string or `StringBuilder`, acting as a hybrid of three components in one:

1.  **A Mutable String Builder**: Efficiently modify, append, and replace text without the performance penalty of creating new string objects for every change.
2.  **A Lightweight Transformation Engine**: Perform token-aware find-and-replace operations using a fluent, chainable API.
3.  **A List Processor**: Treat a string's contents—or the results of a search—as a collection that can be iterated, filtered, and transformed.

Its core design philosophy is to provide a rich, fluent interface for single-string operations. For managing complex sets of reusable rules or multi-pass transformations, the more powerful [uCalc.Transformer](/Reference/uCalcBase/Transformer/Constructor) is the preferred tool.

## ⚙️ Core Concepts

### 1. Mutability and Performance
Unlike native `string` types in C# and other languages, which are immutable, `uCalc.String` is designed to be modified in-place. This makes it highly efficient for building or manipulating strings in a loop.

### 2. Token-Aware Operations
By default, all operations (like [SubString](/Reference/uCalcBase/String/SubString), [After](/Reference/uCalcBase/String/After), and [Before](/Reference/uCalcBase/String/Before)) are **token-based**, not character-based. The string is first broken down into tokens (words, numbers, symbols), and operations are performed on this stream. This provides structural awareness, safely handling nested brackets, quotes, and comments.

> **Future Direction: The `View` Property**
> A planned `View` property will allow you to switch the operational context between tokens, characters, lines, bytes, and other units, providing ultimate control over how the string is processed.

### 3. Chaining and Live Views
Methods that extract a portion of a string (e.g., [SubString](/Reference/uCalcBase/String/SubString), [After](/Reference/uCalcBase/String/After), [Between](/Reference/uCalcBase/String/Between)) do not create a disconnected copy. Instead, they return a new `uCalc.String` object that is a **live, modifiable view** into the parent. 

*   Operations are chained, flowing from parent to child.
*   Modifying a child string directly modifies the content of its parent.

This architecture enables powerful, non-destructive editing pipelines.

### 4. List-like Behavior
After a [Find()](/Reference/uCalcBase/String/Find) operation or by calling methods like [ListOfTokens()](/Reference/uCalcBase/String/ListOfTokens), the `uCalc.String` object begins to act like a collection of results. Subsequent chained operations are then applied to each item in that collection, enabling powerful batch processing.

## 🪄 Shortcut Notations
`uCalc.String` supports implicit conversions, allowing it to be treated like a native string for assignment and output, which significantly reduces boilerplate code. See the [Shortcut notations](/Concepts/Shortcut-notations) topic for details.

## 🏗️ Constructor Overloads

A `uCalc.String` object can be created via its constructor or by using the [uCalc.NewString()](/Reference/uCalcBase/uCalc/NewString) factory method.

### 1. `New(uCalc::String, myString(initialValue))`
This is the most common constructor. It creates a new `uCalc.String` object in the context of the default `uCalc` instance.
*   **`initialValue`** (optional): The starting text content for the string.

### 2. `New(uCalc::String, myString(ucalcInstance, initialValue))`
Creates a new string within the context of a specific `uCalc` instance, bypassing the default. This is the preferred method when working with multiple, isolated parser environments.
*   **`ucalcInstance`**: The parent `uCalc` engine that provides context.
*   **`initialValue`** (optional): The starting text content.

### 3. `New(uCalc::String, myString(uCalc::String::Empty))`
Creates an empty placeholder handle that does not allocate significant resources. It can be assigned a real `uCalc.String` instance later.

## 🆚 Why uCalc? (Comparative Analysis)

*   **vs. `StringBuilder`**: A `StringBuilder` is for simple concatenation. `uCalc.String` adds a full, token-aware search and replace engine.
*   **vs. `Regex`**: Regex is character-based and struggles with nested or structured text. `uCalc.String` is token-aware and handles this complexity safely by default.
*   **vs. `uCalc.Transformer`**: A [Transformer](/Reference/uCalcBase/Transformer/Constructor) is for managing a complex set of reusable rules. A `uCalc.String` is for fluent, single-string "one-liner" transformations. They share the same underlying engine but offer different interfaces for different tasks.

**Examples:**

### Example ID: 1156

**Description:** A simple find-and-replace operation using the fluent, chainable API.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("The quick brown fox."))

// Replace returns the modified String object
s.Replace("brown", "red");

// Use implicit conversion to print the result
wl(s)
End Using
```

**Output:**
```
The quick red fox.
```

---

### Example ID: 1159

**Description:** Demonstrates interoperability between `Transformer` and `String` objects, and chaining methods to create nested views.

**Code:**
```pseudocode
// Create a transformer and perform a transformation
var t = uc.NewTransformer();
t.@Text("if (x > 3) y = x * 2; else if(x == 5) y = x - 1;");
t.FromTo("1", "100");
t.Transform();

// --- Interoperability and Chaining ---

var Pattern = "if ({cond})";

// 1. Create a uCalc.String from a Transformer.
// 2. Chain .After() to get a "live view" of the text after the pattern.
New(uCalc::String, s(t))
var after_first_if = s.After(Pattern);
wl(after_first_if.@Text())

// 3. Chain another .After() on the child string.
var after_second_if = after_first_if.After(Pattern);
wl(after_second_if.@Text())

// --- String to Transformer Conversion ---

// 4. Create a uCalc.String and assign it text.
New(uCalc::String, s2)
s2 = "This is a test";

// 5. Create a Transformer from the uCalc.String to use transformer-specific methods.
New(uCalc::Transformer, t2(s2))
wl(t2.@Text())
```

**Output:**
```
y = x * 2; else if(x == 5) y = x - 100;
 y = x - 100;
This is a test
```

---

### Example ID: 154

**Description:** To_uCalcString

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("if (x > 3) y = x * 2; else if(x == 5) y = x - 1;");
t.FromTo("1", "100");
t.Transform();

var Pattern = "if ({cond})";
wl([NotCpp]new [/NotCpp] uCalc::String(t).After(Pattern).@Text())
wl([NotCpp]new [/NotCpp] uCalc::String(t).After(Pattern).After(Pattern))

New(uCalc::String, s)
s = "This is a test";
wl([NotCpp]new [/NotCpp] uCalc::Transformer(s).@Text())
```

**Output:**
```
y = x * 2; else if(x == 5) y = x - 100;
 y = x - 100;
This is a test
```

---

---

## After - ID: 310
/doc/reference/classes/ucalc.string/after/

**Description:** Creates a live, modifiable view of the substring that follows a specified pattern match.

**Syntax:** After(string, int)
**Parameters:**
pattern - string - The pattern to find. The returned view will start immediately after this pattern's match.
nth - int [default = 1] - The 1-based occurrence of the pattern to find. For example, a value of 2 finds the second match.
**Return:** String - A new `uCalc.String` object that is a live, modifiable view into the portion of the parent string that comes after the specified pattern match. Returns an empty string object if the pattern is not found or if nothing follows it.
**Remarks:**

# ✂️ Extracting Text After a Pattern

The `After` method finds the `nth` occurrence of a given pattern and returns a new [uCalc.String](/Reference/uCalcBase/String/Constructor) object representing all the text that follows it. This is a fundamental tool for parsing data and is part of `uCalc.String`'s fluent, chainable API.

> **Note**: This method may be renamed to `StartAfter` in a future version for better consistency with the [Rule.StartAfter](/Reference/uCalcBase/Rule/StartAfter) property.

## ✨ The "Live View" Concept

The most important feature of this method is that it does not return a simple, disconnected substring. Instead, it returns a **live, modifiable view** into the parent string. This means:
*   Any modifications made to the child string (the returned view) will directly affect the content of the original parent string.
*   This allows for powerful, in-place editing of specific sections of a larger document without the overhead of creating and rejoining substrings.

## ⚙️ Parameters

*   **`pattern`**: The uCalc pattern to search for. This can be a simple literal or a complex pattern with variables.
*   **`nth`**: A 1-based index specifying which occurrence of the pattern to find. The default value of `1` finds the first match.

## Behavior on Failure

If the specified pattern is not found, or if nothing comes after it, the method returns an empty [uCalc.String](/Reference/uCalcBase/String/Constructor) object. No error is raised.

## 💡 Why uCalc? (Comparative Analysis)

In a standard language like C#, you would typically find the end position of a match and then create a new substring.

**C# Manual Approach:**
```csharp
string text = "ID: 12345";
string prefix = "ID: ";
int startIndex = text.IndexOf(prefix);
if (startIndex != -1)
{
    string value = text.Substring(startIndex + prefix.Length);
    // 'value' is now a new, disconnected string "12345"
}
```

This approach is imperative and creates disconnected data. `uCalc.String` provides a more powerful, declarative, and integrated solution:

**The uCalc Advantage:**
```pseudocode
New(uCalc::String, s("ID: 12345"))
var valueView = s.After("ID: "); // Returns a live view

// Modifying the view changes the original string 's'
valueView.Replace("12345", "CHANGED");
wl(s); // Output: ID: CHANGED
```

This ability to create live, chainable views is a key differentiator, enabling a more fluid and powerful style of text manipulation that is not possible with standard string libraries.

**Examples:**

### Example ID: 1163

**Description:** Extracting a value from a simple key-value pair.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("ID: 12345"))

// Get the text after the "ID: " prefix
var value = s.After("ID: ");

wl(value)
End Using
```

**Output:**
```
 12345
```

---

### Example ID: 1164

**Description:** A practical example demonstrating how to extract an error message from a log entry and then chain another operation on the result.

**Code:**
```pseudocode
NewUsing(uCalc::String, log("INFO: Task complete. ERROR: File not found."))

// Chain After() to isolate the error, then Replace() to modify it.
var errorDetails = log.After("ERROR: ").Replace("File", "Resource");

wl("Original log: ", log)      // The original string is modified in-place
wl("Modified details:", errorDetails) // The view reflects the change
End Using
```

**Output:**
```
Original log: INFO: Task complete. ERROR: Resource not found.
Modified details: Resource not found.
```

---

### Example ID: 1165

**Description:** Internal Test: Verifies behavior for patterns at the end of the string and patterns that are not found.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("A B C"))

// Case 1: Pattern is at the end. Should return an empty string.
w("After 'C': '")
w(s.After("C"))
wl("'")

// Case 2: Pattern does not exist. Should return an empty string.
w("After 'D': '")
w(s.After("D"))
wl("'")

// Case 3: Get text after the first word.
w("After 'A': '")
w(s.After("A"))
wl("'")
End Using
```

**Output:**
```
After 'C': ''
After 'D': ''
After 'A': ' B C'
```

---

### Example ID: 105

**Description:** How to extract text that appears after a specific pattern using the String.After() method.

**Code:**
```pseudocode
var(uCalc::String, s) = "This is just a test";
wl(s.After("is"))

s = "/* if else */ if (x > 100) y = x * 2; else if(x == 5) y = x - 1;";
wl(s.After("if ({cond})"))
wl(s.After("if ({cond})").After("if ({cond})"))
wl(s.After("if ({cond})", 2)) // Finds text after 2nd match (same as above)
wl(s.After("NonExistingPattern")) // Nothing to display on this line
wl("----")

```

**Output:**
```
 just a test
 y = x * 2; else if(x == 5) y = x - 1;
 y = x - 1;
 y = x - 1;

----
```

---

---

## As - ID: 852
/doc/reference/classes/ucalc.string/as/

**Syntax:** As()
**Return:**  - 
**Remarks:**

var words = MyString.As(Views.Word);
var lines = MyString.As(Views.Line);


---

## Before - ID: 315
/doc/reference/classes/ucalc.string/before/

**Description:** Creates a live, modifiable view of the substring that precedes a specified pattern match.

**Syntax:** Before(string, int)
**Parameters:**
pattern - string - The pattern to find. The returned view will contain all text up to, but not including, this pattern's match.
nth - int [default = 1] - The 1-based occurrence of the pattern to find. For example, a value of 2 finds the second match and returns all text before it.
**Return:** String - A new `uCalc.String` object that is a live, modifiable view into the portion of the parent string that comes before the specified pattern match. Returns an empty string object if the pattern is not found or is at the beginning of the string.
**Remarks:**

# ✂️ Extracting Text Before a Pattern

The `Before` method finds the `nth` occurrence of a given pattern and returns a new [uCalc.String](/Reference/uCalcBase/String/Constructor) object representing all the text that precedes it. This is a fundamental tool for parsing data and is part of `uCalc.String`'s fluent, chainable API.

> **Note**: This method may be renamed to `UpTo` in a future version for better consistency with similar methods.

## ✨ The "Live View" Concept

The most important feature of this method is that it does not return a simple, disconnected substring. Instead, it returns a **live, modifiable view** into the parent string. This means:
*   Any modifications made to the child string (the returned view) will directly affect the content of the original parent string.
*   This allows for powerful, in-place editing of specific sections of a larger document without the overhead of creating and rejoining substrings.

## ⚙️ Parameters

*   **`pattern`**: The uCalc pattern to search for.
*   **`nth`**: A 1-based index specifying which occurrence of the pattern to find. The default value of `1` finds the first match.

## Behavior on Failure

If the specified pattern is not found, or if it is found at the very beginning of the string, the method returns an empty [uCalc.String](/Reference/uCalcBase/String/Constructor) object. No error is raised.

## 💡 Why uCalc? (Comparative Analysis)

In a standard language like C#, you would typically find the starting position of a match and then create a new substring.

**C# Manual Approach:**
```csharp
string text = "user:admin";
int colonIndex = text.IndexOf(':');
if (colonIndex != -1)
{
    string key = text.Substring(0, colonIndex);
    // 'key' is now a new, disconnected string "user"
}
```

This approach is imperative and creates disconnected data. `uCalc.String` provides a more powerful, declarative, and integrated solution:

**The uCalc Advantage:**
```pseudocode
New(uCalc::String, s("http://example.com"))
var schemeView = s.Before("://"); // Returns a live view

// Modifying the view changes the original string 's'
schemeView.Replace("http", "https");
wl(s); // Output: https://example.com
```

This ability to create live, chainable views is a key differentiator, enabling a more fluid and powerful style of text manipulation that is not possible with standard string libraries. This method is the logical counterpart to [After](/Reference/uCalcBase/String/After) and is often used with [Between](/Reference/uCalcBase/String/Between).

**Examples:**

### Example ID: 1269

**Description:** Extracts the key from a simple key-value pair.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("user:admin"))
var key = s.Before(":");
wl(key)
End Using
```

**Output:**
```
user
```

---

### Example ID: 1270

**Description:** Chains `Before` and `Replace` to modify only the scheme of a URL, demonstrating the live view concept.

**Code:**
```pseudocode
NewUsing(uCalc::String, url("http://example.com"))
wl("Original URL: ", url)
// Get a view of the scheme part
var schemeView = url.Before("://");
// Modify the view
schemeView.Replace("http", "https");
// The original string is updated
wl("Modified URL: ", url)
End Using
```

**Output:**
```
Original URL: http://example.com
Modified URL: https://example.com
```

---

### Example ID: 1271

**Description:** Internal Test: Tests edge cases for patterns that are not found or are at the start of the string.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("A B C"))

// Case 1: Pattern is at the start. Should return an empty string.
w("Before 'A': '")
w(s.Before("A"))
wl("'")

// Case 2: Pattern does not exist. Should return an empty string.
w("Before 'D': '")
w(s.Before("D"))
wl("'")

// Case 3: Get text before the last word.
w("Before 'C': '")
w(s.Before("C"))
wl("'")
End Using
```

**Output:**
```
Before 'A': ''
Before 'D': ''
Before 'C': 'A B '
```

---

---

## Between - ID: 316
/doc/reference/classes/ucalc.string/between/

**Description:** Creates a live, modifiable view of the substring located between two specified patterns.

**Syntax:** Between(string, string, int, int)
**Parameters:**
startPattern - string - The pattern marking the beginning of the text to extract. The view starts immediately after this pattern.
stopPattern - string - The pattern marking the end of the text to extract. The view ends immediately before this pattern.
startNth - int [default = 1] - A 1-based index specifying which occurrence of `startPattern` to use as the starting boundary.
stopNth - int [default = 1] - A 1-based index specifying which occurrence of `stopPattern` to use as the ending boundary.
**Return:** String - A new `uCalc.String` object representing a live, modifiable view into the portion of the parent string between the specified patterns. Returns an empty string object if the patterns are not found.
**Remarks:**

# ✂️ Extracting Text Between Two Patterns

The `Between` method finds the text located between two specified patterns and returns it as a new [uCalc.String](/Reference/uCalcBase/String/Constructor) object. This is a fundamental tool for parsing structured data and is a core part of the fluent, chainable API, often used with methods like [After](/Reference/uCalcBase/String/After) and [Before](/Reference/uCalcBase/String/Before).

## ✨ The "Live View" Concept

The most important feature of this method is that it does not return a simple, disconnected substring. Instead, it returns a **live, modifiable view** into the parent string. This means:

*   Any modifications made to the child string (the returned view) will directly affect the content of the original parent string.
*   This allows for powerful, in-place editing of specific sections of a larger document without the overhead of creating and rejoining substrings.

## ⚙️ Parameters

*   **`startPattern` & `stopPattern`**: These define the boundaries of the text to be extracted. The returned view contains only the content *between* these boundaries, not including the boundaries themselves.
*   **`startNth` & `stopNth`**: These 1-based indices allow you to handle documents with repeated patterns. For example, `Between("(", ")", 2)` would find the text inside the *second* set of parentheses.

If either pattern is not found, the method returns an empty [uCalc.String](/Reference/uCalcBase/String/Constructor) object without raising an error.

## 💡 Why uCalc? (Comparative Analysis)

In a standard language like C#, extracting text between two markers requires a manual, multi-step process involving `IndexOf` and `Substring`.

**C# Manual Approach:**
```csharp
string text = "Config{value=123}";
int startIndex = text.IndexOf("{") + 1;
int endIndex = text.IndexOf("}");
if (startIndex != 0 && endIndex != -1)
{
    string value = text.Substring(startIndex, endIndex - startIndex);
    // 'value' is a new, disconnected string: "value=123"
}
```

This approach is imperative, character-based, and creates disconnected data. `uCalc.String` provides a more powerful, declarative, and integrated solution:

**The uCalc Advantage:**
```pseudocode
New(uCalc::String, s("Config{value=123}"))
var valueView = s.Between("{", "}"); // Returns a live, token-aware view

// Modifying the view changes the original string 's'
valueView.Replace("123", "CHANGED");
wl(s); // Output: Config{value=CHANGED}
```

This ability to create live, token-aware, chainable views is a key differentiator, enabling a more fluid and powerful style of text manipulation that is not possible with standard string libraries.

**Examples:**

### Example ID: 1272

**Description:** How to extract text contained within a pair of parentheses.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("Data (important) more data"))

// Get the text between the opening and closing parenthesis
var content = s.Between("(", ")");

wl(content)
End Using
```

**Output:**
```
important
```

---

### Example ID: 1273

**Description:** A practical example of parsing a value from a simple key-value pair in a configuration string.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("User: admin; Role: user; Department: Sales;"))

// Extract the text between 'Department: ' and the trailing semicolon
var department = s.Between("Department: ", ";");

wl("Department is '", department, "'")
End Using
```

**Output:**
```
Department is ' Sales'
```

---

---

## BetweenInclusive - ID: 355
/doc/reference/classes/ucalc.string/betweeninclusive/

**Description:** Creates a live, modifiable view of the substring that includes the text between two specified patterns and the patterns themselves.

**Syntax:** BetweenInclusive(string, string, int, int)
**Parameters:**
startPattern - string - The pattern marking the inclusive start of the text to extract.
endPattern - string - The pattern marking the inclusive end of the text to extract.
startNth - int [default = 1] - A 1-based index specifying which occurrence of `startPattern` to use as the starting boundary.
endNth - int [default = 1] - A 1-based index specifying which occurrence of `endPattern` to use as the ending boundary.
**Return:** String - A new `uCalc.String` object representing a live, modifiable view of the substring including the start and end patterns. Returns an empty string object if the patterns are not found.
**Remarks:**

# ✂️ `BetweenInclusive`

The `BetweenInclusive` method finds the text that starts with a given pattern and ends with another, returning the entire segment **including the boundary patterns themselves**.

This method is part of the fluent, chainable API of the [uCalc.String](/Reference/uCalcBase/String/Constructor) class.

## `Between` vs. `BetweenInclusive`

This method is the inclusive counterpart to the [Between](/Reference/uCalcBase/String/Between) method. The key difference is what they include in the result:

*   **`Between("A", "C")`**: Finds `A B C` and returns `B`.
*   **`BetweenInclusive("A", "C")`**: Finds `A B C` and returns `A B C`.

## ✨ The "Live View" Concept

Like other extraction methods on [uCalc.String](/Reference/uCalcBase/String/Constructor), this method does not return a simple, disconnected substring. Instead, it returns a **live, modifiable view** into the parent string. This means any modifications made to the returned view will directly affect the content of the original parent string, enabling powerful in-place editing.

## 💡 Why uCalc? (Comparative Analysis)

In a standard language like C#, extracting a block including its delimiters requires finding the start and end indices and then calculating the correct length for `Substring`.

**C# Manual Approach:**
```csharp
string text = "... &lt;p&gt;content&lt;/p&gt; ...";
string startTag = "&lt;p&gt;";
string endTag = "&lt;/p&gt;";
int startIndex = text.IndexOf(startTag);
int endIndex = text.IndexOf(endTag);
if (startIndex != -1 && endIndex != -1)
{
    string value = text.Substring(startIndex, (endIndex + endTag.Length) - startIndex);
    // 'value' is a new, disconnected string: "&lt;p&gt;content&lt;/p&gt;"
}
```

This code is imperative and error-prone. uCalc provides a cleaner, more declarative solution:

**The uCalc Advantage:**
```pseudocode
NewUsing(uCalc::String, s("... &lt;p&gt;content&lt;/p&gt; ..."))
var tagView = s.BetweenInclusive("&lt;p&gt;", "&lt;/p&gt;");

// 'tagView' is a live view containing "&lt;p&gt;content&lt;/p&gt;"
// Modifying it changes the original string 's'.
wl(tagView)
End Using
```

This approach is more readable, token-aware, and powerful due to the live-view architecture.

**Examples:**

### Example ID: 1275

**Description:** Extracting a parenthetical expression, including the parentheses.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("Calculate (10 * 5) and ignore this."))

// Get the text from the opening parenthesis to the closing one.
var expression = s.BetweenInclusive("(", ")");

wl(expression)
End Using
```

**Output:**
```
(10 * 5)
```

---

### Example ID: 1276

**Description:** A practical example of extracting a complete HTML tag and its content from a string.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("Some text <p>This is a paragraph.</p> more text."))

// Extract the entire paragraph tag, including its start and end tags.
var p_tag = s.BetweenInclusive("<p>", "</p>");

wl(p_tag)
End Using
```

**Output:**
```
<p>This is a paragraph.</p>
```

---

### Example ID: 1277

**Description:** Internal Test: Verifies the 'live view' behavior by modifying an extracted block and showing the change reflected in the parent string.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("root [child] end"))

// Get a live view of the block including the brackets
var view = s.BetweenInclusive("'['", "']'");

wl("Initial parent string: ", s)
wl("Initial view: ", view)

// Modify the view. The change will propagate to the parent.
view.Replace("child", "MODIFIED");

wl("Final parent string: ", s)
End Using
```

**Output:**
```
Initial parent string: root [child] end
Initial view: [child]
Final parent string: root [MODIFIED] end
```

---

---

## BracketedText - ID: 317
/doc/reference/classes/ucalc.string/bracketedtext/

**Description:** Returns the text corresponding to a bracket followed by text up to the next matching closing bracket

**Syntax:** BracketedText(int)
**Parameters:**
Index - int - nth Token Index
**Return:** String - uCalc string object
**Remarks:**

This returns the text corresponding to a bracket followed by text up to the next matching closing bracket.

---

## BracketedTextInside - ID: 318
/doc/reference/classes/ucalc.string/bracketedtextinside/

**Description:** Returns the text between a bracket and the the next matching closing bracket

**Syntax:** BracketedTextInside(int)
**Parameters:**
Index - int - nth Token Index
**Return:** String - uCalc String object
**Remarks:**

This returns the text between a bracket and the the next matching closing bracket.  Brackets themselves are not included.

---

## BracketMatch - ID: 319
/doc/reference/classes/ucalc.string/bracketmatch/

**Description:** Returns the matching bracket for the indicated token

**Syntax:** BracketMatch(int)
**Parameters:**
Index - int - nth Token index
**Return:** String - uCalc string object
**Remarks:**

This returns the matching bracket for the indicated token.  Manipulations to the returned uCalc string will be reflected in the overall string.

---

## BracketMatchTokenIndex - ID: 320
/doc/reference/classes/ucalc.string/bracketmatchtokenindex/

**Description:** Returns the nth index of the closing bracket token

**Syntax:** BracketMatchTokenIndex(int)
**Parameters:**
Index - int - nth token index
**Return:** int - Integer
**Remarks:**

Returns nth index of the closing bracket token.

---

## ChildStringOption = [ChildStringOptions] - ID: 324
/doc/reference/classes/ucalc.string/childstringoption-=-[childstringoptions]/

**Description:** Gets the option

**Remarks:**

Many functions create a new string object derived from another given object.  This option determines the persistence of previously derived objects.  The right option depends on what you want to do.  If you're looking to conserve memory, then ClearAll may be the option you need.  However, with this option, you can no longer refer to previously derived strings, otherwise the behavior will be undefined (such as crashing).  You may delay object deletetion be removing only the ones that overlap in location with the newly derived string.  The decision to delete may be delayed based on when an object is being written to.   ChildStringOptions::ClearOverlapOnWrite, allows you to have multiple overlapping views of the same parent string without any conflict.  Only when modifying a derived string are overlapped derived strings removed.  Corresponding Detach options are similar, except that instead of actually erasing an overlapping object, it is disassociated from the parent string.  It can continue to be used as an independent string without undefined behavior.  With this option, the independent strings are erased only when the parent string itself is erased.

---

## ClearDerivedStrings - ID: 326
/doc/reference/classes/ucalc.string/clearderivedstrings/

**Description:** Clears derived strings from memory

**Syntax:** ClearDerivedStrings()
**Return:** String - String object
**Remarks:**

Clears derived strings from memory.

---

## Clone - ID: 496
/doc/reference/classes/ucalc.string/clone/

**Description:** Makes an identical but separate copy of a uCalc String object

**Syntax:** Clone()
**Return:** String - New String object
---

## Compare - ID: 327
/doc/reference/classes/ucalc.string/compare/

**Description:** Compares two strings

**Syntax:** Compare(string, int, int, int)
**Parameters:**
OtherString - string - The other string to compare with
IndexA - int [default = 0] - Starting point of first string
IndexB - int [default = 0] - Starting point of next string
Length - int [default = -1] - Length
**Return:** Comparison - Returns bigger than, equal, or less than (Comparison enum)
**Remarks:**

Compares two strings

---

## Count = [int] - ID: 943
/doc/reference/classes/ucalc.string/count-=-[int]/

---

## Data - ID: 0
/doc/reference/classes/ucalc.string/data/

---

## Data() - ID: 498
/doc/reference/classes/ucalc.string/data/data-void/

**Description:** Returns the raw string data address in memory of a uCalc string object

**Syntax:** Data()
**Return:** IntPtr - 
---

## Data(IntPtr, int) - ID: 500
/doc/reference/classes/ucalc.string/data/data-intptr,-int/

**Description:** Attaches a uCalc string to a raw string address in memory

**Syntax:** Data(IntPtr, int)
**Parameters:**
StringAddress - IntPtr - Address in memory of raw string
Size - int - Number of characters
**Return:** String - 
**Remarks:**

This sets a uCalc string based on a memory address and a size.  This is faster than copying one string to another.  The original string address must remain valid when this new string is used, until this string is released or its value is changed, at which point it will no longer depend on the original raw address.

---

## DataSize - ID: 499
/doc/reference/classes/ucalc.string/datasize/

**Description:** Returns the raw size in characters of the string object

**Syntax:** DataSize()
**Return:** int - 
**Remarks:**

Returns the memory size in characters of the string object.

---

## Description = [string] - ID: 536
/doc/reference/classes/ucalc.string/description-=-[string]/

**Description:** Gets the description associated with a uCalc.String object

**Remarks:**

getter
This returns a user-defined description associated with a String object.

Every uCalc.String object can be set with a description.  It can be used for things like documentation or as a tool tip.

A description starts off as an empty string until you set it to something else.


setter
This sets a description for the given uCalc.String object.

Every uCalc.String object can be set with a description.  It can be used for things like documentation or as a tool tip.

A description starts off as an empty string until you set it to something else.

---

## Find - ID: 328
/doc/reference/classes/ucalc.string/find/

**Description:** Searches for occurences of a pattern in the string

**Syntax:** Find(string, int)
**Parameters:**
Pattern - string - Pattern
Nth - int [default = 1] - Nth match
**Return:** String - This uCalc string object
**Remarks:**

Searches for occurrences of a pattern in the string.  Once this operation is executed, you may retrieve any of the matches with Match(n).

---

## FindOtherThan - ID: 329
/doc/reference/classes/ucalc.string/findotherthan/

**Description:** Finds occurences of all text other than the matching pattern

**Syntax:** FindOtherThan(string, int)
**Parameters:**
Pattern - string - Pattern
Nth - int [default = 1] - Nth match
**Return:** String - This uCalc string object
**Remarks:**

Finds occurrences of all text other than the matching pattern.  This allows you to perform a transformation on all text other than text that matches the given pattern.

---

## Handle - ID: 330
/doc/reference/classes/ucalc.string/handle/

**Description:** Returns the handle of an object

**Syntax:** Handle()
**Return:** String - 
**Remarks:**

Mostly for internal use.

Each object has a handle, which is used to communicate with the uCalc library.  It may not have other uses cases beyond troubleshooting.

---

## Indexer[] - ID: 934
/doc/reference/classes/ucalc.string/indexer[]/

**Syntax:** Indexer[]()
**Return:**  - 
---

## List - ID: 334
/doc/reference/classes/ucalc.string/list/

**Description:** Returns a list of matches, consisting of characters, tokens, elements, statements, or lines

**Syntax:** List(StringListType)
**Parameters:**
ListType - StringListType [default = StringListType::Matches] - Type of list
**Return:** String - uCalc String object
**Remarks:**

Returns a list of consisting of matches, characters, tokens, elements, statements, or lines.

---

## ListFormat - ID: 335
/doc/reference/classes/ucalc.string/listformat/

**Description:** Sets a format for the List() function

**Syntax:** ListFormat(string, string, string, string, string, string, string)
**Parameters:**
Separator - string - Separator
Prefix - string [default = ""] - Prefix
Postfix - string [default = ""] - Postfix
UserFunc - string [default = ""] - UserFunc
Element - string [default = ""] - Element
Index - string [default = ""] - Index
Count - string [default = ""] - Count
**Return:** String - 
**Remarks:**

This sets a format that determines how the value of Str() is returned.  Separator will be inserted between each match; Prefix will be added before the string; Postfix is appended at the end of the string.  UserFunc determines how each match is displayed.  Element is the name of the variable to use in the function (x by default). Index is the name of the current match (Index by default).  Count is the number of matches (Count by default).

For instance: Given this list of matches: "a", "b", "c", "d" ListOfChars().ListFormat(", ", "{", "}", "$'{Index} of {Count}:{x}'").Str() would return: {1 of 4:a, 2 of 4:b, 3 of 4:c, 4 of 4:d}

---

## ListFunction - ID: 336
/doc/reference/classes/ucalc.string/listfunction/

**Description:** Sets the formatting function for displaying the elements of a list

**Syntax:** ListFunction(string, string, string, string)
**Parameters:**
UserFunc - string - UserFunc
Element - string [default = ""] - Element
Index - string [default = ""] - Index
MatchCount - string [default = ""] - MatchCount
**Return:** String - uCalc String object
**Remarks:**

Text that is returned as a list can have a prefix, postfix, and separators between elements.  A list of items within curly braces might have an open curly brace as prefix, a comma as delimiter, and a closing curly brace as postfix. See ListFormat().

**Examples:**

---

## ListPostfix - ID: 339
/doc/reference/classes/ucalc.string/listpostfix/

**Description:** Sets the postfix that is appended at the end of a list

**Syntax:** ListPostfix(string)
**Parameters:**
Postfix - string - Postfix that will be appended at the end of a list
**Return:** String - Current uCalc String object
**Remarks:**

Text that is returned as a list can have a prefix, postfix, and separators between elements.  A list of items within curly braces might have an open curly brace as prefix, a comma as delimiter, and a closing curly brace as postfix.

---

## ListPrefix - ID: 340
/doc/reference/classes/ucalc.string/listprefix/

**Description:** Sets the prefix that is inserted at the start of lists

**Syntax:** ListPrefix(string)
**Parameters:**
Prefix - string - Prefix that will be inserted at the start of a list
**Return:** String - Current uCalc String object
**Remarks:**

Text that is returned as a list can have a prefix, postfix, and separators between elements.  A list of items within curly braces might have an open curly brace as prefix, a comma as delimiter, and a closing curly brace as postfix.

---

## ListSeparator - ID: 341
/doc/reference/classes/ucalc.string/listseparator/

**Description:** Sets the separator that will delimite the elements of a list

**Syntax:** ListSeparator(string)
**Parameters:**
Separator - string - Separator that will delimite each element of a list
**Return:** String - Current uCalc String object
**Remarks:**

Text that is returned as a list can have a prefix, postfix, and separators between elements.  A list of items within curly braces might have an open curly brace as prefix, a comma as delimiter, and a closing curly brace as postfix.

---

## Map - ID: 311
/doc/reference/classes/ucalc.string/map/

**Description:** Applies a transformation expression to each item in the string's internal list, creating a new list of results.

**Syntax:** Map(string, string)
**Parameters:**
expression - string - The expression string to evaluate for each item. The item's value will be available in the variable specified by `variableName`.
variableName - string [default = ""] - The name of the variable within the `expression` that will hold the value of the current item being processed. Defaults to 'x'.
**Return:** String - Returns the current `String` object, now representing the new list of transformed results, to allow for method chaining.
**Remarks:**

The `Map` method is a powerful functional programming tool that transforms each item in a [uCalc.String's](/Reference/uCalcBase/String/Constructor) internal list. This method is used when a `uCalc.String` object is in a "list state," which occurs after operations like [Find()](/Reference/uCalcBase/String/Find) or [ListOfTokens()](/Reference/uCalcBase/String/ListOfTokens).

It iterates through each item in the list, executes a given `expression` on it, and replaces the original list with the new list of transformed results.

### How It Works

For each item in the list, the `Map` method:
1.  Assigns the item's value to a temporary variable (named `x` by default, or as specified by `variableName`).
2.  Evaluates the provided `expression` string in the context of that variable.
3.  Collects the result of each evaluation.

After iterating through all items, the internal list within the `uCalc.String` object is replaced by this new collection of results.

### Built-in Context Variables

Inside the `expression`, you have access to several context-aware variables:
*   **The item variable** (default `x`): The value of the current item being processed.
*   `Index`: The zero-based index of the current item in the list.
*   `Count`: The total number of items in the list.

### 💡 Why uCalc? (Comparative Analysis)

`Map` is a classic higher-order function found in many languages, but uCalc's implementation is unique due to its dynamic, string-based nature.

*   **vs. C# LINQ `Select`**:
    ```csharp
    var numbers = new List<int> { 1, 2, 3 };
    var squared = numbers.Select(x => x * x);
    ```
    LINQ is compile-time and type-safe. uCalc's `Map` is **dynamic at runtime**. The transformation logic is provided as a string, which can be constructed or loaded from user input, configuration files, or other dynamic sources.

*   **vs. JavaScript `Array.prototype.map`**:
    ```javascript
    let numbers = [1, 2, 3];
    let squared = numbers.map(x => x * x);
    ```
    While also dynamic, JavaScript's `map` operates on arrays of native types. uCalc's `Map` operates on an internal list of tokenized string segments, giving it a more powerful context for text manipulation.

**Examples:**

---

## MatchIndexAtChar - ID: 344
/doc/reference/classes/ucalc.string/matchindexatchar/

**Description:** Returns the index of the nth match where a character location is

**Syntax:** MatchIndexAtChar(int)
**Parameters:**
Index - int - Index of the character who's match index you want
**Return:** int - Integer
**Remarks:**

Returns the index of the nth match where a character location is

---

## MatchIndexAtToken - ID: 345
/doc/reference/classes/ucalc.string/matchindexattoken/

**Description:** Returns the index of the nth match where a token location is

**Syntax:** MatchIndexAtToken(int)
**Parameters:**
Index - int - Index of the token who's match index you want
**Return:** int - Integer
**Remarks:**

Returns the index of the nth match where a token location is

---

## MemoryIndex = [int] - ID: 610
/doc/reference/classes/ucalc.string/memoryindex-=-[int]/

**Description:** Returns the unique index value associated with the object

**Remarks:**

Mostly for internal use.

Each object has an integer index value that is unique to the object within the class.  Unlike the [topic: Handle] value that may change each time you run uCalc, the MemoryIndex value is predictable.

This function may not have other uses cases beyond troubleshooting.

---

## NonMatches - ID: 346
/doc/reference/classes/ucalc.string/nonmatches/

**Description:** Returns a string with a list of matches consisting of everything other than occurences of the Find pattern.

**Syntax:** NonMatches()
**Return:** String - uCalc String object
**Remarks:**

Returns a string with a list of matches consisting of everything other than occurences of the Find pattern.

---

## Owned - ID: 744
/doc/reference/classes/ucalc.string/owned/

**Syntax:** Owned()
**Return:** String - 
**Remarks:**

[Revisit]

---

## Parent = [String] - ID: 347
/doc/reference/classes/ucalc.string/parent-=-[string]/

**Description:** Returns the immediate parent of the current string

**Remarks:**

Returns the immediate parent of the current string.

---

## Populate - ID: 348
/doc/reference/classes/ucalc.string/populate/

**Description:** Creates a string from a programmatically constructed list

**Syntax:** Populate(double, double, string, double, string, string, string, string)
**Parameters:**
first - double - first
last - double - last
expression - string - expression
Step - double [default = 1] - Step
Condition - string [default = ""] - Condition
VarIndex - string [default = ""] - VarIndex
VarFirst - string [default = ""] - VarFirst
VarLast - string [default = ""] - VarLast
**Return:** String - uCalc string object
**Remarks:**

For example: Populate(2, 5, "$'{Index}:{First}:{Last} etc.'").Str(); would return: "2:2:5 etc.3:2:5 etc.4:2:5 etc.5:2:5 etc."

---

## Release - ID: 349
/doc/reference/classes/ucalc.string/release/

**Description:** Releases a uCalc string

**Syntax:** Release()
**Return:** void - 
**Remarks:**

This releases a uCalc string from memory along with all the objects dependent on it.

---

## Remove - ID: 350
/doc/reference/classes/ucalc.string/remove/

**Description:** Removes occurrences of a pattern in the string

**Syntax:** Remove(string)
**Parameters:**
From_ - string - pattern of occurences to remove from a string
**Return:** String - uCalc String
**Remarks:**

Removes occurrences of a pattern in the string.

---

## Replace - ID: 351
/doc/reference/classes/ucalc.string/replace/

**Description:** Replaces occurences of a pattern with something else

**Syntax:** Replace(string, string)
**Parameters:**
From_ - string - patter of occurence to match
To_ - string - replacement of occurence
**Return:** String - uCalc String object
**Remarks:**

Replaces occurrences of a pattern with something else.

**Examples:**

### Example ID: 227

**Description:** Demonstrating in-place modification with uCalc.String.Replace

**Code:**
```pseudocode
var(uCalc::String, text) = "This is foo 1, foo 2, Foo 3, foo 4";
text.After("1").Before("3").Replace("foo", "bar"); // 'text' is now modified
wl(text)
```

**Output:**
```
This is foo 1, bar 2, bar 3, foo 4
```

---

---

## Root = [String] - ID: 352
/doc/reference/classes/ucalc.string/root-=-[string]/

**Description:** Returns the root string of the current string

**Remarks:**

Returns the root string of the current string

---

## SkipOver - ID: 353
/doc/reference/classes/ucalc.string/skipover/

**Description:** Skips over a pattern

**Syntax:** SkipOver(string)
**Parameters:**
Pattern - string - Pattern
**Return:** String - uCalc String object
**Remarks:**

Skips over a pattern, preventing a search within it for a match.

---

## StartingFrom - ID: 354
/doc/reference/classes/ucalc.string/startingfrom/

**Description:** Creates a live, modifiable view of the substring that begins with and includes a specified pattern match.

**Syntax:** StartingFrom(string, int)
**Parameters:**
startPattern - string - The pattern marking the beginning of the substring. The returned view will include the text of this match.
occurrence - int [default = 1] - The 1-based occurrence of the pattern to find. For example, a value of 2 finds the second match.
**Return:** String - A new `uCalc.String` object that is a live, modifiable view into the portion of the parent string that starts with the specified pattern match. Returns an empty string object if the pattern is not found.
**Remarks:**

# ✂️ Extracting Text From a Pattern (Inclusive)

The `StartingFrom` method finds the `nth` occurrence of a given pattern and returns a new [uCalc.String](/Reference/uCalcBase/String/Constructor) object representing all the text from that point to the end of the string. This is a fundamental tool for parsing data and is part of `uCalc.String`'s fluent, chainable API.

## `StartingFrom` vs. `After`: The Inclusive Advantage

This method's key distinction is its **inclusive** behavior. The returned substring *includes* the text of the pattern match itself.

*   **`StartingFrom("A")`** on `"A B C"` returns `"A B C"`.
*   **[`After("A")`](/Reference/uCalcBase/String/After)** on `"A B C"` returns `" B C"`.

Choose `StartingFrom` when you need the delimiter as part of the result, and `After` when you only need what follows it.

## ✨ The "Live View" Concept

The most important feature of this method is that it does not return a simple, disconnected substring. Instead, it returns a **live, modifiable view** into the parent string. This means:
*   Any modifications made to the child string (the returned view) will directly affect the content of the original parent string.
*   This allows for powerful, in-place editing of specific sections of a larger document without the overhead of creating and rejoining substrings.

## 💡 Why uCalc? (Comparative Analysis)

In a standard language like C#, you would typically find the starting position of a match and then create a new substring.

**C# Manual Approach:**
```csharp
string text = "ID: 12345";
string prefix = "ID: ";
int startIndex = text.IndexOf(prefix);
if (startIndex != -1)
{
    string value = text.Substring(startIndex);
    // 'value' is now a new, disconnected string "ID: 12345"
}
```

This approach is imperative and creates disconnected data. `uCalc.String` provides a more powerful, declarative, and integrated solution:

**The uCalc Advantage:**
```pseudocode
New(uCalc::String, s("ID: 12345"))
var valueView = s.StartingFrom("ID:"); // Returns a live view

// Modifying the view changes the original string 's'
valueView.Replace("12345", "CHANGED");
wl(s); // Output: ID: CHANGED
```

This ability to create live, chainable views is a key differentiator, enabling a more fluid and powerful style of text manipulation that is not possible with standard string libraries.

**Examples:**

### Example ID: 1278

**Description:** A simple example extracting the latter part of a sentence starting from a specific word.

**Code:**
```pseudocode
NewUsing(uCalc::String, s("This is just a test"))

// Returns a view from 'just' to the end
var result = s.StartingFrom("just");

wl(result)
End Using
```

**Output:**
```
just a test
```

---

### Example ID: 1279

**Description:** Extracts all log entries from the second 'ERROR' onwards, demonstrating how the `occurrence` parameter skips initial matches.

**Code:**
```pseudocode
NewUsing(uCalc::String, log("INFO: OK. ERROR: Fail 1. INFO: OK. ERROR: Fail 2."))

// Find the second occurrence of "ERROR" and get everything after it.
var remainingLog = log.StartingFrom("ERROR", 2);

wl(remainingLog)
End Using
```

**Output:**
```
ERROR: Fail 2.
```

---

---

## SubString - ID: 359
/doc/reference/classes/ucalc.string/substring/

**Description:** Returns substring

**Syntax:** SubString(int, int)
**Parameters:**
StartPos - int - Starting position
Length - int [default = -1] - Length of substring
**Return:** String - uCalc String object
**Remarks:**

Returns a substring of the current string.

Note: the StartPos and Length parameters are in terms of tokens, not characters.

---

## Text = [string] - ID: 860
/doc/reference/classes/ucalc.string/text-=-[string]/

**Remarks:**

This retrieves the string value associated with a uCalc String object. If no argument is passed then the entire string is returned. Use Str(n) when you just want the string representation of a match. Use Match(n) when you want uCalc String Object that you can manipulate further.

This assigns a new string to the uCalc String object.


The Text property syntax is optional.  It's presence can be infered

if `s` is a uCalc.String, you can do `s.Text = "abc"; result = s.Text` can be written as `s = "abc"; result = s`.



**Examples:**

### Example ID: 154

**Description:** To_uCalcString

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("if (x > 3) y = x * 2; else if(x == 5) y = x - 1;");
t.FromTo("1", "100");
t.Transform();

var Pattern = "if ({cond})";
wl([NotCpp]new [/NotCpp] uCalc::String(t).After(Pattern).@Text())
wl([NotCpp]new [/NotCpp] uCalc::String(t).After(Pattern).After(Pattern))

New(uCalc::String, s)
s = "This is a test";
wl([NotCpp]new [/NotCpp] uCalc::Transformer(s).@Text())
```

**Output:**
```
y = x * 2; else if(x == 5) y = x - 100;
 y = x - 100;
This is a test
```

---

---

## TokenIndexAtChar - ID: 363
/doc/reference/classes/ucalc.string/tokenindexatchar/

**Description:** Returns the index of the token that contains the indicated character

**Syntax:** TokenIndexAtChar(int)
**Parameters:**
CharacterPosition - int - Character position
**Return:** int - Integer
**Remarks:**

Returns the index of the token that contains the indicated character.

---

## ToLower - ID: 365
/doc/reference/classes/ucalc.string/tolower/

**Description:** Changes occurences of a pattern to lower case

**Syntax:** ToLower(string, int)
**Parameters:**
Pattern - string [default = ""] - Pattern
Nth - int [default = 1] - nth occrence of pattern
**Return:** String - uCalc String object
**Remarks:**

Changes occurrences of a pattern to lower case.

---

## ToUpper - ID: 366
/doc/reference/classes/ucalc.string/toupper/

**Description:** Changes occurences of a pattern to upper case

**Syntax:** ToUpper(string, int)
**Parameters:**
Pattern - string [default = ""] - Pattern
Nth - int [default = 1] - nth occrence of pattern
**Return:** String - uCalc String object
**Remarks:**

Changes occurrences of a pattern to upper case.

---

## uCalc = [uCalc] - ID: 539
/doc/reference/classes/ucalc.string/ucalc-=-[ucalc]/

**Description:** Returns the uCalc object this String belongs to

---

## UpTo - ID: 369
/doc/reference/classes/ucalc.string/upto/

**Description:** Returns a substring with all text up to and including the matched pattern

**Syntax:** UpTo(string, int)
**Parameters:**
Pattern - string - Pattern to match
Nth - int [default = 1] - nth occurence
**Return:** String - uCalc String object
**Remarks:**

Returns all text up to and including the matched pattern.  By default it goes up to the first occurence of a match, but you may elect to have it go up to the nth occurence.

---

## uCalc.Tokens - ID: 370
/doc/reference/classes/ucalc.tokens/

**Description:** Class for collection of tokens

---

## Introduction - ID: 969
/doc/reference/classes/ucalc.tokens/introduction/

**Description:** Manages the collection of lexical rules (tokens) that define how the parser breaks input strings into meaningful units.

**Remarks:**

# ⚙️ The Tokens Class: The Lexical Engine

The `Tokens` class is the configuration object for uCalc's lexical analyzer, or **tokenizer**. It is the heart of what makes uCalc a **token-aware** engine, providing a powerful and dynamic alternative to traditional character-based tools like regular expressions. This collection defines the set of rules that the parser uses to break a raw input string into a stream of meaningful units—such as words, numbers, operators, and string literals—before any pattern matching or evaluation occurs.

--- 

## 🧠 The Core of Token-Awareness

The most significant advantage of uCalc's parsing model is its foundation in tokenization. This provides a structural understanding of text that character-based tools lack.

*   **Regex is character-aware**: It sees `rate = "rate"` as a flat stream of characters and can easily make incorrect changes.
*   **uCalc is token-aware**: The `Tokens` collection defines rules that first identify `rate` as an `Alphanumeric` token, `=` as a `Reducible` (operator) token, and `"rate"` as a single, atomic `Literal` (string) token. This structural awareness prevents parsing and transformation logic from accidentally corrupting the content of string literals or user-defined constructs like comments.

## 🚀 Dynamic and Configurable at Runtime

Unlike static parser generators like ANTLR or Flex/Bison, where token rules are defined in external grammar files and compiled into the application, uCalc's token set is a live, programmable object. Using the methods on this class, you can add, remove, or modify token definitions at runtime, without any external tools or recompilation. This allows your application to adapt its own syntax on the fly, a key feature for building user-configurable Domain-Specific Languages (DSLs).

## 🥇 Precedence is Key (LIFO)

Token definitions are evaluated in a **Last-In, First-Out (LIFO)** order. The most recently added token definition is checked first, giving it the highest precedence. This is crucial for resolving ambiguity. For example, to correctly parse a language with keywords, you should define the specific keywords (like `if`, `else`) *after* you define the general-purpose identifier token (`{@Alphanumeric}`). This ensures that `if` is matched as a keyword, not just as a generic word.

---

## 📚 Member Overview

The following methods and properties are available for managing a token collection.

| Member | Description |
| :--- | :--- |
| [`Add`](/Reference/uCalcBase/Tokens/Add) | Defines a new lexical token using a regular expression or imports an existing token definition. |
| [`At`](/Reference/uCalcBase/Tokens/At) | Retrieves the token definition (as an `Item`) at a specific zero-based index in the precedence list. |
| [`ByName`](/Reference/uCalcBase/Tokens/ByName) | Retrieves a token definition by its unique name (e.g., `_token_alphanumeric`). |
| [`ByType`](/Reference/uCalcBase/Tokens/ByType) | Retrieves token definitions based on their lexical category (e.g., `TokenType::Literal`). |
| [`Clear`](/Reference/uCalcBase/Tokens/Clear) | Removes all token definitions from the collection. |
| [`ContextSwitch`](/Reference/uCalcBase/Tokens/ContextSwitch) | Dynamically swaps the active token set when a start pattern is matched, until an end pattern is found. |
| [`Count`](/Reference/uCalcBase/Tokens/Count) | Gets the total number of token definitions in the collection. |
| [`Description`](/Reference/uCalcBase/Tokens/Description) | Gets or sets a user-defined text description for the token collection. |
| [`IndexOf`](/Reference/uCalcBase/Tokens/IndexOf) | Gets the zero-based precedence index of a specific token definition. |
| [`Insert`](/Reference/uCalcBase/Tokens/Insert) | Adds a new token definition at a specific index, providing explicit control over its precedence. |
| [`Remove`](/Reference/uCalcBase/Tokens/Remove) | Removes a specific token definition from the collection at runtime. |
| [`uCalc`](/Reference/uCalcBase/Tokens/uCalc) | Retrieves the parent `uCalc` instance that owns this token collection. |

**Examples:**

### Example ID: 1006

**Description:** Defines a C-style line comment token (`//...`) and categorizes it as whitespace so it is ignored by the parser.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// By default, a comment would cause a syntax error.
w("Before: ")
wl(uc.EvalStr("10 + 5 // Add 5"))

// Add a new token definition for C-style comments.
// The regex `//.*` matches from '//' to the end of the line.
// We classify it as Whitespace so the parser skips it.
uc.@ExpressionTokens().Add("//.*", TokenType::Whitespace);

w("After:  ")
wl(uc.EvalStr("10 + 5 // Add 5"))
```

**Output:**
```
Before: Undefined identifier
After:  15
```

---

### Example ID: 1046

**Description:** Practical: Demonstrates how removing the token for single-quoted strings causes the parser to treat the quote and its contents as individual generic tokens.

**Code:**
```pseudocode
// This example removes the single-quoted string token.
New(uCalc::Transformer, t)
var(string, txt) = "This is a test, 'This is a test'";
t.FromTo("{token:1}", "<{@Self}>");

wl("--- Before Removing Token ---")
// Initially, 'This is a test' is treated as a single token.
wl(t.Transform(txt).@Text())

// Now, find and remove the token definition for single-quoted strings.
var singleQuoteToken = t.@Tokens().ByName("_token_string_singlequoted");
t.@Tokens().Remove(singleQuoteToken);

// Re-run the transform. The text must be set again to be re-tokenized.
t.@Text(txt);
wl("")
wl("--- After Removing Token ---")
// Now, the single quote is a generic token, as are the words inside it.
wl(t.Transform().@Text())
```

**Output:**
```
--- Before Removing Token ---
<This> <is> <a> <test><,> <'This is a test'>

--- After Removing Token ---
<This> <is> <a> <test><,> <'><This> <is> <a> <test><'>
```

---

### Example ID: 1364

**Description:** Returns the default list of tokens (index, description, name, regex) in a transformer

**Code:**
```pseudocode
var t = uc.NewTransformer();
wl("Token Count: ", t.@Tokens().@Count())
wl("")
wl("Index  Type  Name: regex")
wl("========================")

foreach (var token in t.@Tokens())
   w(t.@Tokens().IndexOf(token))
   wl("  ", token.@Description(), "  ", token.@Name(), ": ", token.@Regex())
end for
```

**Output:**
```
Token Count: 27

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
```

---

---

## (Constructor) - ID: 656
/doc/reference/classes/ucalc.tokens/-constructor/

**Remarks:**

Tokens are generated as part of a Transformer or String object and should not be constructed independently.

---

## Add - ID: 371
/doc/reference/classes/ucalc.tokens/add/

---

## Add(Item) - ID: 372
/doc/reference/classes/ucalc.tokens/add/add-item/

**Description:** Imports a pre-existing token definition from an Item object into the current token collection.

**Syntax:** Add(Item)
**Parameters:**
tokenItem - Item - The `Item` object representing the token definition to be imported. This item must have been created by a previous call to an `Add` method.
**Return:** Tokens - Returns the current `Tokens` object to allow for a fluent, chainable interface.
**Remarks:**

# ♻️ Reusing Token Definitions

The `Add(Item)` method imports a pre-existing, fully configured token definition into the current token collection. This is a cornerstone of reusability, allowing you to define a complex token once and share it across multiple [Transformer](/Reference/uCalcBase/Transformer/Constructor) or [String](/Reference/uCalcBase/String/Constructor) objects.

This promotes the **DRY (Don't Repeat Yourself)** principle for lexical rules. Instead of re-creating a custom comment style or a specific literal format for every new parser, you can define it once, get its [Item](/Reference/uCalcBase/Item/Constructor) handle, and import it wherever needed.

### ⚙️ How It Works

This method takes an [Item](/Reference/uCalcBase/Item/Constructor) object that represents a token and adds a reference to that token's definition to the current [Tokens](/Reference/uCalcBase/Tokens/Constructor) list. The imported token inherits the precedence of a newly added token (i.e., it is checked first) unless a different insertion point is specified in another overload.

### Prerequisites
*   The `tokenItem` must be a valid token definition, typically created by a previous call to another `Add` overload (e.g., [pseudocode]`uc.Tokens().Add(regex, type)`).
*   The token being imported must belong to the **same parent [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance**. You cannot share token definitions between different, isolated `uCalc` engine instances.

### 💡 Comparative Analysis

Without this method, sharing a token definition would require you to manually extract the regex pattern, token type, and other properties from the original token and pass them to the regex-based `Add` method again.

**Manual (Verbose) Approach:**
```pseudocode
// Assume 'originalToken' is an Item from another Tokens collection.
var regex = originalToken.Regex();
var type = originalToken.TypeOfToken();
// ... get other properties ...
newTokens.Add(regex, type, ...);
```

**Using `Add(Item)` (Clean & Efficient):**
```pseudocode
newTokens.Add(originalToken);
```

This approach is not only cleaner but also ensures that all of the token's properties (like its data type or `QuotedText` flag) are correctly carried over without risk of error.

**Examples:**

### Example ID: 1003

**Description:** A simple demonstration of defining a token in one transformer and reusing it in another.

**Code:**
```pseudocode
New(uCalc::Transformer, t1)
New(uCalc::Transformer, t2)

// Define a custom token in the first transformer
var customToken = t1.@Tokens().Add("###", TokenType::Generic);

// Import the token definition into the second transformer
t2.@Tokens().Add(customToken);
t2.FromTo("###", "MATCH");

wl("t2 can now find '###': ", t2.Transform("Test ### Test"))
```

**Output:**
```
t2 can now find '###': Test MATCH Test
```

---

### Example ID: 1004

**Description:** Shows how importing a comment token definition can prevent find-and-replace rules from incorrectly modifying text inside comments.

**Code:**
```pseudocode
// Create a transformer with a custom comment token definition
New(uCalc::Transformer, t_source)
var commentToken = t_source.@Tokens().Add([verbatim]/\*([\s\S]*?)\*/[/verbatim], TokenType::Whitespace);
commentToken.@Description("C-style block comment");

// Create a second transformer that will do replacements
New(uCalc::Transformer, t_replacer)
t_replacer.FromTo("secret", "REDACTED");

var sourceText = "a secret /* contains another secret */ value";

wl("--- Before Importing Comment Token ---")
// Without knowing about comments, t_replacer incorrectly modifies the text inside the comment.
wl(t_replacer.Transform(sourceText))
wl("")

wl("--- After Importing Comment Token ---")
// Import the comment token definition. Now, the comment block is treated as a single whitespace token.
t_replacer.@Tokens().Add(commentToken);
// The transformer must be reset with the original text for the new token to apply.
t_replacer.@Text(sourceText); 
wl(t_replacer.Transform())
```

**Output:**
```
--- Before Importing Comment Token ---
a REDACTED /* contains another REDACTED */ value

--- After Importing Comment Token ---
a REDACTED /* contains another secret */ value
```

---

### Example ID: 163

**Description:** Token Add(ExistingToken)

**Code:**
```pseudocode

var t1 = uc.NewTransformer();
var CommentRegex = [verbatim]/\*([\s\S]*?)\*/[/verbatim];
var WhitespaceToken = t1.@Tokens().Add(CommentRegex, TokenType::Whitespace);
WhitespaceToken.@Description("Treats text between /* and */ as whitespace");

var txt = "a b, a /* comment a b */ b, a x b, ab, a   b, a, b";

var t2 = uc.NewTransformer();
t2.FromTo("a b", "<{@Self}>");
t2.Transform(txt);
wl(t2)

// The token defined in the other transformer (WhitespaceToken) is imported into this one.
// Now, everything between /* and */ will be treated as whitespace
t2.@Tokens().Add(WhitespaceToken);
wl(t2.Transform(txt))
```

**Output:**
```
<a b>, a /* comment <a b> */ b, a x b, ab, <a   b>, a, b
<a b>, <a /* comment a b */ b>, a x b, ab, <a   b>, a, b
```

---

### Example ID: 166

**Description:** Defining quoted text 

**Code:**
```pseudocode

// In example we'll define quoted text using < and > as
// surrounding quotes.  Singe and double quotes ' and " 
// are already defined by default.  This is just an example.

// Quoted text must be defined as TokenType.Literal
// The last argument, 1, means that the literal part of the match will
// be the part of the regex found int the first parenthesis (here's
// there's only one set of parenthesis).

var t = uc.NewTransformer();
var SpecialQuotes = t.@Tokens().Add("<([^>]*)>", TokenType::Literal, "", 1);
SpecialQuotes.SetDataType(BuiltInType::String);
SpecialQuotes.IsProperty(ItemIs::QuotedText, true);

t.Pattern("{token:1}");
wl(t.Filter("abc <some quoted text> xyz 123.456 + 25e2").@Matches().@Text())
wl("")

// Based on the definition, the part within < and > is the literal part
// passed to the string + operator used by EvalStr

uc.@ExpressionTokens().Add(SpecialQuotes);
wl(uc.EvalStr("<some quoted text> + < plus more>"));
```

**Output:**
```
abc
<some quoted text>
xyz
123.456
+
25e2

some quoted text plus more
```

---

---

## Add(string, TokenType, string, int, RegExGrammar, int) - ID: 373
/doc/reference/classes/ucalc.tokens/add/add-string,-tokentype,-string,-int,-regexgrammar,-int/

**Description:** Defines a new lexical token using a regular expression and adds it to the collection.

**Syntax:** Add(string, TokenType, string, int, RegExGrammar, int)
**Parameters:**
regexPattern - string - The regular expression pattern that defines the token.
tokenType - TokenType [default = TokenType::Generic] - The lexical category of the token, which determines its parsing behavior.
closingBracketRegex - string [default = ""] - An optional regex pattern for the corresponding closing bracket if this token is an opening bracket.
subMatchGroup - int [default = 0] - The 1-based index of a capture group within the regex. If greater than 0, the content of this group is used as the token's value instead of the entire match.
regexGrammar - RegExGrammar [default = RegExGrammar::Default] - The regular expression grammar to use for parsing the pattern.
insertionIndex - int [default = -1] - The position in the token list to insert the new definition. The default (-1) adds it to the end, giving it the highest precedence. Use 0 to give it the lowest precedence.
**Return:** Item - Returns the newly created token as an [Item](/reference/ucalcbase/item) object, which can be used to further configure its properties (e.g., setting its DataType).
**Remarks:**

The `Add` method is the core of uCalc's dynamic lexical analysis engine. It allows you to define new tokens—the fundamental building blocks of a language—at runtime using regular expressions.

### ⚙️ Core Concepts

#### Token Precedence & Insertion
By default, tokens are evaluated in a Last-In, First-Out (LIFO) order. The most recently added token is checked first, giving it the highest precedence. You can override this behavior using the `insertionIndex` parameter:
- **-1 (Default)**: Appends the token, giving it the **highest precedence**.
- **0**: Inserts the token at the beginning, giving it the **lowest precedence**.

#### Token Types (`tokenType`)
A token's `tokenType` dictates its role in the parser. For a full list, see the [TokenType](/reference/enums/tokentype) enum.

| Type | Behavior | Example |
| :--- | :--- | :--- |
| `Generic` | A standard symbol with no special behavior. | . |
| `Literal` | Represents a data value like a number or string. | The regex `[0-9]+` to match numbers. |
| `Whitespace`| Ignored by the parser. | The regex `[ \t]+` to skip spaces. |
| `Bracket` | Marks the start of a nested group. | The regex `\(` for an opening parenthesis. |

### Specialized Token Definitions

#### Defining Bracket Pairs
To define a bracket pair (e.g., `<` and `>`), provide the opening bracket's regex as `regexPattern` and the closing bracket's regex in the `closingBracketRegex` parameter. This allows patterns with [BracketSensitive](/reference/ucalcbase/rule/bracketsensitive) enabled to correctly handle nested structures.

#### Defining Literals (Numbers, Strings, etc.)
Creating a token that can be used in an expression (like a number or string) is a multi-step process:
1.  Call `Add()` with `tokenType` set to `TokenType::Literal`.
2.  On the returned [Item](/reference/ucalcbase/item) object, call the [`.DataType()`](/reference/ucalcbase/item/datatype) method to assign a uCalc [DataType](/reference/ucalcbase/datatype) (e.g., `uc.DataTypeOf("Double")`).
3.  For quoted string literals, you must also set the `ItemIs::QuotedText` property to `true` on the [Item](/reference/ucalcbase/item).

#### Capturing Sub-Matches (`subMatchGroup`)
If your regex contains capture groups (parentheses), you can use the `subMatchGroup` parameter to make the token's value equal to a specific group's content instead of the entire match. For example, to create a string literal token that automatically strips the surrounding quotes, you could use the pattern `"([^"]*)"` and set `subMatchGroup` to `1`.

### 💡 Why uCalc? (Comparative Analysis)

*   **vs. Static Lexer Generators (ANTLR, Flex/Bison)**: Traditional compiler tools require you to define token rules in separate grammar files, generate source code, and recompile your application to see changes. This process is static and happens at compile-time. uCalc's approach is fully **programmatic and dynamic**. You can add, remove, or modify token definitions at runtime, from within your code, without any external tools or recompilation. This provides unparalleled flexibility for creating adaptable and user-extendable Domain-Specific Languages (DSLs).

*   **vs. Ad-hoc Regex & String Splitting**: Manually tokenizing an input string is brittle and often fails to handle language context correctly (e.g., distinguishing an operator from a character inside a string). uCalc provides a robust, structured framework for tokenization, and the `Add` method is your entry point for configuring that framework.

**Examples:**

### Example ID: 1006

**Description:** Defines a C-style line comment token (`//...`) and categorizes it as whitespace so it is ignored by the parser.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// By default, a comment would cause a syntax error.
w("Before: ")
wl(uc.EvalStr("10 + 5 // Add 5"))

// Add a new token definition for C-style comments.
// The regex `//.*` matches from '//' to the end of the line.
// We classify it as Whitespace so the parser skips it.
uc.@ExpressionTokens().Add("//.*", TokenType::Whitespace);

w("After:  ")
wl(uc.EvalStr("10 + 5 // Add 5"))
```

**Output:**
```
Before: Undefined identifier
After:  15
```

---

### Example ID: 342

**Description:** Extends the parser to support C-style `0x` hex and `0b` binary notations using a token transformer.

**Code:**
```pseudocode
// Define a token for C-like 0x hex notation
uc.@ExpressionTokens().Add("0x[0-9A-Fa-f]+", TokenType::TokenTransform);
uc.@TokenTransformer().FromTo("{'0x'}{Num:'[0-9A-Fa-f]+'}", "BaseConvert('{Num}', 16)");
wl("0xFF is evaluated as: ", uc.EvalStr("0xFF"))

// Define a token for C++-style 0b binary notation
uc.@ExpressionTokens().Add("0b[01]+", TokenType::TokenTransform);

// Using {@Eval} is more efficient as the conversion happens once during the token transform pass.
uc.@TokenTransformer().FromTo("{'0b'}{Num:'[01]+'}", "{@Eval: BaseConvert(Num, 2)}");
wl("0b1011 is evaluated as: ", uc.EvalStr("0b1011"))

// Note: uCalc has built-in support for hex/binary using # notation (e.g., #hFF, #b1011)
wl("uCalc's built-in #hFF is: ", uc.EvalStr("#hFF"))
```

**Output:**
```
0xFF is evaluated as: 255
0b1011 is evaluated as: 11
uCalc's built-in #hFF is: 255
```

---

### Example ID: 1008

**Description:** Internal Test: Verifies that the `subMatchGroup` parameter correctly extracts a capture group's content and that `ItemIs::QuotedText` works as expected.

**Code:**
```pseudocode
var t = uc.NewTransformer();

// Define a custom string literal using pipe characters `|...|`.
// The regex `\|([^\|]*)\|` captures the inner content in group 1.
// We set `subMatchGroup` to 1 to use this group as the token's value.
var pipeStringToken = t.@Tokens().Add([verbatim]\|([^\|]*)\|[/verbatim], TokenType::Literal, "", 1);

// Complete the definition by setting the data type and QuotedText property.
pipeStringToken.@DataType(uc.DataTypeOf("String"));
pipeStringToken.IsProperty(ItemIs::QuotedText, true);

// Define a simple rule to prove the token works.
t.FromTo("Test: {@String:s}", "Found: {s(0)} | Content: {s(1)}");

// The transformer now recognizes |...| as a string literal.
wl(t.Transform("Test: |hello|"))
```

**Output:**
```
Found: |hello| | Content: hello
```

---

### Example ID: 155

**Description:** Transformer: Matching by tokens vs match by character; also whitespace sensitivity

**Code:**
```pseudocode
// This examples shows the default match by
// token mode, as well as how to reconfigure
// it in order to do match by character
// along with a whitespace variation

var t = uc.NewTransformer();
var txt = "This is an island test, I said.";
t.FromTo("is", "<is>");

wl(t.Transform(txt))
wl("")

t.@Tokens().@Description("Match by character");
t.@Tokens().Add("."); // This overrides existing tokens
t.FromTo("is", "<is>");
wl(t.@Tokens().@Description())
wl(t.Transform(txt))
wl("")

// Note: whitespace sensitivity is off by default
// Whitespace token is re-introduced
// (after being overridden in the previous Token Add())
t.@Tokens().@Description("By char + whitespace ignored");
t.@Tokens().Add("[\\t\\v ]+", TokenType::Whitespace);
t.FromTo("is", "<{@Self}>");
wl(t.@Tokens().@Description())
wl(t.Transform(txt))
```

**Output:**
```
This <is> an island test, I said.

Match by character
Th<is> <is> an <is>land test, I said.

By char + whitespace ignored
Th<is> <is> an <is>land test, <I s>aid.
```

---

### Example ID: 165

**Description:** Defining a token bracket pair

**Code:**
```pseudocode

// Here we define < and > as a bracket pair.
// Such pairs can be part of a pattern match
// and a match can be found within a bracket pair
// but a match will not cross boundaries with one
// part of the match out and another part inside

var t = uc.NewTransformer();
var txt = "a < b c > c, < a > b c, < a b c >";

t.@Tokens().Add("<", TokenType::Generic, ">");
t.FromTo("a {etc} c", "((a {etc} c))");

wl(txt)
wl(t.Transform(txt))
```

**Output:**
```
a < b c > c, < a > b c, < a b c >
((a < b c > c)), < a > b c, < ((a b c)) >
```

---

### Example ID: 166

**Description:** Defining quoted text 

**Code:**
```pseudocode

// In example we'll define quoted text using < and > as
// surrounding quotes.  Singe and double quotes ' and " 
// are already defined by default.  This is just an example.

// Quoted text must be defined as TokenType.Literal
// The last argument, 1, means that the literal part of the match will
// be the part of the regex found int the first parenthesis (here's
// there's only one set of parenthesis).

var t = uc.NewTransformer();
var SpecialQuotes = t.@Tokens().Add("<([^>]*)>", TokenType::Literal, "", 1);
SpecialQuotes.SetDataType(BuiltInType::String);
SpecialQuotes.IsProperty(ItemIs::QuotedText, true);

t.Pattern("{token:1}");
wl(t.Filter("abc <some quoted text> xyz 123.456 + 25e2").@Matches().@Text())
wl("")

// Based on the definition, the part within < and > is the literal part
// passed to the string + operator used by EvalStr

uc.@ExpressionTokens().Add(SpecialQuotes);
wl(uc.EvalStr("<some quoted text> + < plus more>"));
```

**Output:**
```
abc
<some quoted text>
xyz
123.456
+
25e2

some quoted text plus more
```

---

### Example ID: 163

**Description:** Token Add(ExistingToken)

**Code:**
```pseudocode

var t1 = uc.NewTransformer();
var CommentRegex = [verbatim]/\*([\s\S]*?)\*/[/verbatim];
var WhitespaceToken = t1.@Tokens().Add(CommentRegex, TokenType::Whitespace);
WhitespaceToken.@Description("Treats text between /* and */ as whitespace");

var txt = "a b, a /* comment a b */ b, a x b, ab, a   b, a, b";

var t2 = uc.NewTransformer();
t2.FromTo("a b", "<{@Self}>");
t2.Transform(txt);
wl(t2)

// The token defined in the other transformer (WhitespaceToken) is imported into this one.
// Now, everything between /* and */ will be treated as whitespace
t2.@Tokens().Add(WhitespaceToken);
wl(t2.Transform(txt))
```

**Output:**
```
<a b>, a /* comment <a b> */ b, a x b, ab, <a   b>, a, b
<a b>, <a /* comment a b */ b>, a x b, ab, <a   b>, a, b
```

---

### Example ID: 168

**Description:** Token Context switch

**Code:**
```pseudocode
var CommentTransform = uc.NewTransformer();
var CommentTokens = CommentTransform.@Tokens();
CommentTokens.Add(".");
CommentTokens.Add("[a-z]+");

var txt = "'This is it' /* 'This is it' This is it */ This is it";

var t = uc.NewTransformer();
t.FromTo("is", "<is>");
wl(t.Transform(txt).@Text())

// Now the context will switch between /* and */
// In that context there's no quoted text token,
t.@Tokens().ContextSwitch(CommentTokens, [c]"/\\*"[/c][vb]"/\*"[/vb], [c]"\\*/"[/c][vb]"\*/"[/vb]);
t.FromTo("is", "<is>");
wl(t.Transform(txt).@Text())

```

**Output:**
```
'This is it' /* 'This is it' This <is> it */ This <is> it
'This is it' /* 'This <is> it' This <is> it */ This <is> it
```

---

### Example ID: 175

**Description:** Turn new line into whitespace with Tokens.Add

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("<{tag}>{code}</{tag}>", "[{tag}]{code}[/{tag}]");
var MyStr = [verbatim]<div>Single line</div>
<div>Line 1
Line 2
Line 3
Line 4</div>[/verbatim];

wl("New line as statement separator (default)")
wl("")
wl(t.Transform(MyStr).@Text())
wl("")

wl("New line as whitespace")
wl("")
t.@Tokens().Add([c]"[\\r\\n]+"[/c][vb]"[\r\n]+"[/vb], TokenType::Whitespace);
wl(t.Transform(MyStr).@Text())



```

**Output:**
```
New line as statement separator (default)

[div]Single line[/div]
<div>Line 1
Line 2
Line 3
Line 4</div>

New line as whitespace

[div]Single line[/div]
[div]Line 1
Line 2
Line 3
Line 4[/div]
```

---

---

## Add(Tokens) - ID: 374
/doc/reference/classes/ucalc.tokens/add/add-tokens/

**Description:** Imports a list of token definitions from another Tokens collection, enabling the reuse of lexical configurations.

**Syntax:** Add(Tokens)
**Parameters:**
sourceTokens - Tokens - A pre-existing `Tokens` object whose definitions will be copied into the current collection.
**Return:** Tokens - The current `Tokens` object, allowing for a fluent, chainable syntax.
**Remarks:**

# 🔄 Reusing Token Configurations

The `Add(Tokens)` method provides a powerful way to reuse token configurations by importing all token definitions from one `Tokens` collection into another. This is essential for creating modular, maintainable, and consistent parsing logic across different components of an application.

## Core Functionality

*   **Append, Don't Replace**: This method **appends** the imported tokens to the end of the current list. It does not clear existing tokens. To start with a clean slate, you must call `Clear()` before importing.
*   **Copy, Don't Reference**: The import process creates a *copy* of each token definition. After the import, the two `Tokens` collections are independent; modifying a token in one will not affect the other.

## 💡 Precedence and Order

Token precedence is determined by a Last-In, First-Out (LIFO) order. Since this method appends tokens to the end of the list, **imported tokens will have higher precedence** than any tokens that already exist in the collection. The tokenizer will check for matches against the imported tokens first.

## 🎯 Primary Use Cases

1.  **Sharing Base Definitions**: Create a single `Tokens` object that defines the complete syntax for a language or data format. Other transformers can then import this base set, ensuring consistency.
2.  **Extending Syntax**: Import a base set of tokens and then add additional, more specific tokens to create a specialized dialect or extension of a language.
3.  **Cross-Component Consistency**: Ensure that an [ExpressionTransformer](/Reference/uCalcBase/uCalc/ExpressionTransformer), a [TokenTransformer](/Reference/uCalcBase/uCalc/TokenTransformer), and a general-purpose [Transformer](/Reference/uCalcBase/Transformer/Constructor) all share the same fundamental understanding of syntax by importing from a common source.

## 🆚 Comparative Analysis: Why uCalc?

In traditional compiler development with tools like ANTLR or Flex/Bison, lexical rules are defined in static grammar files. To share or reuse these rules, you typically rely on file-based imports managed by the build system. This process is entirely static and occurs at compile-time.

uCalc's approach is fundamentally different and more flexible:

*   **Programmatic & Dynamic**: Token sets are objects that can be created, modified, and shared entirely at runtime. You can build a library of `Tokens` configurations and programmatically compose them based on application logic, user settings, or other dynamic conditions.
*   **No Build Step**: There is no code generation or recompilation step. This allows for rapid prototyping and enables applications that can adapt or extend their own syntax on the fly.

This runtime flexibility makes `Add(Tokens)` a cornerstone feature for building modular and dynamically configurable parsing systems.

**Examples:**

### Example ID: 1009

**Description:** How to define a custom token in one transformer and reuse it in another.

**Code:**
```pseudocode
// Create a source transformer and define a custom token.
New(uCalc::Transformer, t_source)
var customToken = t_source.@Tokens().Add("###", TokenType::Generic);

// Create a destination transformer.
New(uCalc::Transformer, t_dest)

// Import all token definitions from the source.
t_dest.@Tokens().Add(t_source.@Tokens());
t_dest.FromTo("###", "MATCH");

wl("t_dest can now find '###': ", t_dest.Transform("Test ### Test"))
```

**Output:**
```
t_dest can now find '###': Test MATCH Test
```

---

### Example ID: 167

**Description:** Importing a list of tokens from one transformer to another

**Code:**
```pseudocode
var t = uc.NewTransformer();

// This creates a simpler (not very useful) set of tokens for sake of example
var MyTokens = t.@Tokens();
MyTokens.Clear(); // removes the default list of tokens
MyTokens.Add("."); // Should always have a fallback token like this one
MyTokens.Add(";", TokenType::StatementSep);
MyTokens.Add("<", TokenType::Generic, ">");
MyTokens.Add("[0-9]+", TokenType::Literal);
MyTokens.Add(" +", TokenType::Whitespace);
MyTokens.Add("[a-z]+", TokenType::AlphaNumeric);

t.FromTo("{ This | That} {etc}", "[{@Self}]"); // {etc} stops at the semicolon ";" TokenType.StatementSep

wl(t.Transform("This is a test; That < 123.456; abc >; ABC"))
wl("")

New(uCalc::Transformer, OtherTransform(uc)) // This is an alternative way of constructing a new transformer
OtherTransform.@Tokens().Add(MyTokens); // Imports the entire token list from the other transformer
OtherTransform.Pattern("{word:1}");

wl(OtherTransform.Filter("This is a test; That < 123.456; abc >; ABC").@Matches().@Text())

```

**Output:**
```
[This is a test]; [That < 123.456; abc >]; ABC

This
is
a
test
;
That
<
123
.
456
;
abc
>
;
ABC
```

---

---

## At - ID: 390
/doc/reference/classes/ucalc.tokens/at/

**Description:** Returns the nth token from the token list

**Syntax:** At(int)
**Parameters:**
Index - int - nth Index
**Return:** Item - Token Item
**Remarks:**

Returns the nth token from the token list.

**Examples:**

### Example ID: 70

**Description:** Displays the complete list of default token definitions, showing their type, internal name, and regex pattern.

**Code:**
```pseudocode
// Lists all tokens currently defined for the expression evaluator.

wl("Token Count: ", uc.@ExpressionTokens().@Count())
wl("")
wl("Index  Type  Name: regex")
wl("========================")
var Tokens = uc.@ExpressionTokens();
foreach (var token in Tokens)
   w(Tokens.IndexOf(token))
   wl("  ", token.@Description(), "  ", token.@Name(), ": ", token.@Regex())
end for

// Note that the expression evaluator token list has a few extra tokens,
// related to hex/bin/oct notation, string interpolation, and imaginary number
// notation, which are not found in the default Transformer token list.
```

**Output:**
```
Token Count: 30

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
27  literal  _token_imaginaryunit: #i
28  tokentransform  _token_binaryhexoctalnotation: #[bho][0-9A-F]+
29  tokentransform  _token_stringinterpolationquote: \$['"]
```

---

---

## ByName - ID: 746
/doc/reference/classes/ucalc.tokens/byname/

**Description:** Retrieves a token definition by its name and can optionally re-categorize it in a single operation.

**Syntax:** ByName(string, TokenType)
**Parameters:**
tokenName - string - The name of the token to retrieve (e.g., `_token_alphanumeric`).
newType - TokenType [default = TokenType::None] - Optional. The new lexical category to assign to the token. If `TokenType::None` (the default), the token's type is not changed.
**Return:** Item - Returns the [Item](/Reference/uCalcBase/Item) object for the token. If the token is not found, an empty item is returned (for which `IsEmpty()` is true).
**Remarks:**

The `ByName` method is a versatile tool for interacting with a [Tokens](/Reference/uCalcBase/Tokens) collection. It serves a dual purpose: it retrieves a specific token definition by its unique name and can optionally re-categorize it in the same operation.

This method is the primary way to access built-in or user-defined tokens programmatically when you know their name (e.g., `_token_alphanumeric`). It is often used as a precursor to modifying a token's properties, such as its regex pattern or its lexical type.

## ⚙️ Dual Getter/Setter Behavior

The method's behavior depends on the `newType` parameter:

*   **Getter Mode (Default)**: If `newType` is omitted or set to `TokenType::None`, `ByName` acts purely as a getter. It finds the token with the specified name and returns its corresponding [Item](/Reference/uCalcBase/Item) object.

*   **Setter Mode**: If you provide a specific [TokenType](/Reference/Enums/TokenType) for `newType`, the method first finds the token and then immediately changes its lexical category to the new type. This is a convenient shortcut for `tokens.ByName("...").TypeOfToken(newType)`.

## 🎯 Primary Use Cases

1.  **Introspection**: Retrieve a token to inspect its properties, such as its regex pattern via [pseudocode]`item.Regex()`.
2.  **Dynamic Syntax Modification**: Change the parser's behavior at runtime. A common example is re-categorizing the newline token (`_token_newline`) from a `StatementSep` to `Whitespace` to allow patterns to match across multiple lines.

## 💡 Why uCalc? (Comparative Analysis)

In traditional compiler tools like ANTLR or Flex/Bison, token definitions are static. They are defined in a grammar file, and changing a token's type requires modifying that file, regenerating parser code, and recompiling the application. This is a compile-time, static process.

uCalc's token system is entirely **dynamic and programmatic**. The `ByName` method is a key part of this dynamism. It allows your application to:

*   **Modify Syntax at Runtime**: Your code can re-categorize tokens on the fly, effectively switching between different language "dialects" without a restart.
*   **Create Adaptable Parsers**: Build tools that can be configured by the end-user to support different comment styles or literal formats.

This runtime flexibility provides a significant advantage over static parsing systems, enabling the creation of highly adaptable and user-configurable applications.

**Examples:**

### Example ID: 1012

**Description:** Retrieves a built-in token by its name and inspects its regex pattern.

**Code:**
```pseudocode
var tokens = uc.@ExpressionTokens();
var alphaToken = tokens.ByName("_token_alphanumeric");
wl("Alphanumeric Regex: ", alphaToken.@Regex())
```

**Output:**
```
Alphanumeric Regex: [a-zA-Z_][a-zA-Z0-9_]*
```

---

### Example ID: 1013

**Description:** Dynamically re-categorizes the newline token to treat it as whitespace, allowing a pattern to match across multiple lines.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var source = [verbatim]<data>
  content spans
  multiple lines
</data>[/verbatim];
t.FromTo("<data>{body}</data>", "Body: [{body}]");

wl("--- Before: Newline is a Separator ---")
wl(t.Transform(source))

// Use ByName to find the newline token and change its type.
t.@Tokens().ByName("_token_newline", TokenType::Whitespace);

wl("")
wl("--- After: Newline is Whitespace ---")
wl(t.Transform(source))
```

**Output:**
```
--- Before: Newline is a Separator ---
<data>
  content spans
  multiple lines
</data>

--- After: Newline is Whitespace ---
Body: [content spans
  multiple lines]
```

---

### Example ID: 169

**Description:** Token Remove

**Code:**
```pseudocode
// This example removes the single quote pattern from the list

var t = uc.NewTransformer();
var txt = "This is a test, 'This is a test'";
t.FromTo("{token:1}", "<{@Self}>");
wl(t.Transform(txt).@Text())

// Now the ' character will no longer be special
// (see the Name() example for list of token names
t.@Tokens().Remove(t.@Tokens()["_token_string_singlequoted"]);
wl(t.Transform(txt).@Text())
```

**Output:**
```
<This> <is> <a> <test><,> <'This is a test'>
<This> <is> <a> <test><,> <'><This> <is> <a> <test><'>
```

---

### Example ID: 220

**Description:** Change newline from statement separator to whitespace

**Code:**
```pseudocode
var t = uc.NewTransformer();

t.Str([verbatim]
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
[/verbatim]);

t.Pattern("<div>{body}</div>");

wl("Newline as statement separator (default)")
wl("----------------------------------------")
wl(t.Find().@Matches().@Text())
wl("")

wl("Newline as whitespace")
wl("---------------------")
t.@Tokens()["_token_newline"].@TypeOfToken(TokenType::Whitespace);
wl(t.Find().@Matches().@Text())
```

**Output:**
```
Newline as statement separator (default)
----------------------------------------
<div>a b c</div>
<div>1 2 3</div>

Newline as whitespace
---------------------
<div>a b c</div>
<div>
x
y
z
</div>
<div>1 2 3</div>
```

---

### Example ID: 170

**Description:** Token(TokenType)

**Code:**
```pseudocode
wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Name())
wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex())
wl("")

// Note: In C# or VB you can simply use [TokenType::Literal, n]
// instead of ByType(TokenType::Literal, n)
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 0).@Name())
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 1).@Name())
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 2).@Name())
```

**Output:**
```
_token_alphanumeric
[a-zA-Z_][a-zA-Z0-9_]*

_token_string_singlequoted
_token_string_doublequoted
_token_string_tripledoublequoted
```

---

---

## ByType - ID: 644
/doc/reference/classes/ucalc.tokens/bytype/

**Description:** Retrieves a token definition from the collection by its lexical category (TokenType) and optional index.

**Syntax:** ByType(TokenType, int)
**Parameters:**
tokenType - TokenType - The lexical category to filter by, specified as a member of the [TokenType](/Reference/Enums/TokenType) enum.
nth - int [default = 0] - The zero-based index of the token to retrieve from the filtered list of matching types. Defaults to 0, which returns the first match.
**Return:** Item - An [Item](/Reference/uCalcBase/Item) object representing the token. If no token is found at the specified index for the given type, an empty item is returned (for which `IsEmpty()` is true).
**Remarks:**

The `ByType` method provides a way to query and retrieve token definitions based on their functional category, such as `Literal`, `Whitespace`, or `Bracket`. It is a key tool for introspecting and dynamically modifying the lexical rules of a [Transformer](/Reference/uCalcBase/Transformer/Constructor) or the main expression parser.

### ⚙️ How It Works

This method filters the entire token collection to find all tokens that match the specified `tokenType`. Since multiple tokens can belong to the same category (e.g., there are several built-in `Literal` tokens for different string and number formats), the optional `nth` parameter allows you to select a specific one from the filtered list.

The index `nth` is zero-based and applies only to the subset of tokens matching the type.

### 🎯 Primary Use Cases

1.  **Introspection**: Programmatically find all tokens of a certain type to inspect their regex patterns or other properties. This is useful for building debuggers or documentation tools.
2.  **Dynamic Parser Modification**: Retrieve a specific token to modify its behavior. For example, you might retrieve all `Whitespace` tokens to change their regex patterns.
3.  **Language-Agnostic Logic**: Write code that can find "the alphanumeric token" without needing to know its specific internal name (`_token_alphanumeric`).

### 🆚 Comparative Analysis: Why uCalc?

In a traditional parsing setup using tools like ANTLR or Flex/Bison, the token list is static and compiled. To find all tokens of a certain "type," you would need to manually inspect the generated source code or grammar files.

uCalc's token system is a dynamic, queryable collection. `ByType` provides a high-level, programmatic way to filter this collection that is analogous to using LINQ in C# or list comprehensions in Python to filter objects based on a property.

**C# LINQ Analogy:**
```csharp
// The uCalc way is more direct and built-in
var literalTokens = myTokens.Where(t => t.TypeOfToken == TokenType.Literal).ToList();
```

By providing a direct API for this common task, uCalc simplifies the process of building adaptable and introspective parsers.

For retrieving a token by its unique name, use the [ByName](/Reference/uCalcBase/Tokens/ByName) method. For direct index-based access, use [At](/Reference/uCalcBase/Tokens/At).

**Examples:**

### Example ID: 1018

**Description:** Retrieves the primary alphanumeric token definition using `ByType`.

**Code:**
```pseudocode
var tokens = uc.@ExpressionTokens();
var alphaToken = tokens.ByType(TokenType::AlphaNumeric);

wl("Name: ", alphaToken.@Name())
wl("Regex: ", alphaToken.@Regex())
```

**Output:**
```
Name: _token_alphanumeric
Regex: [a-zA-Z_][a-zA-Z0-9_]*
```

---

### Example ID: 1019

**Description:** Practical: Iterates through all tokens categorized as 'Literal' to display their definitions.

**Code:**
```pseudocode
var tokens = uc.@ExpressionTokens();
var(int, i) = 0;
New(uCalc::Item, literalToken)

wl("--- All Literal Tokens ---")
do
   literalToken = tokens.ByType(TokenType::Literal, i);
   if (literalToken.NotEmpty())
      wl(i, ": ", literalToken.@Name(), " - ", literalToken.@Regex())
   end if
   i = i + 1;
loop while(literalToken.NotEmpty())
```

**Output:**
```
--- All Literal Tokens ---
0: _token_string_singlequoted - '([^']*(?:''[^']*)*)'
1: _token_string_doublequoted - "([^"]*(?:""[^"]*)*)"
2: _token_string_tripledoublequoted - """([\s\S]*?)"""
3: _token_floatnumber - [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
4: _token_imaginaryunit - #i
```

---

### Example ID: 1020

**Description:** Internal Test: Verifies that requesting an out-of-bounds index for a token type returns an empty item.

**Code:**
```pseudocode
var tokens = uc.@ExpressionTokens();

// There is only one Alphanumeric token, so index 1 is out of bounds.
var outOfBoundsToken = tokens.ByType(TokenType::AlphaNumeric, 1);

wl("Is token empty? ", bool(outOfBoundsToken.IsEmpty()))
wl("Was token found? ", bool([cs]![/cs][NotCs]not[/NotCs] outOfBoundsToken.IsProperty(ItemIs::NotFound)))
```

**Output:**
```
Is token empty? True
Was token found? False
```

---

### Example ID: 170

**Description:** Token(TokenType)

**Code:**
```pseudocode
wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Name())
wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex())
wl("")

// Note: In C# or VB you can simply use [TokenType::Literal, n]
// instead of ByType(TokenType::Literal, n)
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 0).@Name())
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 1).@Name())
wl(uc.@ExpressionTokens().ByType(TokenType::Literal, 2).@Name())
```

**Output:**
```
_token_alphanumeric
[a-zA-Z_][a-zA-Z0-9_]*

_token_string_singlequoted
_token_string_doublequoted
_token_string_tripledoublequoted
```

---

### Example ID: 71

**Description:** Change characters accepted as alphanumeric in expressions using ExpressionTokens() & Token()

**Code:**
```pseudocode
// (See alternate version of this example using ItemOf instead of ExpressionTokens)

// In this section underscore, _, and numeric digits
// are accepted as part of alphanumeric tokens
uc.DefineVariable("My_Variable = 111");
wl(uc.@Error().@Message())
uc.DefineVariable("Variable123 = 222");
wl(uc.@Error().@Message())

wl(uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex())
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
wl("---")

// Now we no longer want underscore, _, or numeric digits
// to be accepted in alphanumeric tokens; only A-Z
uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex("[a-zA-Z]+");

uc.DefineVariable("Other_Variable = 333");
wl(uc.@Error().@Message())
uc.DefineVariable("OtherVariable123 = 444");
wl(uc.@Error().@Message())

wl(uc.EvalStr("Other_Variable"))
wl(uc.EvalStr("OtherVariable123 "))
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
wl("---")

// We restore the alphanumeric regex to support _ and numbers again
// Note: My_Variable and Variable123 remained; they were simply inaccessible
uc.@ExpressionTokens()[TokenType::AlphaNumeric].@Regex("[a-zA-Z_][a-zA-Z0-9_]*");
wl(uc.EvalStr("My_Variable"))
wl(uc.EvalStr("Variable123"))
```

**Output:**
```
No error
No error
[a-zA-Z_][a-zA-Z0-9_]*
111
222
---
Invalid definition
Invalid definition
Undefined identifier
Undefined identifier
Undefined identifier
Undefined identifier
---
111
222
```

---

---

## Clear - ID: 375
/doc/reference/classes/ucalc.tokens/clear/

**Description:** Removes all token definitions from the collection, restoring it to an empty state.

**Syntax:** Clear()
**Return:** void - This method does not return a value.
**Remarks:**

The `Clear()` method erases all token definitions from a `Tokens` collection. This is a powerful tool for completely resetting the lexical rules of a [Transformer](/Reference/uCalcBase/Transformer/Constructor) before defining a new, custom set of tokens from scratch.

### 🎯 Primary Use Case: Custom Language Definition

This method is the first step in creating a parser for a completely new syntax. By default, a [Transformer](/Reference/uCalcBase/Transformer/Constructor) inherits a rich set of tokens for parsing general-purpose expressions. `Clear()` allows you to wipe this default set and build a new tokenizer tailored to a specific format, such as a simplified configuration language, a data format, or a Domain-Specific Language (DSL).

### ⚠️ Warning: The Need for a Catch-All Token

A `Transformer` cannot function with a completely empty token list. If no patterns match a character, the tokenizer will not advance, leading to an infinite loop or failure. After clearing the tokens, you must add at least one "catch-all" token that can match any single character to ensure the tokenizer can always make progress.

```pseudocode
// After clearing, always add a fallback token.
t.Tokens().Clear();
t.Tokens().Add("."); // Matches any single character.
```

### ⚖️ Comparative Analysis

*   **vs. Manual `Remove()`**: While you could iterate through a `Tokens` collection and call [Remove()](/Reference/uCalcBase/Tokens/Remove) on each item, `Clear()` is a single, optimized operation that is both faster and more direct.

*   **vs. New `Transformer` Instance**: Creating a `New(uCalc::Transformer, t)` also gives you a fresh start, but it begins with uCalc's default token set. `Clear()` is used when you want to modify the lexical rules of an *existing* transformer instance in-place, rather than creating a new one.

This method is the key to unlocking uCalc's full potential for dynamic language creation, allowing you to move beyond expression evaluation and into full-custom parsing.

**Examples:**

### Example ID: 1021

**Description:** Demonstrates the basic functionality of clearing default tokens and adding a single new one.

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("is", "<IS>");

wl("--- With Default Tokens ---")
// By default, 'is' is a whole word (token)
wl(t.Transform("This is a test"))

// Clear all default token definitions
t.@Tokens().Clear();

// Add a new, simple token that matches any single character
t.@Tokens().Add(".");

wl("")
wl("--- After Clearing and Adding '.' Token ---")
// Now, 'i' and 's' are matched as separate characters
t.FromTo("is", "<IS>"); // The rule must be redefined
wl(t.Transform("This is a test"))
```

**Output:**
```
--- With Default Tokens ---
This <IS> a test

--- After Clearing and Adding '.' Token ---
Th<IS> <IS> a test
```

---

### Example ID: 167

**Description:** Importing a list of tokens from one transformer to another

**Code:**
```pseudocode
var t = uc.NewTransformer();

// This creates a simpler (not very useful) set of tokens for sake of example
var MyTokens = t.@Tokens();
MyTokens.Clear(); // removes the default list of tokens
MyTokens.Add("."); // Should always have a fallback token like this one
MyTokens.Add(";", TokenType::StatementSep);
MyTokens.Add("<", TokenType::Generic, ">");
MyTokens.Add("[0-9]+", TokenType::Literal);
MyTokens.Add(" +", TokenType::Whitespace);
MyTokens.Add("[a-z]+", TokenType::AlphaNumeric);

t.FromTo("{ This | That} {etc}", "[{@Self}]"); // {etc} stops at the semicolon ";" TokenType.StatementSep

wl(t.Transform("This is a test; That < 123.456; abc >; ABC"))
wl("")

New(uCalc::Transformer, OtherTransform(uc)) // This is an alternative way of constructing a new transformer
OtherTransform.@Tokens().Add(MyTokens); // Imports the entire token list from the other transformer
OtherTransform.Pattern("{word:1}");

wl(OtherTransform.Filter("This is a test; That < 123.456; abc >; ABC").@Matches().@Text())

```

**Output:**
```
[This is a test]; [That < 123.456; abc >]; ABC

This
is
a
test
;
That
<
123
.
456
;
abc
>
;
ABC
```

---

---

## ContextSwitch - ID: 376
/doc/reference/classes/ucalc.tokens/contextswitch/

---

## ContextSwitch(Tokens, Item, int32, string, int32) - ID: 377
/doc/reference/classes/ucalc.tokens/contextswitch/contextswitch-tokens,-item,-int32,-string,-int32/

**Description:** Sets a token that will cause a temporary switch to another token list with configurable insertion points

**Syntax:** ContextSwitch(Tokens, Item, int32, string, int32)
**Parameters:**
OtherTokenGroup - Tokens - Other token list to switch to
StartToken - Item - Existing token that will cause the context switch
InsertionPointA - int32 [default = -1] - // Where in the token list to insert the token
EndToken - string [default = ""] - Regex pattern that causes a return to the original token list
InsertionPointB - int32 [default = -1] - Where in the other token list (a copy of it) to insert the ending token
**Return:** Tokens - Current token
**Remarks:**

[revisit]

This causes a context switch to happen when a given token pattern is reached.  This is useful for instance if are parsing source code, and you want comments to be parsed based on a different set of tokens from the rest of the code.

This version of the function inserts a pre-existing token for the context switch, and lets you decide where in the token list to insert it.

---

## ContextSwitch(Tokens, string, int32, string, int32) - ID: 378
/doc/reference/classes/ucalc.tokens/contextswitch/contextswitch-tokens,-string,-int32,-string,-int32/

**Description:** Sets a token pattern that will cause a temporary switch to another token list with configurable insertion points

**Syntax:** ContextSwitch(Tokens, string, int32, string, int32)
**Parameters:**
OtherTokenGroup - Tokens - Other token list to switch to
StartToken - string - Regex pattern that triggers the context switch
InsertionPointA - int32 [default = -1] - Where in the token list to insert the new token
EndToken - string [default = ""] - Regex pattern that causes a return to the original token list
InsertionPointB - int32 [default = -1] - Where in the other token list (a copy of it) to insert the ending token
**Return:** Tokens - Current token list
**Remarks:**

[revisit]
This causes a context switch to happen when a given token pattern is reached.  This is useful for instance if are parsing source code, and you want comments to be parsed based on a different set of tokens from the rest of the code.

This version of the function lets you decide where in the token list to insert the context switching token.

---

## ContextSwitch(Tokens, string, string) - ID: 379
/doc/reference/classes/ucalc.tokens/contextswitch/contextswitch-tokens,-string,-string/

**Description:** Temporarily replaces the active token set when a start pattern is matched, until an end pattern is found.

**Syntax:** ContextSwitch(Tokens, string, string)
**Parameters:**
newTokenSet - Tokens - The `Tokens` collection to activate when the `startPattern` is matched.
startPattern - string - A regular expression that defines the token that triggers the switch to the `newTokenSet`.
endPattern - string - A regular expression that defines the token that ends the context switch and reverts to the original token set.
**Return:** Tokens - Returns the current `Tokens` object to allow for a fluent, chainable interface.
**Remarks:**

## ⚙️ Parsing Embedded Languages with ContextSwitch

The [pseudocode]`ContextSwitch` method is an advanced feature for parsing documents that contain multiple, distinct syntaxes, such as an embedded language. It dynamically swaps the tokenizer's rule set when a specific boundary is crossed.

### How It Works

When you call [pseudocode]`ContextSwitch`, you are defining a special, high-precedence rule. During parsing:

1.  The tokenizer scans text using the main [Tokens](/reference/uclcbase/tokens) collection.
2.  If it finds a match for `startPattern`, it immediately suspends the main token set and begins using `newTokenSet`.
3.  It continues using `newTokenSet` until it finds a match for `endPattern`.
4.  Once `endPattern` is found, it reverts to the original token set.

A classic real-world analogy is parsing HTML with embedded JavaScript:
*   The **main token set** would define HTML tags (`<`, `>`).
*   `startPattern` would be `<script>`.
*   `newTokenSet` would contain tokens for JavaScript (keywords, operators, etc.).
*   `endPattern` would be `</script>`.

This allows the same [Transformer](/reference/uclcbase/transformer) to correctly parse both languages in a single pass.

### ⚠️ Non-Nesting Behavior

By default, context switches are **not nestable**. If the tokenizer is already inside a context switch and encounters another `startPattern`, the second pattern is ignored. The context switch is only terminated by the first `endPattern` it finds. See the internal test example for a demonstration of this behavior.

--- 

## 💡 `ContextSwitch` vs. `LocalTransformer`

Both `ContextSwitch` and [Rule.LocalTransformer](/reference/uclcbase/rule/localtransformer) handle nested or scoped parsing, but they operate at different stages of the process. `LocalTransformer` is the tool for hierarchical, nestable parsing.

| Feature | `Tokens.ContextSwitch` (This Topic) | `Rule.LocalTransformer` |
| :--- | :--- | :--- |
| **Stage** | **Lexical (Tokenizer)** | **Syntactic (Parser)** |
| **What it Does** | Swaps the entire set of token definitions. Changes *how* text is broken into tokens. | Applies a new set of grammar rules to a block of *already-tokenized* text. |
| **Analogy** | Switching from the English alphabet to the Greek alphabet mid-sentence. | Applying different sentence diagramming rules to a specific paragraph. |
| **Nesting** | **No**. Switches are not nestable by default. | **Yes**. Local transformers can be nested to any depth, creating a true hierarchy. |
| **Use Case** | Parsing completely different, embedded languages (e.g., `<script>` in HTML, SQL in a string literal). | Recursively parsing nested structures within the *same* language (e.g., finding `<img>` tags only within `<div>` tags). |

### When to Use Which

*   Use **`ContextSwitch`** when you encounter a block of text that follows entirely different lexical rules from the surrounding document.
*   Use **`LocalTransformer`** when you want to apply a more specific set of find/replace patterns only within a region that has already been matched by a parent rule, using the same lexical rules.

---
## 🆚 Comparative Analysis

*   **vs. Regular Expressions**: Regex has no built-in concept of lexical states. Handling embedded syntaxes would require complex lookarounds or multiple, separate parsing passes managed by your application's code, which is inefficient and error-prone.

*   **vs. Parser Generators (ANTLR, Flex/Bison)**: Traditional compiler tools handle this with "lexical modes" or "states" defined within a static grammar file. The key advantage of uCalc is its **dynamic, programmatic nature**. You can define, modify, and apply these context switches at runtime without any external tools or recompilation, allowing for highly adaptable and user-configurable parsers.

**Examples:**

### Example ID: 1027

**Description:** Using a context switch to prevent transformations inside a designated `[RAW]` block.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var(string, text) = "Replace config, but not the one inside [RAW]this config is raw[/RAW].";

// Create a token set for the raw block that only tokenizes single characters.
New(uCalc::Transformer, rawTransformer)
var rawTokens = rawTransformer.@Tokens();
rawTokens.Clear();
rawTokens.Add("."); // Match any single character

// Switch to rawTokens when [RAW] is found, and switch back at [/RAW].
t.@Tokens().ContextSwitch(rawTokens, [verbatim]\[RAW\][/verbatim], [verbatim]\[/RAW\][/verbatim]);

t.FromTo("config", "SETTING");

wl(t.Transform(text))
```

**Output:**
```
Replace SETTING, but not the one inside [RAW]this config is raw[/RAW].
```

---

### Example ID: 168

**Description:** Token Context switch

**Code:**
```pseudocode
var CommentTransform = uc.NewTransformer();
var CommentTokens = CommentTransform.@Tokens();
CommentTokens.Add(".");
CommentTokens.Add("[a-z]+");

var txt = "'This is it' /* 'This is it' This is it */ This is it";

var t = uc.NewTransformer();
t.FromTo("is", "<is>");
wl(t.Transform(txt).@Text())

// Now the context will switch between /* and */
// In that context there's no quoted text token,
t.@Tokens().ContextSwitch(CommentTokens, [c]"/\\*"[/c][vb]"/\*"[/vb], [c]"\\*/"[/c][vb]"\*/"[/vb]);
t.FromTo("is", "<is>");
wl(t.Transform(txt).@Text())

```

**Output:**
```
'This is it' /* 'This is it' This <is> it */ This <is> it
'This is it' /* 'This <is> it' This <is> it */ This <is> it
```

---

---

## Count = [int] - ID: 380
/doc/reference/classes/ucalc.tokens/count-=-[int]/

**Description:** Gets the total number of token definitions registered in the collection.

**Remarks:**

The `Count` property returns the total number of token definitions currently registered in the [Tokens](/Reference/uCalcBase/Tokens/Constructor) collection.

### 🎯 Primary Use Case: Iteration

This property is most commonly used to determine the upper bound for a loop that iterates through the collection to inspect or modify each token definition.

```pseudocode
var tokens = myTransformer.Tokens();
for (i = 0 to tokens.Count() - 1)
   var tokenItem = tokens.At(i);
   wl(tokenItem.Name());
end for
```

### 💡 Why uCalc? (Comparative Analysis)

While analogous to `.Count` on a `List` in C# or `.size()` on a `std::vector` in C++, the `Count` of a uCalc `Tokens` collection represents something more powerful.

*   **vs. Static Lexers (ANTLR, Flex/Bison)**: In traditional compiler tools, the set of lexical rules (tokens) is defined in a static grammar file and fixed at compile-time. The number of tokens is an unchangeable property of the compiled parser.

*   **The uCalc Advantage**: uCalc's tokenizer is fully dynamic. The `Tokens` collection is a live, mutable object. `Count` reflects the current state of this dynamic system. You can add new tokens with [Add()](/Reference/uCalcBase/Tokens/Add) or remove them with [Clear()](/Reference/uCalcBase/Tokens/Clear), and `Count` will update immediately. This runtime configurability is a key feature that allows applications to adapt or extend their own syntax on the fly.

**Examples:**

### Example ID: 1030

**Description:** How to get the count of default token definitions.

**Code:**
```pseudocode
var tokenCount = uc.@ExpressionTokens().@Count();
wl("Default expression parser has ", tokenCount, " token definitions.")
```

**Output:**
```
Default expression parser has 30 token definitions.
```

---

### Example ID: 1031

**Description:** A practical example of iterating through all token definitions in a collection using Count as the loop boundary.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

var tokens = t.@Tokens();
wl("Total token definitions: ", tokens.@Count())
wl("--- Token List ---")

var i = 0;

for(i = 0 to tokens.@Count() - 1)
    var tokenItem = tokens.At(i);
    wl(i, ": ", tokenItem.@Name())
end for
```

**Output:**
```
Total token definitions: 27
--- Token List ---
0: _token_line
1: _token_catchall
2: _token_catchall_utf8_other
3: _token_punctuation
4: _token_quotechar
5: _token_quotechar_single
6: _token_quotechar_double
7: _token_quotechar_tripledouble
8: _token_memberaccess
9: _token_variableargs
10: _token_reducible2
11: _token_parenthesis
12: _token_parenthesis_close
13: _token_curlybrace
14: _token_curlybrace_close
15: _token_squarebracket
16: _token_squarebracket_close
17: _token_argseparator
18: _token_newline
19: _token_semicolon
20: _token_string_singlequoted
21: _token_string_doublequoted
22: _token_string_tripledoublequoted
23: _token_whitespace
24: _token_reducible
25: _token_floatnumber
26: _token_alphanumeric
```

---

### Example ID: 1032

**Description:** Internal Test: Verifies that the count updates correctly after Add() and Clear() operations, demonstrating the dynamic nature of the collection.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var tokens = t.@Tokens();

var initialCount = tokens.@Count();
wl("1. Initial count: ", initialCount)

// Add a new token
tokens.Add("custom_token");
wl("2. Count after Add: ", tokens.@Count())

// Clear all tokens
tokens.Clear();
wl("3. Count after Clear: ", tokens.@Count())

// Add one token back
tokens.Add(".");
wl("4. Count after adding one back: ", tokens.@Count())
```

**Output:**
```
1. Initial count: 27
2. Count after Add: 28
3. Count after Clear: 0
4. Count after adding one back: 1
```

---

### Example ID: 70

**Description:** Displays the complete list of default token definitions, showing their type, internal name, and regex pattern.

**Code:**
```pseudocode
// Lists all tokens currently defined for the expression evaluator.

wl("Token Count: ", uc.@ExpressionTokens().@Count())
wl("")
wl("Index  Type  Name: regex")
wl("========================")
var Tokens = uc.@ExpressionTokens();
foreach (var token in Tokens)
   w(Tokens.IndexOf(token))
   wl("  ", token.@Description(), "  ", token.@Name(), ": ", token.@Regex())
end for

// Note that the expression evaluator token list has a few extra tokens,
// related to hex/bin/oct notation, string interpolation, and imaginary number
// notation, which are not found in the default Transformer token list.
```

**Output:**
```
Token Count: 30

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
27  literal  _token_imaginaryunit: #i
28  tokentransform  _token_binaryhexoctalnotation: #[bho][0-9A-F]+
29  tokentransform  _token_stringinterpolationquote: \$['"]
```

---

---

## Description = [string] - ID: 540
/doc/reference/classes/ucalc.tokens/description-=-[string]/

**Description:** Gets or sets a user-defined text description for a token collection, useful for documenting and identifying different lexical configurations.

**Remarks:**

# 🏷️ Attaching Metadata to Token Sets

The `Description` property allows you to attach arbitrary string metadata to a [Tokens](/Reference/uCalcBase/Tokens/Constructor) object. This is an invaluable feature for debugging complex transformations, creating self-documenting code, and identifying specific lexical configurations at runtime.

## ⚙️ Getter and Setter Behavior

This property functions as both a getter and a setter:

*   **Getter**: Retrieves the current description string. If no description has been set, it returns an empty string.

*   **Setter**: [pseudocode]`myTokens.@Description("new description")` assigns the new metadata. As a method, `SetDescription()` supports a **fluent interface**, returning the `Tokens` object itself to allow for method chaining.

## 🎯 Core Use Cases

Attaching a description is a best practice for managing multiple or complex token sets.

*   **Debugging**: When an application uses multiple [Transformer](/Reference/uCalcBase/Transformer/Constructor) instances with different token configurations, you can print the `Description` of the active [Tokens](/Reference/uCalcBase/Tokens/Constructor) object to immediately understand which set of lexical rules is being applied.

*   **Self-Documentation**: Store a human-readable note directly on the token set to explain its purpose, such as "Strict JSON Tokenizer" vs. "Flexible Config File Tokenizer". This keeps the documentation tightly coupled with the object it describes.

*   **Runtime Identification**: Use descriptions to programmatically identify specific token configurations. For example, you could iterate through a collection of transformers and activate only those whose token sets have a description matching "Version 2.0 Syntax".

## 💡 Why uCalc? (Comparative Analysis)

Without an integrated `Description` property, developers often resort to less ideal solutions for tracking metadata:

*   **vs. Code Comments**: Standard code comments are static and cannot be accessed by the program at runtime. A `Tokens` description is dynamic data that can be queried, displayed, or used in application logic.

*   **vs. External Dictionaries**: Managing an external dictionary (e.g., `Dictionary<Tokens, string>`) to map token sets to their descriptions is cumbersome. It requires manual synchronization, and if a `Tokens` object is released, the dictionary entry can become a memory leak. uCalc's integrated approach is safer, cleaner, and more efficient.

**Examples:**

### Example ID: 1033

**Description:** Demonstrates the basic getter and setter functionality of the Description property.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var tokens = t.@Tokens();

// Set a description
tokens.@Description("Default token set for general purpose parsing.");

// Get the description
wl(tokens.@Description())
```

**Output:**
```
Default token set for general purpose parsing.
```

---

### Example ID: 1034

**Description:** Uses descriptions to identify and differentiate between two separate token configurations at runtime.

**Code:**
```pseudocode
// Create two transformers with different token configurations
New(uCalc::Transformer, strict_t)
strict_t.@Tokens().@Description("Strict Mode: only 'is' as a whole word.");

New(uCalc::Transformer, flexible_t)
flexible_t.@Tokens().@Description("Flexible Mode: matches 'is' inside other words.");
flexible_t.@Tokens().Clear();
flexible_t.@Tokens().Add("."); // Match by character

var(string, text) = "This island is nice.";

strict_t.FromTo("is", "[MATCH]");
flexible_t.FromTo("is", "[MATCH]");

wl(strict_t.@Tokens().@Description())
wl("Result: ", strict_t.Transform(text))
wl("")
wl(flexible_t.@Tokens().@Description())
wl("Result: ", flexible_t.Transform(text))
```

**Output:**
```
Strict Mode: only 'is' as a whole word.
Result: This island [MATCH] nice.

Flexible Mode: matches 'is' inside other words.
Result: Th[MATCH] [MATCH]land [MATCH] nice.
```

---

### Example ID: 1035

**Description:** Internal Test: Verifies that descriptions are copied when token sets are imported, but remain independent afterward.

**Code:**
```pseudocode
New(uCalc::Transformer, t1)
t1.@Tokens().@Description("Original Description");

// Create a new transformer and import tokens from t1
New(uCalc::Transformer, t2)
t2.@Tokens().Add(t1.@Tokens());

wl("t2's initial description (copied from t1): ", t2.@Tokens().@Description())

// Modify t2's description
t2.@Tokens().@Description("Modified Description");

wl("t2's new description: ", t2.@Tokens().@Description())
wl("t1's description remains unchanged: ", t1.@Tokens().@Description())
```

**Output:**
```
t2's initial description (copied from t1): Original Description
t2's new description: Modified Description
t1's description remains unchanged: Original Description
```

---

### Example ID: 155

**Description:** Transformer: Matching by tokens vs match by character; also whitespace sensitivity

**Code:**
```pseudocode
// This examples shows the default match by
// token mode, as well as how to reconfigure
// it in order to do match by character
// along with a whitespace variation

var t = uc.NewTransformer();
var txt = "This is an island test, I said.";
t.FromTo("is", "<is>");

wl(t.Transform(txt))
wl("")

t.@Tokens().@Description("Match by character");
t.@Tokens().Add("."); // This overrides existing tokens
t.FromTo("is", "<is>");
wl(t.@Tokens().@Description())
wl(t.Transform(txt))
wl("")

// Note: whitespace sensitivity is off by default
// Whitespace token is re-introduced
// (after being overridden in the previous Token Add())
t.@Tokens().@Description("By char + whitespace ignored");
t.@Tokens().Add("[\\t\\v ]+", TokenType::Whitespace);
t.FromTo("is", "<{@Self}>");
wl(t.@Tokens().@Description())
wl(t.Transform(txt))
```

**Output:**
```
This <is> an island test, I said.

Match by character
Th<is> <is> an <is>land test, I said.

By char + whitespace ignored
Th<is> <is> an <is>land test, <I s>aid.
```

---

---

## Handle - ID: 382
/doc/reference/classes/ucalc.tokens/handle/

**Description:** Returns the handle of an object

**Syntax:** Handle()
**Return:** Tokens - 
**Remarks:**

Mostly for internal use.

Each object has a handle, which is used to communicate with the uCalc library.  It may not have other uses cases beyond troubleshooting.

---

## Indexer[] - ID: 933
/doc/reference/classes/ucalc.tokens/indexer[]/

**Syntax:** Indexer[]()
**Return:**  - 
---

## IndexOf - ID: 383
/doc/reference/classes/ucalc.tokens/indexof/

**Description:** Gets the zero-based index of a token definition, which determines its precedence in the matching order.

**Syntax:** IndexOf(Item)
**Parameters:**
tokenItem - Item - The `Item` object representing the token definition whose index is to be found.
**Return:** int32 - The zero-based index of the token definition in the collection, representing its precedence rank. Returns -1 if the token is not found.
**Remarks:**

The `IndexOf` method finds the zero-based position of a specific token definition within the collection. This index is not just an arbitrary position; it directly corresponds to the token's **precedence**.

### ⚙️ Precedence: Higher Index Wins

uCalc's tokenizer evaluates token patterns in a **Last-In, First-Out (LIFO)** order. This means:
*   The **most recently added** token has the **highest index** (`Count() - 1`) and is checked first.
*   The **first token added** (or the oldest built-in token) has the **lowest index** (`0`) and is checked last.

A higher index means higher precedence. This method is the primary tool for programmatically querying the precedence rank of any token.

### 🎯 Use Cases
*   **Debugging**: Verify the order in which tokens are being evaluated to resolve matching conflicts.
*   **Dynamic Analysis**: Write code that can inspect a `Tokens` collection and understand its precedence hierarchy at runtime.
*   **Advanced Configuration**: Programmatically insert tokens at specific indices (using other overloads of `Add` or `Insert`) and then use `IndexOf` to confirm their final precedence.

If the specified token is not found in the collection, the method returns `-1`.

### 💡 Why uCalc? (Comparative Analysis)

*   **vs. Static Lexers (ANTLR, Flex/Bison)**: In traditional parser generators, token precedence is often implicit, determined by the order of rules in a static grammar file. There is no simple, programmatic way to query a token's rank at runtime. uCalc's `IndexOf` makes precedence a first-class, inspectable property of its dynamic lexical model.

*   **vs. Standard `IndexOf`**: Unlike a typical `IndexOf` method that just finds an element's position in a list, this method's return value has direct semantic meaning for the parser's behavior. This makes it a powerful introspection tool rather than a simple collection utility.

**Examples:**

### Example ID: 1036

**Description:** How adding tokens affects their index and, therefore, their precedence.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var tokens = t.@Tokens();
tokens.Clear();
tokens.Add("."); // Add a fallback token at index 0

// The order of definition determines the index (precedence)
var tokenA = tokens.Add("A");
var tokenB = tokens.Add("B");

wl("Index of A: ", tokens.IndexOf(tokenA)) // Will have a lower index
wl("Index of B: ", tokens.IndexOf(tokenB)) // Will have a higher index, thus higher precedence
```

**Output:**
```
Index of A: 1
Index of B: 2
```

---

### Example ID: 1037

**Description:** Internal Test: Verifies the LIFO precedence order and the return value for a token not present in the collection.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var tokens = t.@Tokens();
tokens.Clear();
tokens.Add("."); // Fallback

var tokenPlus = tokens.Add("[+]");
var tokenStar = tokens.Add("[*]");
var tokenCaret = tokens.Add("^");

// LIFO order means precedence is: '^' > '*' > '+'
wl("Precedence Check:")
wl("Caret (^) > Star (*): ", bool(tokens.IndexOf(tokenCaret) > tokens.IndexOf(tokenStar)))
wl("Star (*) > Plus (+): ", bool(tokens.IndexOf(tokenStar) > tokens.IndexOf(tokenPlus)))

// Test for a token not in this collection
New(uCalc::Transformer, t2)
var unaddedToken = t2.@Tokens().Add("unrelated");
wl("Index of un-added token: ", tokens.IndexOf(unaddedToken))
```

**Output:**
```
Precedence Check:
Caret (^) > Star (*): True
Star (*) > Plus (+): True
Index of un-added token: -1
```

---

### Example ID: 70

**Description:** Displays the complete list of default token definitions, showing their type, internal name, and regex pattern.

**Code:**
```pseudocode
// Lists all tokens currently defined for the expression evaluator.

wl("Token Count: ", uc.@ExpressionTokens().@Count())
wl("")
wl("Index  Type  Name: regex")
wl("========================")
var Tokens = uc.@ExpressionTokens();
foreach (var token in Tokens)
   w(Tokens.IndexOf(token))
   wl("  ", token.@Description(), "  ", token.@Name(), ": ", token.@Regex())
end for

// Note that the expression evaluator token list has a few extra tokens,
// related to hex/bin/oct notation, string interpolation, and imaginary number
// notation, which are not found in the default Transformer token list.
```

**Output:**
```
Token Count: 30

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
27  literal  _token_imaginaryunit: #i
28  tokentransform  _token_binaryhexoctalnotation: #[bho][0-9A-F]+
29  tokentransform  _token_stringinterpolationquote: \$['"]
```

---

---

## Insert - ID: 384
/doc/reference/classes/ucalc.tokens/insert/

**Description:** Defines a new token and inserts it at a specific position in the precedence list, providing explicit control over its matching priority.

**Syntax:** Insert(int32, string, TokenType, string, int, RegExGrammar)
**Parameters:**
insertionIndex - int32 - The index where the new token definition will be inserted. Positive values (`0`, `1`, `2`...) specify an absolute position from the beginning (lowest precedence). Negative values (`-1`, `-2`...) specify a position relative to the end (highest precedence).
regexPattern - string - The regular expression that defines the token's pattern.
tokenType - TokenType [default = TokenType::Generic] - The lexical category of the token, which determines its parsing behavior.
closingBracketRegex - string [default = ""] - An optional regex pattern for the corresponding closing bracket if this token is an opening bracket.
subMatchGroup - int [default = 0] - The 1-based index of a capture group within the regex. If greater than 0, the content of this group is used as the token's value instead of the entire match.
regexGrammar - RegExGrammar [default = RegExGrammar::Default] - The regular expression grammar to use for parsing the pattern.
**Return:** Item - Returns the newly created token as an [Item](/Reference/uCalcBase/Item) object, which can be used to further configure its properties.
**Remarks:**

The `Insert` method is a convenience overload for the [Add](/Reference/uCalcBase/Tokens/Add/Add(string_view,TokenType,string_view,size_t,RegExGrammar,int32_t)) method that emphasizes control over a token's **precedence**. It allows you to define a new token and specify its exact position in the token evaluation list.

### ⚙️ Understanding Token Precedence & `insertionIndex`

uCalc's tokenizer evaluates token patterns in a **Last-In, First-Out (LIFO)** order. By default, the most recently added token has the highest index and is checked first, giving it the highest precedence. The `insertionIndex` parameter allows you to override this default behavior with fine-grained control.

| Index Type          | Value         | Behavior                                                                                                              |
| :------------------ | :------------ | :-------------------------------------------------------------------------------------------------------------------- |
| **Positive (Absolute)** | `0`           | Inserts at the very beginning of the list, giving the token the **lowest possible precedence**.                     |
|                     | `1`, `2`, ... | Inserts at the specified absolute index, pushing subsequent tokens to a higher index.                                 |
| **Negative (Relative)** | `-1`          | Appends to the end of the list, giving the token the **highest possible precedence** (same as default `Add`).      |
|                     | `-2`, `-3`, ... | Inserts relative to the end of the list (`-2` is second to last), allowing for high-precedence positioning. |

### Why Use `Insert` vs. `Add`?

While [Add](/Reference/uCalcBase/Tokens/Add/Add(string_view,TokenType,string_view,size_t,RegExGrammar,int32_t)) also has an `insertionIndex` parameter, `Insert` makes the intent clearer when precedence is your primary concern. It is the ideal tool for implementing classic lexer design patterns, such as defining specific keywords with high precedence and a general-purpose identifier with low precedence.

### 💡 Comparative Analysis

In traditional compiler tools like ANTLR or Flex/Bison, token precedence is often determined by the order of rules in a static grammar file. To change a token's priority, you must edit the file and recompile.

uCalc's `Insert` method is part of a fully **dynamic and programmatic** system. You can add, remove, and reorder tokens at runtime, allowing for unparalleled flexibility in creating adaptive or user-configurable parsers. This is a significant advantage over static parsing systems.

**Examples:**

---

## MemoryIndex = [int] - ID: 611
/doc/reference/classes/ucalc.tokens/memoryindex-=-[int]/

**Description:** Returns the unique index value associated with the object

**Remarks:**

Mostly for internal use.

Each object has an integer index value that is unique to the object within the class.  Unlike the [topic: Handle] value that may change each time you run uCalc, the MemoryIndex value is predictable.

This function may not have other uses cases beyond troubleshooting.

---

## Remove - ID: 389
/doc/reference/classes/ucalc.tokens/remove/

**Description:** Dynamically removes a token definition from the collection, altering the parser's lexical rules at runtime.

**Syntax:** Remove(Item)
**Parameters:**
tokenItem - Item - The `Item` object representing the token definition to remove. This is typically obtained via `ByName()` or `ByType()`.
**Return:** void - 
**Remarks:**

# 🗑️ Dynamically Removing Token Definitions

The `Remove` method allows you to dynamically alter the behavior of the tokenizer at runtime by deleting a specific token definition. Once a token is removed, the parser will no longer recognize that pattern, which can fundamentally change how an input string is processed.

This method is a key part of uCalc's dynamic lexical analysis engine, enabling you to restrict or customize a language's syntax on the fly.

## ⚙️ How It Works

To remove a token, you must first get a handle to its [Item](/reference/ucalcbase/item/constructor) object. This is typically done by querying the [Tokens](/reference/ucalcbase/tokens/constructor) collection using methods like [ByName()](/reference/ucalcbase/tokens/byname) or [ByType()](/reference/ucalcbase/tokens/bytype).

```pseudocode
// Get the token for single-quoted strings
var singleQuoteToken = myTransformer.Tokens().ByName("_token_string_singlequoted");

// Remove it from the collection
myTransformer.Tokens().Remove(singleQuoteToken);
```

After removal, any text that previously matched the token's pattern will be tokenized by the next-highest-precedence token that matches it, often a more generic "catch-all" token.

## 🎯 Primary Use Cases

*   **Restricting Syntax**: Create a "safe" or simplified version of a language by removing tokens for features you want to disable. For example, you could remove the token for comments to disallow them.
*   **Replacing a Built-in Token**: The standard pattern for modifying a built-in token is to `Remove` the default version and then [Add()](/reference/ucalcbase/tokens/add) a new one with a custom regex pattern. This allows you to extend the language, for instance, by allowing new characters in identifiers.
*   **Resolving Ambiguity**: If two token patterns are conflicting, removing one can resolve the ambiguity and ensure the desired token is matched.

## 💡 Why uCalc? (Comparative Analysis)

In traditional compiler development with tools like **ANTLR** or **Flex/Bison**, lexical rules are static and defined in a separate grammar file. Changing a token definition requires modifying that file, regenerating parser code, and recompiling the application. This is a compile-time, static process.

uCalc's token system is entirely **dynamic and programmatic**. `Remove` is a key part of this dynamism. It allows your application to:

*   **Modify Syntax at Runtime**: Your code can re-categorize or remove tokens on the fly, effectively switching between different language "dialects" without a restart.
*   **Create Adaptable Parsers**: Build tools that can be configured by the end-user to support different comment styles or literal formats by enabling or disabling specific tokens.

This runtime flexibility provides a significant advantage over static parsing systems. For clearing all tokens at once, see the [Clear()](/reference/ucalcbase/tokens/clear) method.

**Examples:**

### Example ID: 1046

**Description:** Practical: Demonstrates how removing the token for single-quoted strings causes the parser to treat the quote and its contents as individual generic tokens.

**Code:**
```pseudocode
// This example removes the single-quoted string token.
New(uCalc::Transformer, t)
var(string, txt) = "This is a test, 'This is a test'";
t.FromTo("{token:1}", "<{@Self}>");

wl("--- Before Removing Token ---")
// Initially, 'This is a test' is treated as a single token.
wl(t.Transform(txt).@Text())

// Now, find and remove the token definition for single-quoted strings.
var singleQuoteToken = t.@Tokens().ByName("_token_string_singlequoted");
t.@Tokens().Remove(singleQuoteToken);

// Re-run the transform. The text must be set again to be re-tokenized.
t.@Text(txt);
wl("")
wl("--- After Removing Token ---")
// Now, the single quote is a generic token, as are the words inside it.
wl(t.Transform().@Text())
```

**Output:**
```
--- Before Removing Token ---
<This> <is> <a> <test><,> <'This is a test'>

--- After Removing Token ---
<This> <is> <a> <test><,> <'><This> <is> <a> <test><'>
```

---

### Example ID: 1047

**Description:** Internal Test: Removes the core alphanumeric token to verify that the tokenizer falls back to character-by-character tokenization.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var(string, text) = "word game";
t.FromTo("{token:1}", "[{@Self}]");

wl("--- Before Remove ---")
// By default, 'word' is a single alphanumeric token.
wl(t.Transform(text))

// Remove the alphanumeric token definition.
var alphaToken = t.@Tokens().ByName("_token_alphanumeric");
t.@Tokens().Remove(alphaToken);

// The transformer must be reset with the original text for the change to apply.
t.@Text(text);

wl("")
wl("--- After Remove ---")
// Now, 'word' is no longer a single token. The fallback '.' token
// matches each character individually.
wl(t.Transform())
```

**Output:**
```
--- Before Remove ---
[word] [game]

--- After Remove ---
[w][o][r][d] [g][a][m][e]
```

---

### Example ID: 169

**Description:** Token Remove

**Code:**
```pseudocode
// This example removes the single quote pattern from the list

var t = uc.NewTransformer();
var txt = "This is a test, 'This is a test'";
t.FromTo("{token:1}", "<{@Self}>");
wl(t.Transform(txt).@Text())

// Now the ' character will no longer be special
// (see the Name() example for list of token names
t.@Tokens().Remove(t.@Tokens()["_token_string_singlequoted"]);
wl(t.Transform(txt).@Text())
```

**Output:**
```
<This> <is> <a> <test><,> <'This is a test'>
<This> <is> <a> <test><,> <'><This> <is> <a> <test><'>
```

---

---

## uCalc = [uCalc] - ID: 544
/doc/reference/classes/ucalc.tokens/ucalc-=-[ucalc]/

**Description:** Retrieves the parent uCalc instance that owns this token collection, providing access to the full execution context.

**Remarks:**

# 🧭 Navigating the Hierarchy: `Tokens.uCalc`

Every `Tokens` object exists within the context of a parent [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance. It either belongs directly to the `uCalc` instance (like [ExpressionTokens](/Reference/uCalcBase/uCalc/ExpressionTokens)) or to a [Transformer](/Reference/uCalcBase/Transformer/Constructor) which is, in turn, owned by a `uCalc` instance. This property provides the crucial link back to that root `uCalc` engine, allowing you to navigate "up" the object hierarchy.

This is essential for introspection and for writing context-aware lexical rules.

## 🎯 Primary Use Cases

1.  **Contextual Operations**: The most common use is to perform another operation within the same context as the token set. If you have a [Tokens](/Reference/uCalcBase/Tokens/Constructor) object but not a direct reference to its parent `uCalc` instance, you can use this property to retrieve it and call methods like [Eval()](/Reference/uCalcBase/uCalc/Eval) or [DefineVariable()](/Reference/uCalcBase/uCalc/DefineVariable).

2.  **Instance Introspection**: It allows you to determine if two different `Tokens` collections belong to the same execution context, which is invaluable for debugging applications that manage multiple, isolated uCalc instances.

3.  **Accessing Sibling Collections**: Once you retrieve the parent instance, you can use it to find other `Tokens` collections, for example: [pseudocode]`myTokens.@uCalc().@ExpressionTokens()`.

## 💡 Why uCalc? (Comparative Analysis)

This parent-child relationship is a common design pattern for creating navigable object trees.

*   **vs. DOM (Document Object Model)**: The relationship between a `Tokens` collection and its parent `uCalc` instance is analogous to an HTML element and its `ownerDocument` property in the DOM. It provides a structured, predictable way to traverse the hierarchy of your parsing logic.

*   **vs. Ad-Hoc Management**: Without this built-in link, you would need to manually track which `uCalc` instance owns which `Tokens` collection, likely using external dictionaries or wrapper classes. This is complex and error-prone. By making `uCalc` a first-class property, uCalc provides a clean, reliable, and integrated solution for managing the relationship between lexical rules and their execution context.

**Examples:**

### Example ID: 1048

**Description:** Retrieves a Tokens collection's parent uCalc instance and verifies its identity by reading a description.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@uCalc().@Description("My Parent uCalc");
var tokens = t.@Tokens();

// Get the parent from the Tokens object
var parent_uc = tokens.@uCalc();

// Verify we got the correct parent
wl(parent_uc.@Description())
```

**Output:**
```
My Parent uCalc
```

---

### Example ID: 1049

**Description:** Uses the parent uCalc context from a Tokens object to define a variable that is then used by a transformer rule.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var tokens = t.@Tokens();

// Use the parent uCalc instance to define a variable
tokens.@uCalc().DefineVariable("replacement = 'REPLACED'");

t.FromTo("original", "{@Eval: replacement}");

wl(t.Transform("Test of original value."))
```

**Output:**
```
Test of REPLACED value.
```

---

### Example ID: 1050

**Description:** Internal Test: Verifies instance isolation by ensuring Tokens collections from different uCalc instances correctly resolve to their respective parents.

**Code:**
```pseudocode
New(uCalc, uc1)
New(uCalc, uc2)

New(uCalc::Transformer, t1(uc1))
New(uCalc::Transformer, t2(uc2))

var tokens1 = t1.@Tokens();
var tokens2 = t2.@Tokens();

var parent1 = tokens1.@uCalc();
var parent2 = tokens2.@uCalc();

wl("tokens1 belongs to uc1: ", bool(parent1.Handle() == uc1.Handle()))
wl("tokens2 belongs to uc2: ", bool(parent2.Handle() == uc2.Handle()))
wl("tokens1 does not belong to uc2: ", bool(parent1.Handle() != uc2.Handle()))
```

**Output:**
```
tokens1 belongs to uc1: True
tokens2 belongs to uc2: True
tokens1 does not belong to uc2: True
```

---

### Example ID: 171

**Description:** uCalc Description

**Code:**
```pseudocode
uc.@Description("This is the main uCalc object");
var t = uc.NewTransformer();
wl(t.@Tokens().@uCalc().@Description())
```

**Output:**
```
This is the main uCalc object
```

---

---

## uCalc.Transformer - ID: 391
/doc/reference/classes/ucalc.transformer/

**Description:** uCalc transformer class

---

## Introduction - ID: 970
/doc/reference/classes/ucalc.transformer/introduction/

**Description:** An overview of the uCalc.Transformer class, a token-aware engine for pattern matching, data extraction, and structural text replacement.

**Remarks:**

# 🧠 uCalc.Transformer: The Smart Text Engine

The [uCalc.Transformer](/Reference/uCalcBase/Transformer/Constructor) class is a powerful, token-aware engine for finding, replacing, and restructuring text. It serves as a more intelligent and safer alternative to traditional tools like Regular Expressions (Regex), especially when working with structured data such as source code, configuration files, or markup languages.

While the [uCalc.String](/Reference/uCalcBase/String/Constructor) class is ideal for simple, fluent, "one-liner" manipulations, the [Transformer](/Reference/uCalcBase/Transformer/Constructor) is the tool of choice for building robust, rule-based systems. It is the engine that powers static analysis, code refactoring, transpilation, and complex data extraction tasks.

---

## Core Concepts: Beyond Simple String Replacement

The Transformer's power comes from a few fundamental concepts that set it apart from character-based tools.

### 1. Token-Awareness: The Key to Safety
This is the most critical difference between the Transformer and Regex. Before any matching occurs, the Transformer's tokenizer breaks the input string into a stream of meaningful **tokens**: words, numbers, operators, string literals, and comments. This structural awareness prevents common and dangerous bugs, such as accidentally changing text inside a string literal or a user-defined comment structure. For a detailed comparison, see the [Structural Awareness (Tokens vs. Regex)](/Tutorials/Beyond-the-Basics-What-Makes-uCalc-Special/Structural-Awareness-Tokens-vs-Regex) topic.

### 2. Declarative, Readable Patterns
Transformer rules are defined using a declarative [pattern syntax](/Reference/Patterns/Introduction/Syntax-Definitions) that is designed to be human-readable, using clear, token-based patterns with anchors, variables, and token categories. This makes rules easier to write, debug, and maintain.

### 3. Intelligent Replacements
Replacements can include backreferences, conditional logic, and even embedded expressions using [`{@Eval}`](/Reference/Patterns/Pattern-Methods/{@Eval}) to perform calculations or call functions during the replacement. See the [Executing Logic in Replacements](/Tutorials/Text-Transformation-The-Transformer/Executing-Logic-in-Replacements) tutorial.

### 4. Hierarchical & Multi-Pass Processing
For nested data formats, the [LocalTransformer](/Reference/uCalcBase/Rule/LocalTransformer) property enables hierarchical parsing. For complex, multi-stage transformations, you can define a sequence of [Passes](/Reference/uCalcBase/Transformer/Pass), creating a powerful processing pipeline.

---

## Class Members Overview

### ▶️ Core Operation Methods
These methods execute the transformation process.

| Member | Description |
| :--- | :--- |
| [`Find`](/Reference/uCalcBase/Transformer/Find) | Executes a read-only search, populating the matches collection without modifying the text. |
| [`Transform`](/Reference/uCalcBase/Transformer/Transform) | Applies all defined rules to the text, performing find-and-replace operations. |
| [`Filter`](/Reference/uCalcBase/Transformer/Filter) | Extracts and transforms all matches, returning a new string composed only of the results. |
| [`TraceTransform`](/Reference/uCalcBase/Transformer/TraceTransform) | Captures each intermediate step of a cascading transformation for debugging. |

### ✍️ Rule Definition Methods
These methods define the patterns for the transformer to find.

| Member | Description |
| :--- | :--- |
| [`FromTo`](/Reference/uCalcBase/Transformer/FromTo) | Defines a find-and-replace rule that transforms text matching a pattern. |
| [`Pattern`](/Reference/uCalcBase/Transformer/Pattern) | Defines a find-only search pattern that locates text without replacing it. |
| [`SkipOver`](/Reference/uCalcBase/Transformer/SkipOver) | Defines a pattern for text that should be ignored by all other rules. |

### 🧐 Introspection & Results
These properties provide access to the results and state of the transformer.

| Member | Description |
| :--- | :--- |
| [`Matches`](/Reference/uCalcBase/Transformer/Matches) | Retrieves the collection of all matches found by the most recent operation. |
| [`GetMatches`](/Reference/uCalcBase/Transformer/GetMatches) | Retrieves the collection of matches with options to filter the result set. |
| [`Text`](/Reference/uCalcBase/Transformer/Text) | Gets or sets the primary source text string for the transformer. |
| [`WasModified`](/Reference/uCalcBase/Transformer/WasModified) | Checks if the most recent operation resulted in any changes to the text. |
| [`Description`](/Reference/uCalcBase/Transformer/Description) | Gets or sets a user-defined description for the transformer instance. |

### ⚙️ Configuration & Settings
These properties control the transformer's behavior.

| Member | Description |
| :--- | :--- |
| [`Tokens`](/Reference/uCalcBase/Transformer/Tokens) | Provides access to the collection of token definitions for customizing lexical rules. |
| [`DefaultRuleSet`](/Reference/uCalcBase/Transformer/DefaultRuleSet) | Gets a template rule for defining default properties for all new rules. |
| [`GlobalRuleSet`](/Reference/uCalcBase/Transformer/GlobalRuleSet) | Gets a rule for defining global, cumulative properties across all rules in a pass. |
| [`Range`](/Reference/uCalcBase/Transformer/Range) | Restricts all subsequent operations to a specific character range within the source text. |

### 🧬 Lifetime Management
These methods manage the transformer's memory and lifecycle.

| Member | Description |
| :--- | :--- |
| [`Constructor`](/Reference/uCalcBase/Transformer/Constructor) | Creates a new transformer instance. |
| [`Clone`](/Reference/uCalcBase/Transformer/Clone) | Creates an identical, independent copy of the transformer, including all its rules and settings. |
| [`Release`](/Reference/uCalcBase/Transformer/Release) | Explicitly frees all memory and resources associated with the transformer. |
| [`Reset`](/Reference/uCalcBase/Transformer/Reset) | Clears the transformer's state for reuse without creating a new instance. |
| [`Owned`](/Reference/uCalcBase/Transformer/Owned) | Enables RAII-style automatic memory release, primarily for C++. |

### ⛓️ Multi-Pass & Advanced Methods
These methods enable complex, multi-stage transformations.

| Member | Description |
| :--- | :--- |
| [`Pass`](/Reference/uCalcBase/Transformer/Pass) | Creates or retrieves a sequential transformation stage (a pass). |
| [`PassCount`](/Reference/uCalcBase/Transformer/PassCount) | Returns the number of defined transformation passes. |
| [`Setup`](/Reference/uCalcBase/Transformer/Setup) | Creates a dedicated initialization pass that executes before the main transformation rules. |

**Examples:**

### Example ID: 1141

**Description:** A simple find-and-replace transformation to replace all occurrences of a word.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Define a simple replacement rule
t.FromTo("Hello", "Greetings");

// Execute the transformation on an input string
t.@Text("Hello World, and Hello again.");
wl(t.Transform())
```

**Output:**
```
Greetings World, and Greetings again.
```

---

### Example ID: 1123

**Description:** How `SkipOver` creates 'dead zones' where other rules are not applied.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("transform this but (not this) and this");

// A rule to replace the word 'this'
t.FromTo("this", "THAT");

// A rule to ignore any content inside parentheses
t.SkipOver("({content})");

// The 'this' inside the parentheses is protected by the SkipOver rule
wl(t.Transform())
```

**Output:**
```
transform THAT but (not this) and THAT
```

---

---

## (Constructor) - ID: 657
/doc/reference/classes/ucalc.transformer/-constructor/

**Description:** Creates a new, token-aware text transformation engine for pattern matching and structural replacement.

**Remarks:**

# ⚙️ The Transformer Engine

The `Transformer` constructor creates an instance of uCalc's powerful text transformation engine. Unlike standard regular expressions that operate on raw characters, a `Transformer` operates on **tokens**—the fundamental building blocks of a language (words, numbers, operators, etc.). This makes it inherently aware of structure, allowing it to safely and reliably parse complex, nested text that would be difficult or impossible to handle with Regex.

A new `Transformer` instance can be created in several ways, allowing you to control its context and lexical rules.

## Constructor Overloads

### 1. [pseudocode]`New(Transformer, t)`
Creates a new transformer using the default [uCalc](/Reference/uCalcBase/uCalc) instance for its context and token set. This is the simplest way to create a transformer for general use.

### 2. [pseudocode]`New(Transformer, t(ucalcInstance))`
Creates a new transformer within the context of a specific `uCalc` instance. This is the preferred method when working with multiple, isolated parsing environments.

### 3. [pseudocode]`New(Transformer, t(tokensToInherit))`
Creates a new transformer that inherits a *copy* of the lexical rules from an existing [Tokens](/Reference/uCalcBase/Tokens/Constructor) collection. This is ideal for sharing a custom tokenizer configuration across multiple transformers.

## 💡 Why uCalc? (Transformer vs. Regex)

| Feature | Standard Regex | uCalc Transformer |
| :--- | :--- | :--- |
| **Awareness** | Character-based. Unaware of structure. | **Token-based**. Understands numbers, strings, and operators as units. |
| **Nested Brackets** | Fails on nested structures like `func(a, (b+c))`. | Handles nested brackets `()`, `[]`, `{}` automatically by default. |
| **Readability** | Dense, cryptic patterns (e.g., `(?<=\s)\d+(?=\s))`). | Clean, declarative patterns (e.g., `{@Number}`). |
| **Safety** | Can accidentally match inside string literals or comments. | Respects string and comment boundaries by default (`QuoteSensitive`). |

## 🧰 The Transformer-String Equivalence

A `Transformer` and a [uCalc.String](/Reference/uCalcBase/String/Constructor) are two different interfaces for the same underlying object. You can seamlessly convert between them. This allows you to build a string using the `uCalc.String` API and then immediately apply transformation rules to it by treating it as a `Transformer`.

## 🧠 Memory Management

A `Transformer` object holds significant resources and must be released when no longer needed to prevent memory leaks.

*   **C# / VB.NET**: Use the `using` statement for automatic release.
*   **C++**: For stack-allocated transformers, call [Owned()](/Reference/uCalcBase/Transformer/Owned) to enable RAII-style automatic cleanup.

**Examples:**

### Example ID: 1141

**Description:** A simple find-and-replace transformation to replace all occurrences of a word.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Define a simple replacement rule
t.FromTo("Hello", "Greetings");

// Execute the transformation on an input string
t.@Text("Hello World, and Hello again.");
wl(t.Transform())
```

**Output:**
```
Greetings World, and Greetings again.
```

---

### Example ID: 188

**Description:** Transformer constructor

**Code:**
```pseudocode
wl("Transformer constructors")
New(uCalc::Transformer, t1) // New transformer in default uCalc space
New(uCalc::Transformer, t2(uc)) // New transformer inherits
New(uCalc::Transformer, t3(t1.@Tokens())) // Imports tokens from t1
```

**Output:**
```
Transformer constructors
```

---

### Example ID: 154

**Description:** To_uCalcString

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("if (x > 3) y = x * 2; else if(x == 5) y = x - 1;");
t.FromTo("1", "100");
t.Transform();

var Pattern = "if ({cond})";
wl([NotCpp]new [/NotCpp] uCalc::String(t).After(Pattern).@Text())
wl([NotCpp]new [/NotCpp] uCalc::String(t).After(Pattern).After(Pattern))

New(uCalc::String, s)
s = "This is a test";
wl([NotCpp]new [/NotCpp] uCalc::Transformer(s).@Text())
```

**Output:**
```
y = x * 2; else if(x == 5) y = x - 100;
 y = x - 100;
This is a test
```

---

---

## Clone - ID: 504
/doc/reference/classes/ucalc.transformer/clone/

**Description:** Creates an identical, yet completely independent, copy of the Transformer object, including all its rules and settings.

**Syntax:** Clone()
**Return:** Transformer - A new, independent Transformer instance that is a complete replica of the original.
**Remarks:**

The `Clone` method creates a deep, independent copy of a `Transformer` object. This is a highly efficient operation, as it duplicates the transformer's internal state directly in memory, which is significantly faster than creating a new transformer and redefining all its rules and tokens from scratch.

### What is Cloned?
A clone is a complete replica of the original `Transformer`'s state at the moment of cloning, including:
*   **All Rules**: Every `FromTo` and `Pattern` rule is copied.
*   **Tokens**: The entire collection of token definitions is duplicated.
*   **Text**: The current source string held by the transformer is copied.
*   **Settings**: All default rule settings (`CaseSensitive`, `WhitespaceSensitive`, etc.) are preserved.

Once created, the clone is completely independent; modifying the clone will not affect the original, and vice-versa.

### 🎯 Primary Use Cases

1.  **Performance Optimization**: Parsing a complex set of rules and token definitions can be computationally expensive. If you need to use the same configuration repeatedly, you should configure it once, and then `Clone` the `Transformer` object as needed. This avoids the high cost of repeated setup.

2.  **Templating**: `Clone` is perfect for creating a "template" pattern. You can create a base `Transformer` with a standard set of rules (e.g., for parsing a specific language or format). Then, for different tasks, you can `Clone` this base and add a few specialized rules to the clone, promoting modularity and reuse.

3.  **Isolation & Sandboxing**: Create a clone to experiment with temporary rules or transformations without altering the state of the original, master `Transformer`.

### `Transformer.Clone()` vs. `uCalc.Clone()`

It is crucial to understand the difference between cloning a `Transformer` and cloning the entire `uCalc` engine:

| Method | What It Copies | Parent `uCalc` Instance |
| :--- | :--- | :--- |
| **`Transformer.Clone()`** (This Method) | A **single `Transformer` object**. | The clone belongs to the **same** parent `uCalc` instance as the original. | 
| [`uCalc.Clone()`](/Reference/uCalcBase/uCalc/Clone) | The **entire `uCalc` engine**, including all variables, functions, and every `Transformer` within it. | The clone creates a **new, isolated** parent `uCalc` instance. |

### Memory Management

A cloned `Transformer` object holds resources and must be released when no longer needed to prevent memory leaks. This can be done explicitly with [`Release()`](/Reference/uCalcBase/Transformer/Release) or automatically using language-specific scoping constructs like `using` in C# or `Owned()` in C++.

**Examples:**

### Example ID: 1054

**Description:** Demonstrating that a clone is independent and that modifying it does not affect the original.

**Code:**
```pseudocode
// 1. Create and configure the original transformer
New(uCalc::Transformer, t1)
t1.FromTo("A", "B");
wl("Original Transform: ", t1.Transform("A C A"))

// 2. Clone it
var t2 = t1.Clone();

// 3. Modify the clone. This does not affect the original.
t2.FromTo("C", "D");
wl("Cloned Transform:   ", t2.Transform("A C A"))

// 4. Verify original is unchanged by re-running its transform
wl("Original is Unchanged: ", t1.Transform("A C A"))
t2.Release();
t1.Release();
```

**Output:**
```
Original Transform: B C B
Cloned Transform:   B D B
Original is Unchanged: B C B
```

---

### Example ID: 1055

**Description:** A practical example using Clone() to create a specialized parser from a base template, demonstrating rule inheritance.

**Code:**
```pseudocode
// 1. Create a "base" HTML transformer template
New(uCalc::Transformer, baseHtmlParser)
baseHtmlParser.@Description("Base HTML Parser");
// Rule to skip over comments
baseHtmlParser.SkipOver("<!--{body}->");
// Rule to find any tag
baseHtmlParser.Pattern("<{tag}>");
baseHtmlParser.@DefaultRuleSet().SetStatementSensitive(false);

// 2. Create a specialized clone to find only image tags
var imageParser = baseHtmlParser.Clone();
imageParser.@Description("Image Tag Finder");
imageParser.FromTo("<img {attribs} />", "FOUND_IMG_TAG");

var(string, html) = " <body> <img src='a.jpg' /> <!-- <img src='b.jpg' /> --> </body> ";

// The clone inherits the SkipOver rule from the base, so the commented img tag is ignored.
wl(imageParser.Transform(html))

imageParser.Release();
baseHtmlParser.Release();
```

**Output:**
```
 <body> FOUND_IMG_TAG <!-- <img src='b.jpg' /> --> </body> 
```

---

---

## DefaultRuleSet = [Rule] - ID: 412
/doc/reference/classes/ucalc.transformer/defaultruleset-=-[rule]/

**Description:** Gets a special Rule object that acts as a template, defining the default properties for all new rules created in this Transformer.

**Remarks:**

# ⚙️ The Default Rule Set: A Template for Consistency

The `DefaultRuleSet` property provides access to a special [Rule](/reference/ucalcbase/rule) object that is not used for matching text itself. Instead, it acts as a **prototype or template** for all new rules created within its parent [Transformer](/reference/ucalcbase/transformer). This is a powerful feature for establishing consistent behavior and reducing boilerplate code.

### How It Works

When you create a new rule using [FromTo()](/reference/ucalcbase/transformer/fromto) or [Pattern()](/reference/ucalcbase/transformer/pattern), the new `Rule` object starts with a copy of all the property settings from `DefaultRuleSet`. You can then override these defaults on a per-rule basis.

```pseudocode
// Set a default for all rules in this transformer
t.@DefaultRuleSet().@CaseSensitive(true);

// This rule will now be case-sensitive by default
var rule1 = t.FromTo("HELLO", "HI");

// You can still override it for a specific rule
var rule2 = t.FromTo("world", "there").SetCaseSensitive(false);
```

### Commonly Configured Properties

This is the ideal place to configure behavior that should apply to most or all rules in a transformer:

*   [CaseSensitive](/reference/ucalcbase/rule/casesensitive): Determines if patterns are case-sensitive.
*   [WhitespaceSensitive](/reference/ucalcbase/rule/whitespacesensitive): Controls whether whitespace is significant.
*   [StatementSensitive](/reference/ucalcbase/rule/statementsensitive): Determines if newlines and semicolons act as boundaries.
*   [QuoteSensitive](/reference/ucalcbase/rule/quotesensitive): Controls whether quoted text is treated as an atomic unit.
*   [BracketSensitive](/reference/ucalcbase/rule/bracketsensitive): Enables awareness of nested parentheses and brackets.
*   [RewindOnChange](/reference/ucalcbase/rule/rewindonchange): Enables recursive or cascading transformations.

### 💡 Why uCalc? (Comparative Analysis)

Most regular expression engines handle global settings with flags that apply to the entire regex object (e.g., `RegexOptions.IgnoreCase` in .NET, or the `/i` flag in Perl/JavaScript). This is often an all-or-nothing choice. If you need two patterns with different case sensitivity, you typically need to create two separate regex objects.

uCalc's model is more object-oriented and flexible. The `DefaultRuleSet` provides **instance-level defaults** for a specific `Transformer` object. This offers superior encapsulation, allowing you to have multiple `Transformer` instances with different default behaviors running concurrently. Furthermore, the ability to override these defaults on a per-rule basis provides a powerful, two-tiered configuration system that is not available with simple global regex flags.

**Examples:**

### Example ID: 142

**Description:** WhitespaceSensitive()

**Code:**
```pseudocode
var t = uc.NewTransformer();
var Text = "This is a test.";
var p = t.FromTo("This {words:3}", "[{words}]");

wl("Input: ", Text)
wl("Pattern: ", p.@Pattern())
wl("")

wl("3 captured tokens are in brackets")
wl("")

wl("WhitespaceSensitive = ", bool(t.@DefaultRuleSet().@WhitespaceSensitive()))
wl(t.Transform(Text))
wl("")

t.@DefaultRuleSet().@WhitespaceSensitive(true);
wl("WhitespaceSensitive = ", bool(t.@DefaultRuleSet().@WhitespaceSensitive()))
wl(t.Transform(Text))

```

**Output:**
```
Input: This is a test.
Pattern: This {words:3}

3 captured tokens are in brackets

WhitespaceSensitive = False
[is a test].

WhitespaceSensitive = True
[ is ]a test.
```

---

### Example ID: 140

**Description:** StatementSensitive()

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("x = 1; if (true) func1(3+4); else func2(x*y); y = x + 2");
var p = t.Pattern("if {etc}");

wl("Input: ", t.@Text())
wl("Pattern: ", p.@Pattern())
wl("")

t.Find();
wl("StatementSensitive: ", bool(t.@DefaultRuleSet().@StatementSensitive()))
wl(t.@Matches().@Text())
wl("")

t.@DefaultRuleSet().@StatementSensitive(false);
t.Find();
wl("StatementSensitive: ", bool(t.@DefaultRuleSet().@StatementSensitive()))
wl(t.@Matches().@Text())
```

**Output:**
```
Input: x = 1; if (true) func1(3+4); else func2(x*y); y = x + 2
Pattern: if {etc}

StatementSensitive: True
if (true) func1(3+4)

StatementSensitive: False
if (true) func1(3+4); else func2(x*y); y = x + 2
```

---

### Example ID: 152

**Description:** RewindOnChange

**Code:**
```pseudocode
var ExprT = uc.@ExpressionTransformer();  // Transformer used for Eval() and Evaluate()

ExprT.@DefaultRuleSet().@RewindOnChange(true);

ExprT.FromTo("AddUp({x})", "{x}");
ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

ExprT.FromTo("ArgCount({x})", "1");
ExprT.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))");

ExprT.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})");

var Expression = "Average(1, 2, 3, 4)";
wl("Input: ", Expression)
wl("Transform: ", ExprT.Transform(Expression))
wl("Eval: ", uc.Eval(Expression))
```

**Output:**
```
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
```

---

---

## Description = [string] - ID: 542
/doc/reference/classes/ucalc.transformer/description-=-[string]/

**Description:** Gets or sets a user-defined text description for the Transformer instance, useful for identifying or documenting different transformation configurations.

**Remarks:**

# 🏷️ Attaching Metadata to Transformers

The `Description` property provides a way to attach an arbitrary string of metadata to a [Transformer](/Reference/uCalcBase/Transformer/Constructor) instance. This is invaluable for debugging complex transformation pipelines, creating self-documenting configurations, and identifying specific transformers at runtime.

### ⚙️ Getter and Setter Behavior

This property functions as both a getter and a setter:

*   **Getter**: When called with no arguments, [pseudocode]`myTransformer.@Description()` returns the current description of the transformer. If no description has been set, it returns an empty string.

*   **Setter**: [pseudocode]`myTransformer.@Description("your text")` sets the transformer's description. `SetDescription("your text")` as a method supports a **fluent interface**, meaning it returns the `Transformer` object itself, allowing you to chain method calls.

### 🎯 Core Use Cases

Attaching a description is a best practice for managing multiple or complex transformer instances.

*   **Debugging**: When an application uses multiple transformers for different purposes (e.g., one for sanitizing input, another for formatting output), you can print the `Description` of the active transformer to immediately understand which set of lexical rules is being applied.

*   **Self-Documentation**: Store a human-readable note directly on the transformer to explain its role, such as "Markdown to HTML Converter" or "SQL Injection Sanitizer". This keeps the documentation tightly coupled with the object it describes.

*   **Runtime Identification**: Use descriptions to programmatically identify specific transformer configurations. For example, you could iterate through a collection of transformers and select one based on its description.

### 💡 Why uCalc? (Comparative Analysis)

Without an integrated `Description` property, developers often resort to less ideal solutions for tracking metadata:

*   **vs. Code Comments**: Standard code comments are static and cannot be accessed by the program at runtime. A `Transformer`'s description is dynamic data that can be queried, displayed, or used in application logic.

*   **vs. External Dictionaries**: Managing an external dictionary (e.g., `Dictionary<Transformer, string>`) to map transformers to their descriptions is cumbersome. It requires manual synchronization, and if a `Transformer` object is released, the dictionary entry can become a memory leak. uCalc's integrated approach is safer, cleaner, and more efficient.

The `Description` property is a consistent feature across many uCalc objects, including [Rule](/Reference/uCalcBase/Rule/Constructor), [Item](/Reference/uCalcBase/Item/Constructor), and the main [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance, providing a unified system for metadata management.

**Examples:**

### Example ID: 1062

**Description:** A basic example demonstrating how to set and get a description for a Transformer.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Description("My First Transformer");
wl("Transformer Description: ", t.@Description())
```

**Output:**
```
Transformer Description: My First Transformer
```

---

### Example ID: 1063

**Description:** Uses descriptions to differentiate between two transformers used for different environments, such as a verbose 'debug' transformer and a silent 'production' one.

**Code:**
```pseudocode
var text = "The value is x";

// 1. Setup Debug Transformer
New(uCalc::Transformer, t_debug)
t_debug.@Description("Debug Transformer (Verbose)");
t_debug.FromTo("x", "100 // debug value");

// 2. Setup Production Transformer
New(uCalc::Transformer, t_prod)
t_prod.@Description("Production Transformer (Clean)");
t_prod.FromTo("x", "100");

wl(t_debug.@Description(), ": ", t_debug.Transform(text))
wl(t_prod.@Description(), ": ", t_prod.Transform(text))
```

**Output:**
```
Debug Transformer (Verbose): The value is 100 // debug value
Production Transformer (Clean): The value is 100
```

---

### Example ID: 1064

**Description:** Internal Test: Verifies that the description property is correctly copied when a Transformer is cloned.

**Code:**
```pseudocode
New(uCalc::Transformer, t_original)
t_original.@Description("Original Transformer");

// Clone the transformer
var t_cloned = t_original.Clone();

wl("Original Description: ", t_original.@Description())
wl("Cloned Description:   ", t_cloned.@Description())

// Modify the clone's description to ensure they are independent
t_cloned.@Description("Cloned and Modified");

wl("Original after mod: ", t_original.@Description())
wl("Cloned after mod:   ", t_cloned.@Description())
```

**Output:**
```
Original Description: Original Transformer
Cloned Description:   Original Transformer
Original after mod: Original Transformer
Cloned after mod:   Cloned and Modified
```

---

### Example ID: 132

**Description:** ParentTransformer

**Code:**
```pseudocode
var Txt = "Test a b c. x y z";

var FirstTransform = uc.NewTransformer().SetText(Txt).SetDescription("First Transformer");
var aaa = FirstTransform.FromTo("Test {etc}.", "[{etc}]");

var SecondTransform = uc.NewTransformer().SetDescription("Second Transformer");
var bbb = SecondTransform.FromTo("Test {etc}.", "({etc})");

wl(aaa.@ParentTransformer().@Description())
wl(FirstTransform.Transform().@Text())
wl("")

wl(SecondTransform.@Description())
wl(bbb.@ParentTransformer().Transform(Txt).@Text())
```

**Output:**
```
First Transformer
[a b c] x y z

Second Transformer
(a b c) x y z
```

---

### Example ID: 149

**Description:** Pass()

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

var t = uc.NewTransformer();
t.@Text(FruitsXML);

var Pass1 = t.Pass();
var Pass2 = t.Pass();

Pass1.@Description("Pass A");
Pass1.FromTo("Fruits", "ListOfFruits");
Pass1.FromTo("<Fruit CommonName={@str:name} ScientificName={@str:sci_name} />", "<Fruit>{name}</Fruit>");

Pass2.@Description("Pass B");
Pass2.FromTo("{Fruit: Apple | Orange | Mango }", "{Fruit} *");
Pass2.FromTo("{Fruit: Banana | Grapes | Watermelon }", "{Fruit} **");

t.Transform();
wl("All passes")
wl("----------")
wl(t.@Text())

wl(t.Pass(0).@Description())
wl(t.Pass(1).@Description())
wl("Pass count: ", t.PassCount())
wl("")

t.Str(FruitsXML);
Pass2.Release();
t.Transform();
wl("Pass1 only (Pass2 released)")
wl("---------------------------")
wl(t.@Text())

```

**Output:**
```
All passes
----------

<ListOfFruits>
  <Fruit>Apple *</Fruit>
  <Fruit>Banana **</Fruit>
  <Fruit>Orange *</Fruit>
  <Fruit>Grapes **</Fruit>
  <Fruit>Strawberry</Fruit>
  <Fruit>Pineapple</Fruit>
  <Fruit>Mango *</Fruit>
  <Fruit>Blueberry</Fruit>
  <Fruit>Rambutan</Fruit>
  <Fruit>Salak (Snake Fruit)</Fruit>
  <Fruit>Jabuticaba</Fruit>
  <Fruit>Watermelon **</Fruit>
</ListOfFruits>

Pass A
Pass B
Pass count: 2

Pass1 only (Pass2 released)
---------------------------

<ListOfFruits>
  <Fruit>Apple</Fruit>
  <Fruit>Banana</Fruit>
  <Fruit>Orange</Fruit>
  <Fruit>Grapes</Fruit>
  <Fruit>Strawberry</Fruit>
  <Fruit>Pineapple</Fruit>
  <Fruit>Mango</Fruit>
  <Fruit>Blueberry</Fruit>
  <Fruit>Rambutan</Fruit>
  <Fruit>Salak (Snake Fruit)</Fruit>
  <Fruit>Jabuticaba</Fruit>
  <Fruit>Watermelon</Fruit>
</ListOfFruits>
```

---

---

## Filter - ID: 392
/doc/reference/classes/ucalc.transformer/filter/

---

## Filter() - ID: 393
/doc/reference/classes/ucalc.transformer/filter/filter-void/

**Description:** Performs a pattern-matching operation and returns a new string consisting only of the transformed matches.

**Syntax:** Filter()
**Return:** Transformer - Current object
**Remarks:**

[Revisit]
The `Filter()` method performs a pattern-matching operation similar to [Find()](/Reference/uCalcBase/Transformer/Find) but produces a new string composed exclusively of the results. Unlike [Transform()](/Reference/uCalcBase/Transformer/Transform), which modifies the source text in-place, `Filter()` extracts the matches and concatenates their transformed output, with each result separated by a newline.

This makes it the ideal tool for data extraction, summarization, or creating a new document from selected parts of an original.

### `Find()` vs. `Filter()` vs. `Transform()`

Choosing the correct method is key to efficient text processing. This table clarifies their distinct purposes:

| Method                                                     | Purpose                                | Result                                                                                               | Use Case                                                    |
| :--------------------------------------------------------- | :------------------------------------- | :--------------------------------------------------------------------------------------------------- | :---------------------------------------------------------- |
| **`Find()`**                                               | **Locate**                             | Populates the [Matches](/Reference/uCalcBase/Transformer/Matches) collection with the locations of patterns. Does not produce an output string. | When you only need to know *if* and *where* patterns exist. |
| **`Filter()`**                                             | **Extract & Transform**                | Creates a **new string** consisting only of the transformed results of each match, separated by newlines. | Extracting all log errors, URLs, or specific data points from a document into a clean list. |
| **`Transform()`**                                          | **Modify In-Place**                    | Modifies the **original text**, replacing matches according to rules but preserving all other content. | Performing a search-and-replace operation on a document.    |

### How Replacements Work

The output of `Filter()` is built from the replacement part of each matching rule defined with [FromTo()](/Reference/uCalcBase/Transformer/FromTo). If a rule was defined with [Pattern()](/Reference/uCalcBase/Transformer/Pattern), which has no explicit replacement, the matched text itself (`{@Self}`) is used.

### 💡 Why uCalc? (Comparative Analysis)

In a standard Regex workflow, achieving the same result as `Filter()` is a multi-step, manual process:

1.  Run the regex search to get a collection of all matches.
2.  Create a `StringBuilder` or a `List<string>` in your host language (C#/C++).
3.  Loop through the match collection.
4.  For each match, perform any necessary transformation on its value.
5.  Append the transformed string to your builder/list.
6.  Finally, join the results with newlines to get the final string.

`Filter()` encapsulates this entire workflow into a single, highly optimized method call. You define your extraction and transformation logic declaratively, and the engine handles the iteration, transformation, and string concatenation internally, leading to code that is cleaner, faster, and less error-prone.

**Examples:**

### Example ID: 130

**Description:** Rule Name

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<b>(5+4)</b> this and that etc");
var a = t.Pattern("<{tg}>");
var b = t.Pattern("This {body} That");
var c = t.Pattern("etc");
var d = t.Pattern("({expr})");

t.Filter();
wl("--- Matches ---")
wl(t.@Matches().@Text())
wl("--- Pattern names ---")
wl(a.@Name())
wl(b.@Name())
wl(c.@Name())
wl(d.@Name())
wl("--- Pattern defs ---")
wl(a.@Pattern())
wl(b.@Pattern())
wl(c.@Pattern())
wl(d.@Pattern())
```

**Output:**
```
--- Matches ---
<b>
(5+4)
</b>
this and that
etc
--- Pattern names ---
<
this
etc
(
--- Pattern defs ---
<{tg}>
This {body} That
etc
({expr})
```

---

---

## Filter(string) - ID: 394
/doc/reference/classes/ucalc.transformer/filter/filter-string/

**Description:** Performs a Filter operation on the given text

**Syntax:** Filter(string)
**Parameters:**
expression - string - Expression to be transformed
**Return:** Transformer - Current transformer
**Remarks:**

[Revisit]
This performs a filter operation on text.  This is similar to a Transform() operation, however, the result is text consisting of just the matches.  The operation is performed on the string passed to this Filter() function.

**Examples:**

### Example ID: 138

**Description:** Rule StartAfter()

**Code:**
```pseudocode
var t = uc.NewTransformer();
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

var Fruit = t.FromTo("CommonName={@string:name}", "{name}");

// StopAfter()
Fruit.@StopAfter(4);
t.Filter(FruitsXML);
wl("*** Stop after: ", Fruit.@StopAfter(), " ***")
wl(t.@Matches().@Text())
Fruit.@StopAfter(-1); // Resets back to infinity (default) for next example
wl("")

// StartAfter()
Fruit.@StartAfter(6);
t.Filter(FruitsXML);
wl("*** Start after: ", Fruit.@StartAfter(), " ***")
wl(t.@Matches().@Text())
Fruit.@StartAfter(0); // Resets back to 0 (default) for next example
wl("")


// Both StartAfter() and StopAfter()
Fruit.SetStartAfter(2).SetStopAfter(5);
t.Filter(FruitsXML);
wl("*** Between ", Fruit.@StartAfter() + 1, " and ", Fruit.@StopAfter(), " ***")
wl(t.@Matches().@Text())
wl("")

// All
uc.DefineVariable("x = 1");
Fruit = t.FromTo("CommonName={@string:name}", "{@Eval: x++}. {name}");
t.Filter(FruitsXML);
wl("*** All ***")
wl(t.@Matches().@Text())
```

**Output:**
```
*** Stop after: 4 ***
Apple
Banana
Orange
Grapes

*** Start after: 6 ***
Mango
Blueberry
Rambutan
Salak (Snake Fruit)
Jabuticaba
Watermelon

*** Between 3 and 5 ***
Orange
Grapes
Strawberry

*** All ***
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon
```

---

---

## Find - ID: 395
/doc/reference/classes/ucalc.transformer/find/

**Description:** Executes a search operation on the current text using all defined pattern rules, populating the internal collection of matches.

**Syntax:** Find()
**Return:** Transformer - The current Transformer object
**Remarks:**

The `Find()` method is the primary function for executing a read-only search operation. It processes the text currently held by the [Transformer](/Reference/uCalcBase/Transformer/Constructor) against all active rules, populating an internal collection of matches without modifying the text itself.

### The Search Workflow

1.  **Define Rules**: Before calling `Find()`, you must define what to search for using methods like [Pattern()](/Reference/uCalcBase/Transformer/Pattern), [FromTo()](/Reference/uCalcBase/Transformer/FromTo), and [SkipOver()](/Reference/uCalcBase/Transformer/SkipOver).
2.  **Execute Search**: Call `Find()` to run the search engine. The transformer scans the text, and every time a segment matches a rule, a [Match](/Reference/uCalcBase/Matches/Match/Constructor) object is created and stored internally.
3.  **Access Results**: After the search completes, retrieve the results using the [Matches()](/Reference/uCalcBase/Transformer/Matches) property, which returns a [Matches](/Reference/uCalcBase/Matches/Constructor) collection object.

### Concurrency and Precedence

All active rules are evaluated concurrently in a single pass. If multiple patterns could match at the same location, the **most recently defined rule** takes precedence. This LIFO (Last-In, First-Out) ordering is crucial for managing overlapping patterns.

### `Find()` vs. `Transform()` vs. `Filter()`

These three methods trigger the same core matching engine but produce different outcomes:

| Method | Effect on Text | Primary Use Case |
| :--- | :--- | :--- |
| **`Find()`** | 🔵 **None**. The text is not modified. | Pure search and analysis. Find locations without altering the source. |
| [`Transform()`](/Reference/uCalcBase/Transformer/Transform) | 🟠 **Modified**. Matched text is replaced. | Search-and-replace operations. |
| [`Filter()`](/Reference/uCalcBase/Transformer/Filter) | 🔴 **Replaced**. Text is replaced with a concatenation of all matches. | Extracting all matching segments from a larger document. |

### 💡 Why uCalc? (Comparative Analysis)

`Find()` offers significant advantages over traditional string search methods.

*   **vs. Regular Expressions (`Regex.Matches`)**:
    *   **Token-Awareness**: Regex is character-based and struggles with nested structures like parentheses `()` or quotes `""`. uCalc's `Find()` operates on tokens, so it inherently understands these structures, preventing incorrect matches inside string literals or across mismatched brackets.
    *   **Concurrent Patterns**: To search for multiple distinct patterns with regex, you typically combine them into a large, unreadable alternation (`(pattern1|pattern2|...)`). With uCalc, you define each pattern with a separate, clear `Pattern()` call, and `Find()` executes them all concurrently.

*   **vs. `string.IndexOf`**:
    *   **Power**: `IndexOf` finds the first occurrence of a single, literal substring. `Find()` locates multiple occurrences of complex, token-aware patterns with variables, alternations, and other advanced logic.

**Examples:**

### Example ID: 1065

**Description:** Finding all occurrences of a specific word.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("apple banana apple cherry apple");
t.Pattern("apple");
t.Find();
wl("Found ", t.@Matches().Count(), " occurrences of 'apple'.")
```

**Output:**
```
Found 3 occurrences of 'apple'.
```

---

### Example ID: 1066

**Description:** A practical example using multiple concurrent patterns to find and categorize log entries.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var logText = "INFO: System start. WARN: Low disk. ERROR: DB connection failed.";
t.@Text(logText);

// Define rules for different log levels
var errorRule = t.Pattern("ERROR: {msg}.");
var warnRule = t.Pattern("WARN: {msg}.");

t.Find();

wl("Total issues found: ", t.@Matches().Count())
wl("--- Error Matches ---")
wl(errorRule.@Matches().@Text())
wl("--- Warning Matches ---")
wl(warnRule.@Matches().@Text())
```

**Output:**
```
Total issues found: 2
--- Error Matches ---
ERROR: DB connection failed.
--- Warning Matches ---
WARN: Low disk.
```

---

### Example ID: 1067

**Description:** Internal Test: Verifies correct precedence with overlapping patterns and confirms that re-running Find produces the same results.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("The apple is an apple.");

// Overlapping patterns. The longer one is defined last, so it gets precedence.
t.Pattern("apple");
t.Pattern("an apple");

wl("--- First Find ---")
t.Find();
// The first 'apple' matches the first rule.
// The 'an apple' matches the second (higher precedence) rule.
wl(t.@Matches().@Text())

// Re-running find should produce the exact same result
wl("--- Second Find (no change) ---")
t.Find();
wl(t.@Matches().@Text())
```

**Output:**
```
--- First Find ---
apple
an apple
--- Second Find (no change) ---
apple
an apple
```

---

### Example ID: 111

**Description:** Returns Start and End positions of Transformer matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>");
//         ^             ^                       ^              ^
//     012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50
// Carrets (^) point to Start and End locations of the matches

wl(t.@Text())
wl("")

t.Pattern("<{tag}>{etc}</{tag}>");
t.Find();
var Matches = t.@Matches();

wl(Matches[0].@Text())
wl("Start pos: ", Matches[0].@StartPosition())
wl("End pos: ", Matches[0].@EndPosition())
wl("Length: ", Matches[0].@Length())
wl("")

wl(Matches[1].@Text())
wl("Start pos: ", Matches[1].@StartPosition())
wl("End pos: ", Matches[1].@EndPosition())
wl("Length: ", Matches[1].@Length())
```

**Output:**
```
<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>

<h1>First</h1>
Start pos: 4
End pos: 18
Length: 14

<h2>Second</h2>
Start pos: 42
End pos: 57
Length: 15
```

---

### Example ID: 114

**Description:** Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>");
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text())
   wl("Start pos: ", match.@StartPosition())
   wl("End pos: ", match.@EndPosition())
   wl("Length: ", match.@Length())
   wl("")
end foreach
```

**Output:**
```
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
```

---

---

## FromTo - ID: 396
/doc/reference/classes/ucalc.transformer/fromto/

**Description:** Defines a token-aware, find-and-replace rule that transforms text matching a pattern.

**Syntax:** FromTo(string, string)
**Parameters:**
pattern - string - The uCalc pattern string that defines the text to find. It can contain literals, variables (e.g., `{name}`), and token category matchers (e.g., `{@Number}`).
replacement - string [default = ""] - The string that will replace the matched text. It can contain literal text, backreferences to captured variables (e.g., `{name}`), and pattern methods (e.g., `{@Eval:...}`).
**Return:** Rule - Returns the newly created [Rule](/Reference/uCalcBase/Rule/Constructor) object, which can be used to further configure its behavior (e.g., setting its active state, case-sensitivity, etc.).
**Remarks:**

`FromTo` is the cornerstone method of the [Transformer](/Reference/uCalcBase/Transformer/Constructor) engine, used to define a find-and-replace rule. It binds a search pattern to a replacement template, allowing for powerful, token-aware text transformations.

### ⚙️ How It Works

The method takes two primary arguments: a `pattern` string and a `replacement` string.

1.  **The Pattern String (`pattern`)**: This string defines *what* to search for. It uses uCalc's [Pattern Syntax](/Reference/Patterns/Introduction/Syntax-Definitions) which can include:
    *   **Literals (Anchors)**: Exact text that must be present (e.g., `"ID:"`).
    *   **Variables (Captures)**: Placeholders like `{name}` or `{@Number:val}` that capture dynamic content.
    *   **Complex Logic**: Optional parts (`[]`), alternations (`|`), and other structural directives.

2.  **The Replacement String (`replacement`)**: This string defines *how* to construct the new text. It can contain:
    *   **Literal Text**: Characters to be inserted as-is.
    *   **Variable Backreferences**: Placeholders like `{name}` that re-insert the text captured by the corresponding variable in the pattern.
    *   **Pattern Methods**: Powerful directives like `{@Eval: ...}` to execute code or `{!var:default}` for conditional logic.

For a complete guide to pattern syntax, see the [Patterns](/Reference/Patterns/Introduction/Syntax-Definitions) section.

### 🥇 Precedence and Rule Order (LIFO)

A [Transformer](/Reference/uCalcBase/Transformer/Constructor) can have multiple rules. When two or more patterns could potentially match the same text (e.g., `"An apple."` and `"An {item}."`), uCalc uses a **Last-In, First-Out (LIFO)** precedence rule: **The most recently defined rule is checked first.**

This allows you to define general, catch-all rules first, and then add more specific, higher-precedence rules on top of them.

### `FromTo` vs. `Pattern`

| Method | Purpose | Replacement Behavior | Use Case |
| :--- | :--- | :--- | :--- |
| **`FromTo(p, r)`** | **Find and Replace** | Uses the provided `replacement` string `r`. | Text transformation, data normalization, code generation. |
| **[Pattern(p)](/Reference/uCalcBase/Transformer/Pattern)** | **Find Only** | Implicitly uses `{@Self}` as the replacement (i.e., re-inserts the matched text). | Locating patterns without modifying the source text. |

### 💡 Why uCalc? (Comparative Analysis)

In many languages, string replacement is handled by regular expressions.

*   **Standard Regex (`Regex.Replace`)**:
    [csharp]`Regex.Replace(input, @"Hello (\w+)", "Greetings, $1");`
    While powerful, regex is purely character-based. It struggles with nested structures, is often difficult to read, and replacement logic is limited to simple backreferences. More complex logic requires using a `MatchEvaluator` callback, which can be verbose.

*   **uCalc `FromTo`**:
    [pseudocode]`t.FromTo("Hello {name}", "Greetings, {name}!");`
    uCalc's `FromTo` offers significant advantages:
    *   **Readability**: Patterns use natural language and variables, making them easier to understand and maintain.
    *   **Token-Awareness**: uCalc is "safe by default." It understands language structures like quotes and brackets, preventing accidental replacements inside string literals or across mismatched parentheses.
    *   **Embedded Logic**: The replacement string can contain conditional logic (`{var: ...}`) and execute expressions (`{@Eval: ...}`) directly, which is far more concise than writing a separate callback function.

This makes `FromTo` a more robust, readable, and powerful tool for any task involving structured text transformation.

**Examples:**

### Example ID: 1071

**Description:** A simple find-and-replace transformation.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("Hello {name}", "Greetings, {name}!");
wl(t.Transform("Hello World"))
```

**Output:**
```
Greetings, World!
```

---

### Example ID: 73

**Description:** Using ExpressionTransformer to transform expressions before they are parsed

**Code:**
```pseudocode
var ExprT = uc.@ExpressionTransformer();  // Transformer used for Eval() and Evaluate()

var p1 = ExprT.FromTo("AddUp({x})", "{x}"); // RewindOnChange False by default
var p2 = ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))").SetRewindOnChange(true);

wl("p1 RewindOnChange: ", bool(p1.@RewindOnChange()))
wl("p2 RewindOnChange: ", bool(p2.@RewindOnChange()))

wl("")

wl("Input: ", "AddUp(1,2,3,4)")
wl("Transform: ", ExprT.Transform("AddUp(1,2,3,4)"))
wl("Eval: ", uc.Eval("AddUp(1,2,3,4)"))
```

**Output:**
```
p1 RewindOnChange: False
p2 RewindOnChange: True

Input: AddUp(1,2,3,4)
Transform: (1 + (2 + (3 + 4)))
Eval: 10
```

---

### Example ID: 127

**Description:** Maximum, GlobalMaximum

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

uc.DefineVariable("x");
var t = uc.NewTransformer();
var FruitsTag = t.FromTo("<Fruits>", "List of fruits");
var Fruit = t.FromTo("CommonName={@string:name}", "{@Eval: x++}. {name}");

uc.Eval("x = 1");
Fruit.@Maximum(10);
t.Filter(FruitsXML);
wl("Maximum = ", Fruit.@Maximum())
wl("Matches count: ", t.@Matches().Count()) // 1 for FruitsTag occurrence 
wl("")
wl(t.@Matches())
wl("")
wl("===============")

uc.Eval("x = 1");
Fruit.@Maximum(20);
t.Filter(FruitsXML);
wl("Maximum = ", Fruit.@Maximum())
wl("Matches count: ", t.@Matches().Count()) // 1 for FruitsTag plus 12 fruits
wl("")
wl(t.@Matches())
wl("")
wl("===============")

uc.Eval("x = 1");
Fruit.@GlobalMaximum(10); // Notice "List of fruits" will not show
t.Filter(FruitsXML);
wl("MaximumAND = ", Fruit.@GlobalMaximum())
wl("Matches count: ", t.@Matches().Count()) // Even FruitsTage won't be counted
wl("")
wl(t.@Matches())
wl("===============")

uc.Eval("x = 1");
Fruit.@GlobalMaximum(20);
t.Filter(FruitsXML);
wl("MaximumAND = ", Fruit.@GlobalMaximum())
wl("Matches count: ", t.@Matches().Count())
wl("")
wl(t.@Matches())

```

**Output:**
```
Maximum = 10
Matches count: 1

List of fruits

===============
Maximum = 20
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon

===============
MaximumAND = 10
Matches count: 0


===============
MaximumAND = 20
Matches count: 13

List of fruits
1. Apple
2. Banana
3. Orange
4. Grapes
5. Strawberry
6. Pineapple
7. Mango
8. Blueberry
9. Rambutan
10. Salak (Snake Fruit)
11. Jabuticaba
12. Watermelon
```

---

---

## GetMatches - ID: 404
/doc/reference/classes/ucalc.transformer/getmatches/

**Description:** Retrieves the collection of matches from a Transformer operation, with options to filter the result set.

**Syntax:** GetMatches(MatchesOption, bool)
**Parameters:**
options - MatchesOption [default = MatchesOption::All] - An enum member specifying which subset of matches to return, such as all, focusable only, or only the root/innermost level.
mapUTF16 - bool [default = false] - Internal use only. Controls UTF-16 character mapping for .NET environments.
**Return:** Matches - A `Matches` object containing the collection of matches, filtered according to the provided `options`.
**Remarks:**

# 🎯 Retrieving Filtered Match Results

The `GetMatches` method retrieves the [Matches](/Reference/uCalcBase/Matches/Constructor) collection generated by the most recent [Transformer](/Reference/uCalcBase/Transformer/Constructor) operation (e.g., [Find()](/Reference/uCalcBase/Transformer/Find)). Its key feature is the ability to filter the result set on-the-fly, providing different views of the data without needing to re-run the initial search.

### GetMatches() vs. Matches Property

This method is the counterpart to the simpler [Matches](/Reference/uCalcBase/Transformer/Matches) property. The property is a convenient shortcut for retrieving *all* matches, equivalent to calling `GetMatches(MatchesOption::All)`. You must use the `GetMatches()` method when you need to apply any of the advanced filtering options.

--- 

## ⚙️ Filtering with `MatchesOption`

The behavior of `GetMatches` is controlled by the `options` parameter, which accepts a member of the [MatchesOption](/Reference/Enums/MatchesOption) enum:

| Option | Description |
| :--- | :--- |
| `MatchesOption::All` (Default) | Returns all matches found by the `Transformer` operation. |
| `MatchesOption::FocusableOnly` | Filters the list to include only matches from rules marked as focusable (e.g., with [Rule.Focusable(true)](/Reference/uCalcBase/Rule/Focusable)). |
| `MatchesOption::RootLevelOnly` | In a nested match hierarchy created by a [LocalTransformer](/Reference/uCalcBase/Rule/LocalTransformer), this returns only the top-level (parent) matches. |
| `MatchesOption::InnermostOnly` | The opposite of `RootLevelOnly`; filters the list to include only the most deeply nested (child) matches. |

--- 

## 💡 Why uCalc? (Comparative Analysis)

In a language like C#, developers might filter a collection of results using LINQ:

```csharp
// C# LINQ example
var focusableMatches = allMatches.Where(m => m.Rule.IsFocusable).ToList();
```

This approach is stateless and creates a *new* collection. uCalc's model is different and offers unique advantages:

1.  **Stateful & In-Place**: Methods like [Matches.Reset()](/Reference/uCalcBase/Matches/Reset) can modify the `Matches` collection in-place, which can be more memory-efficient.
2.  **Engine-Side Filtering**: The filtering logic is executed inside the highly optimized uCalc engine, which is generally faster than performing the filtering in host application code.
3.  **Declarative API**: The `MatchesOption` enum provides a direct and declarative way to ask for a specific view of the data, leading to cleaner and more readable code.

**Examples:**

### Example ID: 1080

**Description:** Demonstrates the basic difference between getting all matches and filtering for only 'focusable' ones.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("ID:100, Name:Admin, ID:200");

// Define two rules, but only one is marked as 'focusable'
t.Pattern("ID:{@Number}").SetFocusable(true);
t.Pattern("Name:{@Alpha}").SetFocusable(false);
t.Find();

// Get all matches using the default option
var allMatches = t.GetMatches();
wl("--- All Matches (", allMatches.Count(), ") ---")
wl(allMatches.@Text())

// Get only the focusable matches
var focusableMatches = t.GetMatches(MatchesOption::FocusableOnly);
wl("")
wl("--- Focusable Matches Only (", focusableMatches.Count(), ") ---")
wl(focusableMatches.@Text())
```

**Output:**
```
--- All Matches (3) ---
ID:100
Name:Admin
ID:200

--- Focusable Matches Only (2) ---
ID:100
ID:200
```

---

### Example ID: 1081

**Description:** Parses a log file and uses the `FocusableOnly` option to quickly extract only the critical error entries.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var log = "INFO: Task started. ERROR: Connection failed. INFO: Task finished.";
t.@Text(log);

// Rules for different log levels. Only errors are focusable.
t.Pattern("INFO: {msg}.").SetFocusable(false);
t.Pattern("ERROR: {msg}.").SetFocusable(true);
t.Find();

wl("All log entries:")
wl(t.GetMatches().@Text())
wl("")

wl("Critical errors only:")
// Use the option to filter for only the important entries
var errorMatches = t.GetMatches(MatchesOption::FocusableOnly);
wl(errorMatches.@Text())
```

**Output:**
```
All log entries:
INFO: Task started.
ERROR: Connection failed.
INFO: Task finished.

Critical errors only:
ERROR: Connection failed.
```

---

### Example ID: 111

**Description:** Returns Start and End positions of Transformer matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>");
//         ^             ^                       ^              ^
//     012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50
// Carrets (^) point to Start and End locations of the matches

wl(t.@Text())
wl("")

t.Pattern("<{tag}>{etc}</{tag}>");
t.Find();
var Matches = t.@Matches();

wl(Matches[0].@Text())
wl("Start pos: ", Matches[0].@StartPosition())
wl("End pos: ", Matches[0].@EndPosition())
wl("Length: ", Matches[0].@Length())
wl("")

wl(Matches[1].@Text())
wl("Start pos: ", Matches[1].@StartPosition())
wl("End pos: ", Matches[1].@EndPosition())
wl("Length: ", Matches[1].@Length())
```

**Output:**
```
<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>

<h1>First</h1>
Start pos: 4
End pos: 18
Length: 14

<h2>Second</h2>
Start pos: 42
End pos: 57
Length: 15
```

---

### Example ID: 114

**Description:** Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>");
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text())
   wl("Start pos: ", match.@StartPosition())
   wl("End pos: ", match.@EndPosition())
   wl("Length: ", match.@Length())
   wl("")
end foreach
```

**Output:**
```
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
```

---

### Example ID: 112

**Description:** Filters matches by rule; FilterByRule, Matches.Str, Matches.Count

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

wl("All matches -- count = ", t.@Matches().Count())
wl("----------------------")
wl(t.@Matches())
wl("")

wl("Only BoldTag matches -- count = ", BoldTag.@Matches().Count())
wl("-------------------------------")
wl(BoldTag.@Matches())
wl("")

wl("Only H3Tag matches -- count = ", H3Tag.@Matches().Count())
wl("-----------------------------")
wl(H3Tag.@Matches())
```

**Output:**
```
All matches -- count = 5
----------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
<p>My paragraph</p>

Only BoldTag matches -- count = 2
-------------------------------
<b>Bold statement</b>
<b>Other text</b>

Only H3Tag matches -- count = 2
-----------------------------
<h3>Title</h3>
<h3>Title B</h3>
```

---

### Example ID: 123

**Description:** Focusable to toggle pattern matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b>");

var BoldTag = t.Pattern("<b>{text}</b>").SetFocusable(true);
var H3Tag = t.Pattern("<h3>{text}</h3>").SetFocusable(true);
t.Find();

wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")

BoldTag.@Focusable(false);
wl("BoldTag.Focusable(): ", bool(BoldTag.@Focusable()))
wl("--------------------------")
// t.Find(); // A Find operation does not have to be executed again
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")

BoldTag.@Focusable(true);
wl("BoldTag.Focusable(): ", bool(BoldTag.@Focusable()))
wl("--------------------------")

//t.Find(); // A Find operation does not have to be executed again
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")
```

**Output:**
```
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>

BoldTag.Focusable(): False
--------------------------
<h3>Title</h3>
<h3>Title B</h3>

BoldTag.Focusable(): True
--------------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
```

---

### Example ID: 139

**Description:** Focusable to select only patterns from local transformer

**Code:**
```pseudocode
var t = uc.NewTransformer();
var FruitsXML =
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <!-- <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' /> -->
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <!-- <Fruit CommonName='Mango' ScientificName='Mangifera indica' /> -->
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <!-- <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' /> -->
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <!-- <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' /> -->
</Fruits>
[/verbatim];

// List names of fruit within comment, not the whole comment as well
t.@Text(FruitsXML);
var CommentedFruits = t.Pattern("<!-- {comment} -->").SetFocusable(false);
var CommentedFruitsTr = CommentedFruits.@LocalTransformer();
CommentedFruitsTr.FromTo("CommonName={@string:text}", "{text}").@Focusable(true);

t.Filter();
wl("With Focusable()")
wl("----------------")
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")

// Note: The displayed Fruit element is modified by CommentedFruitsTr.FromTo()
wl("Without Focusable()")
wl("-------------------")
wl(t.@Matches().@Text())
```

**Output:**
```
With Focusable()
----------------
Grapes
Mango
Rambutan
Watermelon

Without Focusable()
-------------------
<!-- <Fruit Grapes ScientificName='Vitis vinifera' /> -->
Grapes
<!-- <Fruit Mango ScientificName='Mangifera indica' /> -->
Mango
<!-- <Fruit Rambutan ScientificName='Nephelium lappaceum' /> -->
Rambutan
<!-- <Fruit Watermelon ScientificName='Citrullus lanatus' /> -->
Watermelon
```

---

### Example ID: 148

**Description:** MatchesOption: RootLevelOnly and InnermostOnly

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "<p id='aa'>xyz</p><p id='bb'>Hello</p ><p id='cc'>World</p>";
t.Str(txt);

t.Pattern("<p {etc}>").@LocalTransformer().FromTo("id={@string:id}", "{id}");
t.Filter();


wl("All matches")
wl("-----------")
wl(t.GetMatches(MatchesOption::All).@Text()) // All is the default
wl("")

wl("RootLevelOnly")
wl("-------------")
wl(t.GetMatches(MatchesOption::RootLevelOnly).@Text())
wl("")

wl("InnermostOnly")
wl("-------------")
wl(t.GetMatches(MatchesOption::InnermostOnly).@Text())
wl("")
```

**Output:**
```
All matches
-----------
<p aa>
aa
<p bb>
bb
<p cc>
cc

RootLevelOnly
-------------
<p aa>
<p bb>
<p cc>

InnermostOnly
-------------
aa
bb
cc
```

---

---

## GlobalRuleSet = [Rule] - ID: 413
/doc/reference/classes/ucalc.transformer/globalruleset-=-[rule]/

**Description:** Gets a special Rule object used to define global, cumulative properties that apply across all rules in a transformation pass.

**Remarks:**

> **Note**: This feature is currently in the design phase and is not yet implemented in the production engine.
# ⚙️ Global Transformation Control: GlobalRuleSet

The `GlobalRuleSet` property provides access to a special [Rule](/Reference/uCalcBase/Rule/Constructor) object that is not used for matching text itself. Instead, it acts as a central control panel for setting properties that have a **cumulative effect** on the entire [Transformer](/Reference/uCalcBase/Transformer/Constructor) operation. This is a powerful feature for establishing global constraints and validation logic.

### Global vs. Default vs. Per-Rule Settings

It is crucial to understand the different scopes of rule configuration:

| Configuration Method | Scope & Purpose |
| :--- | :--- |
| **Per-Rule** (`myRule.@StopAfter(5)`) | **Individual**. Affects only `myRule`. Each rule has its own independent counter and settings. |
| **[DefaultRuleSet](/Reference/uCalcBase/Transformer/DefaultRuleSet)** | **Template**. Sets the *initial* property values for all new rules created in the transformer. Each rule still behaves independently. |
| **`GlobalRuleSet`** (This Property) | **Global/Cumulative**. Sets a *shared, single limit* for the entire transformer pass. The counter is shared across all rules. |

### Key Cumulative Properties

When set on the `GlobalRuleSet`, these properties have a cumulative effect:

*   **`@StopAfter(n)`**: The entire transformation pass stops after a combined total of `n` matches have been found across *all* active rules.
*   **`@StartAfter(n)`**: The transformation will skip the first `n` total matches found across all rules before it begins keeping results.
*   **`@Maximum(n)`**: The entire transformation pass is **invalidated** (returning zero matches) if the combined total of matches from all rules exceeds `n`.
*   **`@Minimum(n)`**: The entire transformation pass is **invalidated** if the combined total of matches from all rules is less than `n`.

### ⚠️ Performance & Memory Considerations

To enable the "all or nothing" validation behavior of global `Minimum` and `Maximum` properties, the [Transformer](/Reference/uCalcBase/Transformer/Constructor) may need to store a backup of the original string. If a global constraint is not met, the engine discards all results. This can consume more memory than a standard transformation.

### 💡 Why uCalc? (Comparative Analysis)

In a standard Regex-based workflow, enforcing a global match count is a manual, multi-step process:

1.  Run searches for all patterns to get all possible matches.
2.  Combine the match collections.
3.  Write an `if` statement in your host language (C#, C++, etc.) to check if the total count meets your constraints.
4.  If it doesn't, manually discard all results.

This is imperative, verbose, and inefficient. uCalc's `GlobalRuleSet` is **declarative**. You state your constraints directly on the `Transformer`, and the engine handles the complex validation and counting logic internally. This leads to cleaner, more expressive, and less error-prone code by keeping the validation logic tightly coupled with the transformation it governs.

**Examples:**

---

## Handle - ID: 397
/doc/reference/classes/ucalc.transformer/handle/

**Description:** Returns the handle of an object

**Syntax:** Handle()
**Return:** Transformer - 
**Remarks:**

Mostly for internal use.

Each object has a unique handle, which is used to communicate with the uCalc library.  It may not have other uses cases beyond troubleshooting.

---

## Matches = [Matches] - ID: 863
/doc/reference/classes/ucalc.transformer/matches-=-[matches]/

**Description:** Retrieves the collection of all matches found by the most recent find, filter, or transform operation.

**Remarks:**

The `@Matches` property is the primary way to access the results of a [Transformer](/Reference/uCalcBase/Transformer/Constructor) operation. After running a search with [Find()](/Reference/uCalcBase/Transformer/Find), [Filter()](/Reference/uCalcBase/Transformer/Filter), or [Transform()](/Reference/uCalcBase/Transformer/Transform), this property returns a [Matches](/Reference/uCalcBase/Matches/Constructor) collection object containing all the substrings that matched your defined rules.

### ⚙️ The Transformer Workflow

A typical search operation follows these steps:
1.  Define rules on a `Transformer` instance using [Pattern()](/Reference/uCalcBase/Transformer/Pattern) or [FromTo()](/Reference/uCalcBase/Transformer/FromTo).
2.  Call [Find()](/Reference/uCalcBase/Transformer/Find) to execute the search.
3.  Call `@Matches()` to get the collection of results.
4.  Iterate through the collection to inspect each [Match](/Reference/uCalcBase/Matches/Match/Constructor) object.

```pseudocode
New(uCalc::Transformer, t)
t.FromTo("apple", "[FRUIT]");
t.Find("An apple a day.");

var allMatches = t.@Matches();
wl("Found ", allMatches.Count(), " match(es).")
```

### `Matches` vs. `GetMatches`

This property is a convenient shortcut for retrieving *all* matches. It is functionally equivalent to calling the [GetMatches()](/Reference/uCalcBase/Transformer/GetMatches) method with `MatchesOption::All`.

*   Use [pseudocode]`@Matches()` for a complete, unfiltered list of results.
*   Use [pseudocode]`GetMatches(options)` when you need to filter the results (e.g., to get only [Focusable](/Reference/Enums/MatchesOption) matches or nested matches).

### `Transformer.Matches` vs. `Rule.Matches`

It is crucial to understand the difference in scope:

*   [pseudocode]`myTransformer.@Matches()`: Returns a collection of **all matches** found by **all active rules** in the transformer.
*   [pseudocode]`myRule.@Matches()`: Returns a subset containing only the matches found by **that specific rule**.

### 💡 Why uCalc? (Comparative Analysis)

In environments like .NET, a regular expression search returns a `MatchCollection`. While functionally similar, uCalc's `Matches` object has distinct advantages rooted in its token-aware architecture.

*   **Token Awareness vs. Character Awareness**: A standard regex match is purely character-based. uCalc's matches are token-aware. A match for `{@Bracketed}` will correctly capture `(a + (b * c))`, something that is extremely difficult for a simple regex. The resulting `Matches` object represents these structurally sound captures.
*   **Rich Metadata**: A regex `Match` object provides the captured string and its position. A uCalc `Match` provides much richer context. The ability to retrieve the specific [Rule](/Reference/uCalcBase/Rule/Constructor) that generated the match via [pseudocode]`aMatch.@Rule()` is invaluable for debugging and for building applications with complex, layered logic where you need to know *why* something was matched.

**Examples:**

### Example ID: 1099

**Description:** A simple `Find()` followed by `@Matches().Count()` to count all occurrences of a word.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("apple banana apple cherry apple");

// Define a pattern to find any alphanumeric word
t.Pattern("apple");
t.Find();

wl("Found ", t.@Matches().Count(), " occurrences of 'apple'.")
```

**Output:**
```
Found 3 occurrences of 'apple'.
```

---

### Example ID: 1100

**Description:** Practical: Iterates through all matches and uses the `Match.Rule` property to identify which pattern generated each match, demonstrating a key introspection feature.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
var logText = "INFO: System start. WARN: Low disk. ERROR: DB connection failed.";
t.@Text(logText);

// Define rules for different log levels
var errorRule = t.Pattern("ERROR: {msg}.");
var warnRule = t.Pattern("WARN: {msg}.");
var infoRule = t.Pattern("INFO: {msg}.");

t.Find();

wl("--- Analysis of All Matches ---")
foreach (var match in t.@Matches())
    // Use the match's Rule property to get the name of the rule that found it
    wl("Found '", match.@Text(), "' using rule: '", match.@Rule().@Name(), "'")
end foreach
```

**Output:**
```
--- Analysis of All Matches ---
Found 'INFO: System start.' using rule: 'info'
Found 'WARN: Low disk.' using rule: 'warn'
Found 'ERROR: DB connection failed.' using rule: 'error'
```

---

### Example ID: 111

**Description:** Returns Start and End positions of Transformer matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>");
//         ^             ^                       ^              ^
//     012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50
// Carrets (^) point to Start and End locations of the matches

wl(t.@Text())
wl("")

t.Pattern("<{tag}>{etc}</{tag}>");
t.Find();
var Matches = t.@Matches();

wl(Matches[0].@Text())
wl("Start pos: ", Matches[0].@StartPosition())
wl("End pos: ", Matches[0].@EndPosition())
wl("Length: ", Matches[0].@Length())
wl("")

wl(Matches[1].@Text())
wl("Start pos: ", Matches[1].@StartPosition())
wl("End pos: ", Matches[1].@EndPosition())
wl("Length: ", Matches[1].@Length())
```

**Output:**
```
<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>

<h1>First</h1>
Start pos: 4
End pos: 18
Length: 14

<h2>Second</h2>
Start pos: 42
End pos: 57
Length: 15
```

---

### Example ID: 114

**Description:** Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>");
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text())
   wl("Start pos: ", match.@StartPosition())
   wl("End pos: ", match.@EndPosition())
   wl("Length: ", match.@Length())
   wl("")
end foreach
```

**Output:**
```
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
```

---

### Example ID: 112

**Description:** Filters matches by rule; FilterByRule, Matches.Str, Matches.Count

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b><p>My paragraph</p>");

var AnyOtherTag = t.Pattern("<{tag}>{text}</{tag}>");
var BoldTag = t.Pattern("<b>{text}</b>");
var H3Tag = t.Pattern("<h3>{text}</h3>");
t.Find();

wl("All matches -- count = ", t.@Matches().Count())
wl("----------------------")
wl(t.@Matches())
wl("")

wl("Only BoldTag matches -- count = ", BoldTag.@Matches().Count())
wl("-------------------------------")
wl(BoldTag.@Matches())
wl("")

wl("Only H3Tag matches -- count = ", H3Tag.@Matches().Count())
wl("-----------------------------")
wl(H3Tag.@Matches())
```

**Output:**
```
All matches -- count = 5
----------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
<p>My paragraph</p>

Only BoldTag matches -- count = 2
-------------------------------
<b>Bold statement</b>
<b>Other text</b>

Only H3Tag matches -- count = 2
-----------------------------
<h3>Title</h3>
<h3>Title B</h3>
```

---

### Example ID: 123

**Description:** Focusable to toggle pattern matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("<h3>Title</h3><b>Bold statement</b><h3>Title B</h3><b>Other text</b>");

var BoldTag = t.Pattern("<b>{text}</b>").SetFocusable(true);
var H3Tag = t.Pattern("<h3>{text}</h3>").SetFocusable(true);
t.Find();

wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")

BoldTag.@Focusable(false);
wl("BoldTag.Focusable(): ", bool(BoldTag.@Focusable()))
wl("--------------------------")
// t.Find(); // A Find operation does not have to be executed again
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")

BoldTag.@Focusable(true);
wl("BoldTag.Focusable(): ", bool(BoldTag.@Focusable()))
wl("--------------------------")

//t.Find(); // A Find operation does not have to be executed again
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")
```

**Output:**
```
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>

BoldTag.Focusable(): False
--------------------------
<h3>Title</h3>
<h3>Title B</h3>

BoldTag.Focusable(): True
--------------------------
<h3>Title</h3>
<b>Bold statement</b>
<h3>Title B</h3>
<b>Other text</b>
```

---

### Example ID: 139

**Description:** Focusable to select only patterns from local transformer

**Code:**
```pseudocode
var t = uc.NewTransformer();
var FruitsXML =
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <!-- <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' /> -->
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <!-- <Fruit CommonName='Mango' ScientificName='Mangifera indica' /> -->
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <!-- <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' /> -->
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <!-- <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' /> -->
</Fruits>
[/verbatim];

// List names of fruit within comment, not the whole comment as well
t.@Text(FruitsXML);
var CommentedFruits = t.Pattern("<!-- {comment} -->").SetFocusable(false);
var CommentedFruitsTr = CommentedFruits.@LocalTransformer();
CommentedFruitsTr.FromTo("CommonName={@string:text}", "{text}").@Focusable(true);

t.Filter();
wl("With Focusable()")
wl("----------------")
wl(t.GetMatches(MatchesOption::FocusableOnly).@Text())
wl("")

// Note: The displayed Fruit element is modified by CommentedFruitsTr.FromTo()
wl("Without Focusable()")
wl("-------------------")
wl(t.@Matches().@Text())
```

**Output:**
```
With Focusable()
----------------
Grapes
Mango
Rambutan
Watermelon

Without Focusable()
-------------------
<!-- <Fruit Grapes ScientificName='Vitis vinifera' /> -->
Grapes
<!-- <Fruit Mango ScientificName='Mangifera indica' /> -->
Mango
<!-- <Fruit Rambutan ScientificName='Nephelium lappaceum' /> -->
Rambutan
<!-- <Fruit Watermelon ScientificName='Citrullus lanatus' /> -->
Watermelon
```

---

### Example ID: 148

**Description:** MatchesOption: RootLevelOnly and InnermostOnly

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "<p id='aa'>xyz</p><p id='bb'>Hello</p ><p id='cc'>World</p>";
t.Str(txt);

t.Pattern("<p {etc}>").@LocalTransformer().FromTo("id={@string:id}", "{id}");
t.Filter();


wl("All matches")
wl("-----------")
wl(t.GetMatches(MatchesOption::All).@Text()) // All is the default
wl("")

wl("RootLevelOnly")
wl("-------------")
wl(t.GetMatches(MatchesOption::RootLevelOnly).@Text())
wl("")

wl("InnermostOnly")
wl("-------------")
wl(t.GetMatches(MatchesOption::InnermostOnly).@Text())
wl("")
```

**Output:**
```
All matches
-----------
<p aa>
aa
<p bb>
bb
<p cc>
cc

RootLevelOnly
-------------
<p aa>
<p bb>
<p cc>

InnermostOnly
-------------
aa
bb
cc
```

---

---

## MemoryIndex = [int] - ID: 612
/doc/reference/classes/ucalc.transformer/memoryindex-=-[int]/

**Description:** Returns the unique index value associated with the object

**Remarks:**

Mostly for internal use.

Each object has an integer index value that is unique to the object within the class.  Unlike the [topic: Handle] value that may change each time you run uCalc, the MemoryIndex value is predictable.

This function may not have other uses cases beyond troubleshooting.

---

## Owned - ID: 745
/doc/reference/classes/ucalc.transformer/owned/

**Description:** Marks the Transformer object for automatic memory release when it goes out of scope, enabling RAII-style lifetime management in C++.

**Syntax:** Owned()
**Return:** Transformer - Returns the current Transformer instance to allow for method chaining.
**Remarks:**

## 🛡️ Managing Transformer Lifetime: The `Owned` Method

The `Owned()` method is a crucial memory management tool, primarily for C++, that flags a `Transformer` object for automatic release when its corresponding variable goes out of scope. This aligns with the C++ RAII (Resource Acquisition Is Initialization) paradigm, preventing memory leaks by ensuring resources are cleaned up deterministically.

A `Transformer` can be a resource-intensive object, holding compiled rules, token sets, and match results. Proper resource management is essential.

### C++: Embracing RAII

`Owned()` is designed specifically for C++ developers to leverage the **RAII** pattern. When you declare an object as "owned", its destructor will automatically call [Release()](/Reference/uCalcBase/Transformer/Release), ensuring resources are freed when the object goes out of scope.

```pseudocode
[cpp]
{
    // An object created on the stack is a candidate for RAII.
    uCalc::Transformer myParser(uc);
    myParser.Owned(); // Now, myParser will be released automatically.
    
    myParser.FromTo("a", "b");
    wl(myParser.Transform("a c a"));

} // myParser's destructor is called here, which automatically calls Release().
[/cpp]
```

### C# and VB.NET: The `using` Keyword

In .NET languages, `Owned()` is **not needed**. The idiomatic way to ensure automatic resource cleanup is to use the `using` statement (C#) or `Using` block (VB.NET). All major uCalc objects, including `Transformer`, implement `IDisposable`, which integrates directly with this language feature.

```pseudocode
[cs]
// The 'using' statement ensures myParser.Release() is called automatically.
using (var myParser = uc.NewTransformer())
{
    myParser.FromTo("a", "b");
    wl(myParser.Transform("a c a"));
} // myParser is released here.
[/cs]
```

### Comparative Analysis

*   **vs. Standard Smart Pointers (`std::unique_ptr`)**: A C++ developer might ask, "Why not just return a `std::unique_ptr<Transformer>`?" uCalc uses an internal, cross-platform reference counting and object management system. The `Owned()` method acts as a bridge, allowing the C++-specific RAII pattern to interface cleanly with uCalc's internal lifetime management without exposing implementation details.

*   **vs. Manual `Release()` Calls**: Forgetting to call [Release()](/Reference/uCalcBase/Transformer/Release) is a common source of memory leaks. Using `Owned()` in C++ (or `using` in C#) makes resource management declarative and less error-prone. The cleanup is guaranteed by the language's scoping rules, leading to safer and more robust code.

**Examples:**

### Example ID: 162

**Description:** "using" (C#) and Owned (C++) for auto-releasing Transformer object

**Code:**
```pseudocode

// In C# and VB you should use "using".
// In C++ you can flag a uCalc object for
// auto-release with Owned(), or by setting
// the last parameter of the constructor to true.

New(uCalc::Transformer, t(uc))
var MemIndex = t.@MemoryIndex();
t.Release(); // MemIndex will be recycled and assigned to the next def

[NotCpp]// Use "using" so that the object is auto-released when it it goes out of scope[/NotCpp]
   NewUsing(uCalc::Transformer, TempTransform(uc)) [cpp]// Owned() causes TempTransform to be released when it goes out of scope[/cpp]
   wl(bool(TempTransform.@MemoryIndex() == MemIndex)) // MemoryIndex() will be the recycled value of the released t object
End Using
// TempTransform goes out of scope here

New(uCalc::Transformer, t3(uc))
wl(bool(t3.@MemoryIndex() == MemIndex)) // MemoryIndex() will be the recycled value of the released TempTransform object
t3.Release();

[c]{!Eval: Chr(123)}[/c][vb]If True Then[/vb][NotCpp]
   // Use "using" so that the object is auto-released when it it goes out of scope[/NotCpp]
   New(uCalc::Transformer, StickyTransformer(uc)) [cpp]// StickyTransformer here does NOT get released when it goes out of scope[/cpp]
   wl(bool(StickyTransformer.@MemoryIndex() == MemIndex))
[c]{!Eval: Chr(125)}[/c][vb]End If[/vb] // StickyTransformer remains in memery

New(uCalc::Transformer, t4(uc))
wl(bool(t4.@MemoryIndex() == MemIndex)) // False since StickyTransformer was not released; MemoryIndex() has a new value
```

**Output:**
```
True
True
True
False
```

---

---

## Pass - ID: 407
/doc/reference/classes/ucalc.transformer/pass/

**Description:** Creates or retrieves a sequential transformation stage (a pass), enabling multi-step text processing pipelines.

**Syntax:** Pass(int, bool)
**Parameters:**
index - int [default = -1] - The zero-based index of the pass to select or create. If the default value of -1 is used, a new pass is created at the end of the sequence.
share - bool [default = false] - If true, the pass inherits a copy of the rules from the main transformer. If false (default), the pass starts with a clean, empty rule set.
**Return:** Transformer - A `Transformer` object representing the specified pass, which can be configured with its own independent set of rules.
**Remarks:**

The `Pass` method is the entry point for creating multi-stage transformation pipelines. It allows you to break down a complex transformation into a sequence of simpler, independent steps. Each pass is its own [Transformer](/Reference/uCalcBase/Transformer/Constructor) object with its own set of rules.

### How It Works: A Sequential Pipeline

When `Transform()` is called on the main [Transformer](/Reference/uCalcBase/Transformer/Constructor), the input text is processed sequentially through each defined pass:
1.  The text is processed by Pass 0.
2.  The *output* of Pass 0 becomes the *input* for Pass 1.
3.  This continues until the final pass is complete.

This architecture is ideal for separating distinct logical stages, such as an initial data cleanup pass, followed by a data extraction pass, and finally a formatting pass.

### Creating and Accessing Passes

Passes are identified by a zero-based index.
*   **Create a new pass**: Call `Pass()` with no arguments or `-1`. This appends a new pass to the end of the sequence.
*   **Access an existing pass**: Call `Pass(n)` to retrieve the [Transformer](/Reference/uCalcBase/Transformer/Constructor) object for the nth pass.

### The `share` Parameter: Rule Inheritance

The `share` parameter controls whether a new pass inherits rules from the main (root) transformer.
*   **`share = false` (Default)**: The pass is created with a clean slate. It has its own isolated set of rules and does not inherit any from the parent.
*   **`share = true`**: The pass is created with a *copy* of all rules currently defined on the main transformer. You can then add more rules to the pass. Changes to the pass's rules will not affect the main transformer.

### 💡 Why uCalc? (Comparative Analysis)

Without the `Pass` system, you would need to manually create and manage a pipeline of separate [Transformer](/Reference/uCalcBase/Transformer/Constructor) objects, which is verbose and error-prone:

**Manual Approach:**
```pseudocode
New(uCalc::Transformer, t1)
New(uCalc::Transformer, t2)
// ... define rules for t1 and t2 ...

var(string, result1) = t1.Transform("input");
var(string, finalResult) = t2.Transform(result1);
```

**uCalc `Pass` Approach:**
```pseudocode
New(uCalc::Transformer, t)
var pass1 = t.Pass();
var pass2 = t.Pass();
// ... define rules for pass1 and pass2 ...

var(string, finalResult) = t.Transform("input");
```

uCalc's `Pass` method encapsulates the entire pipeline into a single object, simplifying the logic and making the transformation sequence easier to manage and understand.

**Examples:**

### Example ID: 1105

**Description:** A simple two-pass transformation where the output of the first pass becomes the input for the second.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("A");

// Pass 0 will change 'A' to 'B'
var pass0 = t.Pass(0);
pass0.FromTo("A", "B");

// Pass 1 will receive 'B' and change it to 'C'
var pass1 = t.Pass(1);
pass1.FromTo("B", "C");

t.Transform();
wl(t) // The final output is 'C'
```

**Output:**
```
C
```

---

### Example ID: 149

**Description:** Pass()

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

var t = uc.NewTransformer();
t.@Text(FruitsXML);

var Pass1 = t.Pass();
var Pass2 = t.Pass();

Pass1.@Description("Pass A");
Pass1.FromTo("Fruits", "ListOfFruits");
Pass1.FromTo("<Fruit CommonName={@str:name} ScientificName={@str:sci_name} />", "<Fruit>{name}</Fruit>");

Pass2.@Description("Pass B");
Pass2.FromTo("{Fruit: Apple | Orange | Mango }", "{Fruit} *");
Pass2.FromTo("{Fruit: Banana | Grapes | Watermelon }", "{Fruit} **");

t.Transform();
wl("All passes")
wl("----------")
wl(t.@Text())

wl(t.Pass(0).@Description())
wl(t.Pass(1).@Description())
wl("Pass count: ", t.PassCount())
wl("")

t.Str(FruitsXML);
Pass2.Release();
t.Transform();
wl("Pass1 only (Pass2 released)")
wl("---------------------------")
wl(t.@Text())

```

**Output:**
```
All passes
----------

<ListOfFruits>
  <Fruit>Apple *</Fruit>
  <Fruit>Banana **</Fruit>
  <Fruit>Orange *</Fruit>
  <Fruit>Grapes **</Fruit>
  <Fruit>Strawberry</Fruit>
  <Fruit>Pineapple</Fruit>
  <Fruit>Mango *</Fruit>
  <Fruit>Blueberry</Fruit>
  <Fruit>Rambutan</Fruit>
  <Fruit>Salak (Snake Fruit)</Fruit>
  <Fruit>Jabuticaba</Fruit>
  <Fruit>Watermelon **</Fruit>
</ListOfFruits>

Pass A
Pass B
Pass count: 2

Pass1 only (Pass2 released)
---------------------------

<ListOfFruits>
  <Fruit>Apple</Fruit>
  <Fruit>Banana</Fruit>
  <Fruit>Orange</Fruit>
  <Fruit>Grapes</Fruit>
  <Fruit>Strawberry</Fruit>
  <Fruit>Pineapple</Fruit>
  <Fruit>Mango</Fruit>
  <Fruit>Blueberry</Fruit>
  <Fruit>Rambutan</Fruit>
  <Fruit>Salak (Snake Fruit)</Fruit>
  <Fruit>Jabuticaba</Fruit>
  <Fruit>Watermelon</Fruit>
</ListOfFruits>
```

---

---

## PassCount - ID: 408
/doc/reference/classes/ucalc.transformer/passcount/

**Description:** Returns the number of passes

**Syntax:** PassCount()
**Return:** int - Integer
**Remarks:**

This returns the number of passes, as defined with Pass().

**Examples:**

### Example ID: 149

**Description:** Pass()

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

var t = uc.NewTransformer();
t.@Text(FruitsXML);

var Pass1 = t.Pass();
var Pass2 = t.Pass();

Pass1.@Description("Pass A");
Pass1.FromTo("Fruits", "ListOfFruits");
Pass1.FromTo("<Fruit CommonName={@str:name} ScientificName={@str:sci_name} />", "<Fruit>{name}</Fruit>");

Pass2.@Description("Pass B");
Pass2.FromTo("{Fruit: Apple | Orange | Mango }", "{Fruit} *");
Pass2.FromTo("{Fruit: Banana | Grapes | Watermelon }", "{Fruit} **");

t.Transform();
wl("All passes")
wl("----------")
wl(t.@Text())

wl(t.Pass(0).@Description())
wl(t.Pass(1).@Description())
wl("Pass count: ", t.PassCount())
wl("")

t.Str(FruitsXML);
Pass2.Release();
t.Transform();
wl("Pass1 only (Pass2 released)")
wl("---------------------------")
wl(t.@Text())

```

**Output:**
```
All passes
----------

<ListOfFruits>
  <Fruit>Apple *</Fruit>
  <Fruit>Banana **</Fruit>
  <Fruit>Orange *</Fruit>
  <Fruit>Grapes **</Fruit>
  <Fruit>Strawberry</Fruit>
  <Fruit>Pineapple</Fruit>
  <Fruit>Mango *</Fruit>
  <Fruit>Blueberry</Fruit>
  <Fruit>Rambutan</Fruit>
  <Fruit>Salak (Snake Fruit)</Fruit>
  <Fruit>Jabuticaba</Fruit>
  <Fruit>Watermelon **</Fruit>
</ListOfFruits>

Pass A
Pass B
Pass count: 2

Pass1 only (Pass2 released)
---------------------------

<ListOfFruits>
  <Fruit>Apple</Fruit>
  <Fruit>Banana</Fruit>
  <Fruit>Orange</Fruit>
  <Fruit>Grapes</Fruit>
  <Fruit>Strawberry</Fruit>
  <Fruit>Pineapple</Fruit>
  <Fruit>Mango</Fruit>
  <Fruit>Blueberry</Fruit>
  <Fruit>Rambutan</Fruit>
  <Fruit>Salak (Snake Fruit)</Fruit>
  <Fruit>Jabuticaba</Fruit>
  <Fruit>Watermelon</Fruit>
</ListOfFruits>
```

---

---

## Pattern - ID: 727
/doc/reference/classes/ucalc.transformer/pattern/

**Description:** Defines a find-only search pattern that locates text without replacing it, populating the matches collection.

**Syntax:** Pattern(string)
**Parameters:**
searchPattern - string - The uCalc pattern string that defines the text to find. It can contain literals, variables (e.g., `{name}`), and token category matchers (e.g., `{@Number}`).
**Return:** Rule - Rule containing the search pattern
**Remarks:**

The `Pattern` method defines a rule for finding text within a [Transformer](/Reference/uCalcBase/Transformer/Constructor) without replacing it. It is the primary method for pure search-and-analysis operations where the goal is to locate text segments and inspect their properties, rather than modify the source string.

### Implicit Replacement with `{@Self}`

Unlike its counterpart [FromTo()](/Reference/uCalcBase/Transformer/FromTo), which requires an explicit replacement string, `Pattern` has an implicit replacement behavior. If a rule defined with `Pattern` is used in a `Transform()` operation, it automatically uses the special `{@Self}` keyword as its replacement. This means the matched text is simply replaced by itself, leaving the source string unchanged but still populating the [Matches](/Reference/uCalcBase/Matches/Constructor) collection with the results of the find operation.

### `Pattern()` vs. `FromTo()`

Choosing the right method depends on your goal:

| Method | Purpose | Replacement Behavior | Primary Use Case |
| :--- | :--- | :--- | :--- |
| **`Pattern(p)`** | **Find Only** | Implicitly `{@Self}`. Re-inserts the matched text. | Locating patterns, counting occurrences, and analyzing text without modification. | 
| **`FromTo(p, r)`** | **Find and Replace** | Explicitly defined by the `r` parameter. | Text transformation, data normalization, search-and-replace. |

### 💡 Why uCalc? (Comparative Analysis)

For find-only operations, `Pattern` offers significant advantages over traditional regular expressions.

*   **Token-Awareness**: Regex is character-based and struggles with nested structures like `func(a, (b+c))`. uCalc's `Pattern` method operates on tokens, so it inherently understands these structures, preventing incorrect matches inside string literals or across mismatched brackets.
*   **Concurrent Patterns**: To search for multiple distinct patterns with regex, you must combine them into a large, unreadable alternation (`(pattern1|pattern2|...)`). With uCalc, you define each pattern with a separate, clear `Pattern()` call, and the engine executes them all concurrently in a single pass.

**Examples:**

### Example ID: 173

**Description:** Pattern: Simple Variable Capture

**Code:**
```pseudocode
var t = uc.NewTransformer();
t = "Here is the temperature: 98.6 F";

// Define the pattern first
t.Pattern("Temperature: {temp} F");

// Then execute the search
t.Find();

wl(t.@Matches()[0][cpp].@Text()[/cpp])
```

**Output:**
```
temperature: 98.6 F
```

---

### Example ID: 111

**Description:** Returns Start and End positions of Transformer matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>");
//         ^             ^                       ^              ^
//     012345678901234567890123456789012345678901234567890123456789
//     0         10        20        30        40        50
// Carrets (^) point to Start and End locations of the matches

wl(t.@Text())
wl("")

t.Pattern("<{tag}>{etc}</{tag}>");
t.Find();
var Matches = t.@Matches();

wl(Matches[0].@Text())
wl("Start pos: ", Matches[0].@StartPosition())
wl("End pos: ", Matches[0].@EndPosition())
wl("Length: ", Matches[0].@Length())
wl("")

wl(Matches[1].@Text())
wl("Start pos: ", Matches[1].@StartPosition())
wl("End pos: ", Matches[1].@EndPosition())
wl("Length: ", Matches[1].@Length())
```

**Output:**
```
<br><h1>First</h1>Blah Blah<br>Testing<br><h2>Second</h2>

<h1>First</h1>
Start pos: 4
End pos: 18
Length: 14

<h2>Second</h2>
Start pos: 42
End pos: 57
Length: 15
```

---

### Example ID: 114

**Description:** Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>");
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text())
   wl("Start pos: ", match.@StartPosition())
   wl("End pos: ", match.@EndPosition())
   wl("Length: ", match.@Length())
   wl("")
end foreach
```

**Output:**
```
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
```

---

---

## Range - ID: 409
/doc/reference/classes/ucalc.transformer/range/

**Description:** Restricts all subsequent find and transform operations to a specific character range within the source text.

**Syntax:** Range(int, int)
**Parameters:**
startPosition - int - The zero-based starting character position of the range.
length - int - The number of characters in the range. A value of -1 extends the range to the end of the string.
**Return:** Transformer - The current `Transformer` object, allowing for a fluent, chainable interface.
**Remarks:**

*(Note: This feature is not yet fully implemented and the final syntax may change.)*

The `Range` method sets a "window" on the source text, restricting all subsequent find and transform operations to a specific sub-section of the string. This is a powerful performance optimization, as it avoids the memory allocation and copying overhead of creating a manual substring.

### How It Works

When you call `Range`, the [Transformer](/Reference/uCalcBase/Transformer/Constructor) records the specified `startPosition` and `length`. Any subsequent calls to methods like [Find()](/Reference/uCalcBase/Transformer/Find) or [Transform()](/Reference/uCalcBase/Transformer/Transform) will operate only within this virtual boundary. 

Match positions (`StartPosition`, `EndPosition`) returned by the [Matches](/Reference/uCalcBase/Matches/Constructor) object remain relative to the **original, full source string**, preserving their global coordinates.

To clear the range and revert to searching the entire string, you can call `Range(0, -1)`.

### 💡 Why uCalc? (Comparative Analysis)

In a standard text processing workflow, to operate on a portion of a string, you must first create a substring.

**Manual Substring Approach (Less Efficient):**
```pseudocode
// 1. Create a new string in memory.
var sub = myString.Substring(100, 50);

// 2. Perform the transformation on the new, smaller string.
var result = t.Transform(sub);

// 3. Manually stitch the result back into the original string.
```
This approach is inefficient for large documents because it involves memory allocation and data copying. If you need the original match coordinates, you must also manually add the starting offset back.

**The uCalc `Range` Advantage:**
uCalc's `Range` method is a **zero-copy operation**. It doesn't create a new string. Instead, it adjusts the transformer's internal pointers to define a virtual search area. This is significantly faster and uses less memory, making it the ideal solution for parsing specific sections of large files, such as the body of an HTTP response or the content within a specific XML/HTML tag.

**Examples:**

---

## Release - ID: 410
/doc/reference/classes/ucalc.transformer/release/

**Description:** Explicitly frees all memory and resources associated with a Transformer instance, including all of its defined rules, tokens, and match results.

**Syntax:** Release()
**Return:** void - This method does not return a value.
**Remarks:**

### 💾 Core Concept: Freeing Engine Resources

The `Release()` method explicitly destroys a `Transformer` instance and deallocates all of its associated resources, including rules, tokens, passes, match lists, and the internal text buffer. It is the primary mechanism for manual memory management within the uCalc ecosystem.

### 🤔 Why is `Release()` Necessary? (Comparative Analysis)

uCalc's memory model is different from standard garbage-collected or native memory management, making `Release()` essential.

*   **vs. C# Garbage Collection (GC)**: In C#, when a `Transformer` object variable goes out of scope, the C# Garbage Collector only reclaims the memory for the **handle** (the C# wrapper object). The underlying C++ engine instance, which holds the bulk of the data, remains in memory. `Release()` is the signal to destroy that underlying engine instance. Without it, you will have a memory leak.

*   **vs. C++ `delete`**: uCalc uses its own internal memory manager for performance and object recycling. A `Transformer` handle is not a raw C++ pointer that can be managed with `delete`. Calling `Release()` ensures the object is returned to uCalc's internal pool correctly.

### ⚙️ Manual vs. Automatic Release (Best Practice)

While `Release()` provides manual control, the recommended approach is to use language-specific scoping mechanisms that call `Release()` for you automatically:

*   **C# / VB.NET**: Create the `Transformer` instance within a `using` block. The instance will be automatically released when the block is exited.
*   **C++**: For stack-allocated objects, call [Owned()](/Reference/uCalcBase/Transformer/Owned) to enable RAII. The `Transformer` instance is released when its destructor is called at the end of its scope.

Use `Release()` explicitly only when the lifetime of the `Transformer` object is not tied to a specific lexical scope.

### `Release()` vs. `Active(false)` vs. `Reset()`

It is crucial to choose the correct method for your needs:

| Method                                          | Purpose                     | Effect on Object                                 |
| :---------------------------------------------- | :-------------------------- | :----------------------------------------------- |
| **`Release()`** (This Method)                   | **Destroy** the object      | The object is destroyed and its memory is freed. The handle becomes invalid. |
| **[Rule.Active(false)](/Reference/uCalcBase/Rule/Active)** | **Temporarily disable** a rule | The rule's definition is preserved in memory but is ignored during matching. |
| **[Reset()](/Reference/uCalcBase/Transformer/Reset)** | **Clear the object's state**  | The `Transformer` object remains alive but is reset to its initial state (no text, no rules). |

**Idempotency Note**: `Release()` is idempotent. Calling it multiple times on the same (already released) handle is safe and has no effect.

**Examples:**

### Example ID: 149

**Description:** Pass()

**Code:**
```pseudocode
var FruitsXML = 
[verbatim]
<Fruits>
  <Fruit CommonName='Apple' ScientificName='Malus domestica' />
  <Fruit CommonName='Banana' ScientificName='Musa acuminata' />
  <Fruit CommonName='Orange' ScientificName='Citrus × sinensis' />
  <Fruit CommonName='Grapes' ScientificName='Vitis vinifera' />
  <Fruit CommonName='Strawberry' ScientificName='Fragaria × ananassa' />
  <Fruit CommonName='Pineapple' ScientificName='Ananas comosus' />
  <Fruit CommonName='Mango' ScientificName='Mangifera indica' />
  <Fruit CommonName='Blueberry' ScientificName='Vaccinium corymbosum' />
  <Fruit CommonName='Rambutan' ScientificName='Nephelium lappaceum' />
  <Fruit CommonName='Salak (Snake Fruit)' ScientificName='Salacca zalacca' />
  <Fruit CommonName='Jabuticaba' ScientificName='Plinia cauliflora' />
  <Fruit CommonName='Watermelon' ScientificName='Citrullus lanatus' />
</Fruits>
[/verbatim];

var t = uc.NewTransformer();
t.@Text(FruitsXML);

var Pass1 = t.Pass();
var Pass2 = t.Pass();

Pass1.@Description("Pass A");
Pass1.FromTo("Fruits", "ListOfFruits");
Pass1.FromTo("<Fruit CommonName={@str:name} ScientificName={@str:sci_name} />", "<Fruit>{name}</Fruit>");

Pass2.@Description("Pass B");
Pass2.FromTo("{Fruit: Apple | Orange | Mango }", "{Fruit} *");
Pass2.FromTo("{Fruit: Banana | Grapes | Watermelon }", "{Fruit} **");

t.Transform();
wl("All passes")
wl("----------")
wl(t.@Text())

wl(t.Pass(0).@Description())
wl(t.Pass(1).@Description())
wl("Pass count: ", t.PassCount())
wl("")

t.Str(FruitsXML);
Pass2.Release();
t.Transform();
wl("Pass1 only (Pass2 released)")
wl("---------------------------")
wl(t.@Text())

```

**Output:**
```
All passes
----------

<ListOfFruits>
  <Fruit>Apple *</Fruit>
  <Fruit>Banana **</Fruit>
  <Fruit>Orange *</Fruit>
  <Fruit>Grapes **</Fruit>
  <Fruit>Strawberry</Fruit>
  <Fruit>Pineapple</Fruit>
  <Fruit>Mango *</Fruit>
  <Fruit>Blueberry</Fruit>
  <Fruit>Rambutan</Fruit>
  <Fruit>Salak (Snake Fruit)</Fruit>
  <Fruit>Jabuticaba</Fruit>
  <Fruit>Watermelon **</Fruit>
</ListOfFruits>

Pass A
Pass B
Pass count: 2

Pass1 only (Pass2 released)
---------------------------

<ListOfFruits>
  <Fruit>Apple</Fruit>
  <Fruit>Banana</Fruit>
  <Fruit>Orange</Fruit>
  <Fruit>Grapes</Fruit>
  <Fruit>Strawberry</Fruit>
  <Fruit>Pineapple</Fruit>
  <Fruit>Mango</Fruit>
  <Fruit>Blueberry</Fruit>
  <Fruit>Rambutan</Fruit>
  <Fruit>Salak (Snake Fruit)</Fruit>
  <Fruit>Jabuticaba</Fruit>
  <Fruit>Watermelon</Fruit>
</ListOfFruits>
```

---

---

## Reset - ID: 411
/doc/reference/classes/ucalc.transformer/reset/

**Description:** Clears a transformer's state, such as its input text, rules, or match results, allowing for reuse without creating a new instance.

**Syntax:** Reset(TransformerResetOption)
**Parameters:**
resetOption - TransformerResetOption [default = TransformerResetOption::All] - Specifies which components of the transformer to clear. Defaults to clearing everything.
**Return:** Transformer - Returns the current `Transformer` object, allowing for a fluent, chainable interface.
**Remarks:**

# 🔄 Reusing Transformers with Reset

The `Reset` method clears some or all of a [Transformer's](/Reference/uCalcBase/Transformer/Constructor) state, allowing it to be reused for a new task without the performance overhead of creating a new object. This is essential for optimizing applications that perform many different transformation tasks.

By default, `Reset` performs a complete cleanup, but you can target specific components by providing a member of the [TransformerResetOption](/Reference/Enums/TransformerResetOption) enumeration.

## ⚙️ Reset Options

The `resetOption` parameter lets you choose what to clear:

| Option | Behavior | 
| :--- | :--- |
| `All` (Default) | **Complete Reset**. Clears input text, all rules ([FromTo](/Reference/uCalcBase/Transformer/FromTo), [Pattern](/Reference/uCalcBase/Transformer/Pattern), [SkipOver](/Reference/uCalcBase/Transformer/SkipOver)), custom [Tokens](/Reference/uCalcBase/Transformer/Tokens), transformation [Passes](/Reference/uCalcBase/Transformer/Pass), and match results. | 
| `Input` | **Clears Text Only**. Resets the internal text string to empty. All rules and token definitions are preserved. | 
| `Rules` | **Clears Rules Only**. Deletes all defined rules. The input text and custom token definitions remain. | 
| `Tokens` | **Clears Tokens Only**. Removes all custom token definitions and restores the default uCalc token set. Text and rules are preserved. | 
| `Results` | **Clears Matches Only**. Empties the internal list of matches from the last [Find()](/Reference/uCalcBase/Transformer/Find), [Filter()](/Reference/uCalcBase/Transformer/Filter), or [Transform()](/Reference/uCalcBase/Transformer/Transform) operation. | 
| `Passes` | **Clears Passes Only**. Removes any additional transformation passes created with [Pass()](/Reference/uCalcBase/Transformer/Pass), leaving the main pass (pass 0). | 

## 💡 Why Reset? (Comparative Analysis)

In a loop or a high-frequency processing scenario, you have two choices for handling multiple, independent transformation tasks:

1.  **Create a New Transformer**: [pseudocode]`New(uCalc::Transformer, t)`
    This is simple but has a performance cost. It involves allocating memory, copying default token sets, and other setup overhead for every new object.

2.  **Reuse and Reset**: [pseudocode]`t.Reset()`
    This is the **high-performance** option. `Reset()` clears the state of an existing object but reuses its memory allocation. It avoids the construction/destruction overhead, making it significantly faster for repetitive tasks.

**Best Practice**: For performance-critical applications, create a pool of `Transformer` objects and use `Reset()` to prepare them for each new task rather than creating new instances repeatedly.

**Examples:**

### Example ID: 1118

**Description:** Shows how a full reset clears all rules and input, allowing a transformer object to be reconfigured from a clean slate.

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "a b c d e";

t.@Text(txt);
t.FromTo("a", "aaa");
t.FromTo("c", "xyz");

wl("Input: ", t)
wl("Transformed: ", t.Transform())

wl("")
wl("Resetting...")
t.Reset();

wl("Input after reset: ", t, "(empty)")
t.@Text("a b c d e");
wl("New input: ", t.@Text())
wl("Transform after reset: ", t.Transform().@Text(), " (no rules exist)")

wl("")
wl("Defining new rules...")
t.FromTo("b", "ABC");
t.FromTo("d", "DDD");
wl("Final transformed: ", t.Transform().@Text())
```

**Output:**
```
Input: a b c d e
Transformed: aaa b xyz d e

Resetting...
Input after reset: (empty)
New input: a b c d e
Transform after reset: a b c d e (no rules exist)

Defining new rules...
Final transformed: a ABC c DDD e
```

---

### Example ID: 151

**Description:** Transformer Reset()

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "a b c d e";

t.@Text(txt);
t.FromTo("a", "aaa");
t.FromTo("c", "xyz");

wl("Input: ", t)
wl("Transformed: ", t.Transform())

wl("Reset")
t.Reset();

wl("Input: ", t, "(empty)")
t.@Text("a b c d e");
wl("New input: ", t.@Text())
wl("Transformed: ", t.Transform().@Text(), " (no transform)")
wl("New rules")

t.FromTo("b", "ABC");
t.FromTo("d", "DDD");
wl("Transformed: ", t.Transform().@Text())

```

**Output:**
```
Input: a b c d e
Transformed: aaa b xyz d e
Reset
Input: (empty)
New input: a b c d e
Transformed: a b c d e (no transform)
New rules
Transformed: a ABC c DDD e
```

---

---

## Setup - ID: 739
/doc/reference/classes/ucalc.transformer/setup/

**Description:** Creates a dedicated initialization pass that executes an expression before the main transformation rules, ideal for resetting state between runs.

**Syntax:** Setup(string)
**Parameters:**
expressionString - string - An expression string to be executed once at the beginning of each transform operation. Typically used to initialize or reset variables.
**Return:** Transformer - The `Transformer` object representing the newly created setup pass (Pass 0).
**Remarks:**

> **Note**: This feature is currently in the design phase and is not yet implemented in the production engine.

# ⚙️ Creating a Setup Pass for State Management

The `Setup()` method creates a dedicated, high-priority **initialization pass** (Pass 0) for a [Transformer](/Reference/uCalcBase/Transformer). This pass executes a given expression once at the very beginning of each `Transform()` operation, making it the ideal mechanism for resetting stateful variables before the main transformation rules are applied.

### How It Works: The `{@All}` and `{@Exec}` Shortcut

`Setup()` is a convenient shortcut for a common multi-pass pattern. A call like:
[pseudocode]`t.Setup("counter = 0; total = 0;");`

is equivalent to creating a new pass and defining a special rule:
[pseudocode]`t.Pass().FromTo("{@All}", "{@Self}{@Exec: counter = 0; total = 0;}");`

This works because:
1.  **`Pass()`**: Creates a new pass. If it's the first one, it becomes Pass 0.
2.  **`{@All}`**: Matches the entire input text as a single, efficient block. It doesn't perform a costly token-by-token search, making it a very fast way to trigger a one-time action.
3.  **`{@Self}`**: Re-inserts the original text unmodified.
4.  **`{@Exec}`**: Executes the setup expression for its side effects (e.g., setting variables) without inserting any text into the output.

After using `Setup()`, subsequent rules should be added to a new pass (created with [Pass()](/Reference/uCalcBase/Transformer/Pass)) to ensure they run *after* the setup pass.

### Primary Use Case: Resetting State Between `Transform()` Calls

`Setup()` is essential when you use the same transformer instance to process multiple, independent text blocks. Without a setup pass, state from one transformation (like an incremented counter) would leak into the next.

## 💡 Why uCalc? (Comparative Analysis)

In a typical programming workflow, you would manage state manually in your host application code.

**Manual Approach (C#):**
```csharp
var t = uc.NewTransformer();
uc.DefineVariable("counter = 0");
t.FromTo("item", "{@Eval: counter++}");

foreach (var textBlock in myTextBlocks)
{
    uc.Eval("counter = 0"); // Manual reset before each transform
    var result = t.Transform(textBlock);
    // ...
}
```

This approach mixes the state management logic with the application's control flow.

**The uCalc `Setup()` Advantage:**
uCalc's `Setup()` method is **declarative**. It moves the state initialization logic *into* the transformer's definition.

```pseudocode
var t = uc.NewTransformer();
t.Setup("counter = 0"); // State reset is now part of the transformer
var mainPass = t.Pass();
mainPass.FromTo("item", "{@Eval: counter++}");

foreach (var textBlock in myTextBlocks)
{
    var result = t.Transform(textBlock); // Reset happens automatically
    // ...
}
```

This creates a self-contained, stateful component that is cleaner, more reusable, and less prone to errors, as the responsibility for resetting state is handled automatically by the transformer itself.

**Examples:**

---

## SkipOver - ID: 728
/doc/reference/classes/ucalc.transformer/skipover/

**Description:** Defines a pattern for text that the transformer should ignore, effectively treating it as a 'dead zone' for all other find and replace rules.

**Syntax:** SkipOver(string)
**Parameters:**
pattern - string - The pattern defining the text to be ignored by all other find/replace rules.
**Return:** Rule - Rule object
**Remarks:**

# 🛡️ Excluding Text with SkipOver

The `SkipOver` method defines a "dead zone" or "no-fly zone" for the transformer. Any text that matches the specified `pattern` is completely ignored by all other find and replace rules ([FromTo](/Reference/uCalcBase/Transformer/FromTo) and [Pattern](/Reference/uCalcBase/Transformer/Pattern)).

This is the primary mechanism for protecting sections of text from being transformed, with the most common use case being code or markup comments.

### 🥇 Precedence is Key

It is crucial to understand that **`SkipOver` rules are evaluated before any other type of rule**. They have the highest precedence. If a segment of text matches a `SkipOver` pattern, it is immediately excluded from further processing, and no `FromTo` or `Pattern` rules will be tested against it, regardless of their definition order.

### `SkipOver` vs. `FromTo(pattern, "{@Self}")`

One might think that a rule like [pseudocode]`t.FromTo("/* {comment} */", "{@Self}")` would have the same effect. This is incorrect for two critical reasons:

1.  **Precedence**: A `FromTo` rule competes with all other `FromTo` and `Pattern` rules based on definition order (LIFO). A `SkipOver` rule *always* wins.
2.  **Matching**: A `FromTo` rule still creates a `Match` object that is added to the results collection. A `SkipOver` match is not recorded and does not appear in the final [Matches](/Reference/uCalcBase/Matches) list.

### ⚖️ Comparative Analysis

*   **vs. Regular Expressions**: In standard regex, achieving this "skip" behavior is complex. It often requires negative lookarounds (`(?<!...)` and `(?!...)`) or multiple, carefully ordered processing passes. For example, to replace `var` but not inside a comment, you would need a complicated regex or pre-process the text to remove comments first, then add them back. uCalc's `SkipOver` makes this a single, declarative, and highly readable step.

**Conclusion**: Use `SkipOver` for any content that should be completely invisible to the rest of your transformation logic.

**Examples:**

### Example ID: 1123

**Description:** How `SkipOver` creates 'dead zones' where other rules are not applied.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.@Text("transform this but (not this) and this");

// A rule to replace the word 'this'
t.FromTo("this", "THAT");

// A rule to ignore any content inside parentheses
t.SkipOver("({content})");

// The 'this' inside the parentheses is protected by the SkipOver rule
wl(t.Transform())
```

**Output:**
```
transform THAT but (not this) and THAT
```

---

### Example ID: 1124

**Description:** A practical, real-world example of using `SkipOver` to ignore HTML comments while transforming other parts of the document.

**Code:**
```pseudocode
var t = uc.NewTransformer();
// Disable statement sensitivity to handle multi-line content
t.@DefaultRuleSet().@StatementSensitive(false);

var htmlContent =
[verbatim]
<nav>
  <li><a href="#intro">Intro</a></li>
  <!-- <li><a href="#contact">Contact</a></li> -->
  <li><a href="#about">About</a></li>
</nav>
[/verbatim];
t.@Text(htmlContent);

// A rule to find all list items
t.Pattern("<li>{item}</li>");

// A rule to skip over HTML comments
t.SkipOver("<!-- {comment} -->");

t.Find();
wl("--- Found List Items ---")
wl(t.@Matches().@Text())
```

**Output:**
```
--- Found List Items ---
<li><a href="#intro">Intro</a></li>
<li><a href="#about">About</a></li>
```

---

### Example ID: 137

**Description:** SkipOver(),  Str(), Implicit Str()

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "a b c (a b c a b c) a b c";
t.FromTo("a", "AA");

// You can either set the string before or pass it to Transform()
t.Str(txt);
wl(t.Transform().@Text())

t.SkipOver("({text})");
wl(t.Transform(txt)) // Implicit Text property
```

**Output:**
```
AA b c (AA b c AA b c) AA b c
AA b c (a b c a b c) AA b c
```

---

### Example ID: 110

**Description:** How to find matched patterns while skipping commented text using SkipOver().

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("int result = (x + 3) * 2 - (y - 7 / z) * (5 ^ a + 10); /* (x + y) */");

// Capture standard blocks surrounded by parentheses
t.Pattern("({expr})");

// Instruct the transformer to ignore any text inside C-style block comments.
// This prevents the commented "(x + y)" from being falsely counted as a match.
t.SkipOver("/* {etc} */"); // commented text between /* */ is skipped

t.Find();
wl(t.@Matches().Count())
```

**Output:**
```
3
```

---

### Example ID: 114

**Description:** Matches

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<h3>Title</h3><b>Bold statement</b><!--<h3>Title B</h3>--><b>Other text</b><p>My paragraph</p>");
//     0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456
//     0         10        20        30        40        50        60        70        80        90
//     ^             ^                                           ^                ^                  ^
// Carrets (^) represent starting and ending point of the matches

t.Pattern("<{tag}>{text}</{tag}>");
t.Pattern("<b>{text}</b>");
t.Pattern("<h3>{text}</h3>");
t.SkipOver("<!--{text}-->");
t.Find();

foreach(var match in t.@Matches())
   wl(match.@Text())
   wl("Start pos: ", match.@StartPosition())
   wl("End pos: ", match.@EndPosition())
   wl("Length: ", match.@Length())
   wl("")
end foreach
```

**Output:**
```
<h3>Title</h3>
Start pos: 0
End pos: 14
Length: 14

<b>Bold statement</b>
Start pos: 14
End pos: 35
Length: 21

<b>Other text</b>
Start pos: 58
End pos: 75
Length: 17

<p>My paragraph</p>
Start pos: 75
End pos: 94
Length: 19
```

---

### Example ID: 125

**Description:** Using SkipOver() to ignore XML-style comments

**Code:**
```pseudocode
// StatementSensitive() is set to false so that ";" and newline are not treated as special

var t = uc.NewTransformer();
wl("StatementSensitive: ", bool(t.@DefaultRuleSet().@StatementSensitive()))
wl("Setting StatementSensitive to False")

t.@DefaultRuleSet().@StatementSensitive(false); // so that newline does not behave as a statement separator

wl("StatementSensitive: ", bool(t.@DefaultRuleSet().@StatementSensitive()))
wl("")

var Content =
[verbatim]
<nav aria-label="Main navigation">
  <ul>
    <li><a href="#intro">Intro</a></li>
    <li><a href="#examples">Examples</a></li>
    <!-- <li><a href="#contact">Contact</a></li> -->
  </ul>
</nav>

<!-- 
<h2>Ingredients</h2>
<ul>
  <li>3 cups flour</li>
  <li>1.5 cups water</li>
  <li>1 tsp salt</li>
</ul>
-->

<nav aria-label="Chapter navigation">
    <ul>
      <li><a href="#one">One</a></li>
      <li><a href="#two">Two</a></li>
      <li><a href="#three">Three</a></li>
    </ul>
</nav>
[/verbatim];

t.Str(Content);
var Pattern = t.Pattern("<li>{item}</li>");
t.Find();
wl(t.@Matches().@Text())
wl("")

wl("<!-- Skip over commented lines -->")
wl("----------------------------------")
t.SkipOver("<!-- {comment} -->");
t.Find();
wl(t.@Matches().@Text())
wl("")

```

**Output:**
```
StatementSensitive: True
Setting StatementSensitive to False
StatementSensitive: False

<li><a href="#intro">Intro</a></li>
<li><a href="#examples">Examples</a></li>
<li><a href="#contact">Contact</a></li>
<li>3 cups flour</li>
<li>1.5 cups water</li>
<li>1 tsp salt</li>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>

<!-- Skip over commented lines -->
----------------------------------
<li><a href="#intro">Intro</a></li>
<li><a href="#examples">Examples</a></li>
<li><a href="#one">One</a></li>
<li><a href="#two">Two</a></li>
<li><a href="#three">Three</a></li>
```

---

---

## Stop - ID: 738
/doc/reference/classes/ucalc.transformer/stop/

**Description:** Defines a global stop pattern that acts as an uncrossable boundary for all variable captures within the transformer.

**Syntax:** Stop(string)
**Parameters:**
pattern - string - The pattern string that defines the stop boundary.
**Return:** Rule - Returns the newly created [Rule](/Reference/uCalcBase/Rule/Constructor) object representing the stop pattern, which can be used to modify or release it.
**Remarks:**

> **Note**: This feature is currently in the design phase and is not yet implemented in the production engine.

The `Stop` method defines a global "hard stop" boundary for an entire [Transformer](/Reference/uCalcBase/Transformer/Constructor) instance. When any rule's variable (e.g., `{body}`) is capturing text, it will immediately stop if it encounters a match for a `Stop` pattern. The stop pattern itself is not consumed and is not part of any match.

This is a powerful feature for parsing text with well-defined but un-consumable terminators, such as an `END` keyword or a block delimiter that should not be part of any capture.

### 🎯 Behavior and Precedence

- **Global Scope**: A `Stop` pattern applies to **all** rules within the [Transformer](/Reference/uCalcBase/Transformer/Constructor). It is not tied to a specific `FromTo` or `Pattern` rule.
- **LIFO Precedence**: If you define multiple `Stop` patterns, the **most recently defined** one has the highest precedence and will be checked for first.

### 🆚 Comparison with Other Boundary Mechanisms

It is crucial to understand how `Stop` differs from other boundary types in uCalc:

| Mechanism | Scope | Behavior | Use Case |
| :--- | :--- | :--- | :--- |
| **Rule Anchor** | Rule-specific | **Consumed**. Becomes part of the match (`{@Self}`). | Defining the start or end of a specific pattern. |
| **Statement Separator** | Instance-wide | **Consumed**. A token type (like `;`) that terminates a capture if [StatementSensitive](/Reference/uCalcBase/Rule/StatementSensitive) is true. | Parsing code or line-based data where newlines are significant. |
| **`{@Stop}` Directive** | Rule-specific | **Not Consumed**. Truncates what is included in the `{@Self}` capture for a single rule. | Creating a lookahead within a single pattern. |
| **`Stop()` Method** | **Transformer-wide** | **Not Consumed**. A global boundary that terminates *any* variable capture in *any* rule. | Defining a universal terminator for a document format. |

### 💡 Why uCalc? (Comparative Analysis)

`Transformer.Stop` is conceptually similar to a **positive lookahead** in regular expressions (`(?=...pattern...)`), which asserts that a pattern must exist without consuming it.

However, uCalc's `Stop` patterns have a key advantage: they are **token-aware**. A regex lookahead operates on raw characters and can be difficult to write for structured data. A `Stop` pattern operates on the token stream, so it inherently respects word boundaries, quoted strings, and other language constructs, making it a more robust and reliable tool for parsing.

**Examples:**

---

## StrData - ID: 417
/doc/reference/classes/ucalc.transformer/strdata/

**Description:** Returns actual character base pointer of string

**Syntax:** StrData()
**Return:** CONSTCHAR - Pointer to byte array
**Remarks:**

This returns a pointer to the actual location in memory of a Transformer string.  This is the string that is returned by Str().  Note: This should never be used alone.  Always use it in pair with StrLength.

---

## StrLength - ID: 418
/doc/reference/classes/ucalc.transformer/strlength/

**Description:** Gets the length, in characters, of the string currently held by the Transformer.

**Syntax:** StrLength()
**Return:** int - The number of characters in the string.
**Remarks:**

# 📏 Getting String Length: The `Length` Property

The `@Length` property returns the number of characters in the string currently held by the [Transformer](/Reference/uCalcBase/Transformer/Constructor) and available via the [@Text](/Reference/uCalcBase/Transformer/Text) property.

### ⚡ Performance Advantage

This property is highly efficient. It retrieves the length of the internal string buffer without needing to copy the entire string into a new object. This is a significant performance advantage when working with very large documents (megabytes or gigabytes), as you can check the size of the data before deciding whether to perform an expensive transformation or retrieval operation.

### `@Length` vs. `StrData`

It's important to use `@Length` in conjunction with [StrData](/Reference/uCalcBase/Transformer/StrData) when working with raw memory pointers, particularly in C++. `StrData` returns a pointer to the start of the character buffer, and `@Length` provides the size of that buffer, allowing for safe, bounded memory operations.

### 💡 Comparative Analysis

This property is analogous to `.Length` on a `string` in C# or `.length()` on a `std::string` in C++. However, its context within the [Transformer](/Reference/uCalcBase/Transformer/Constructor) is key.

*   **Before vs. After Transformation**: The value of `@Length` changes dynamically as you perform transformations that alter the string. You can call `@Length()` before a [Transform](/Reference/uCalcBase/Transformer/Transform) and after it to see how the string's size was affected.

*   **Integrated Workflow**: uCalc's API provides a cohesive environment. You can load a string, check its `@Length`, define rules, run a [Transform](/Reference/uCalcBase/Transformer/Transform), and then check the new `@Length`, all using a single [Transformer](/Reference/uCalcBase/Transformer/Constructor) object. This is a more integrated workflow than manually passing strings between different functions in native code.

**Examples:**

### Example ID: 157

**Description:** StrLength()

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.Str("a b c d e f");
t.FromTo("{ a | d }", "xy");

wl(t)
wl("Length: ", t.StrLength())
wl("")
wl(t.Transform())
wl("Length: ", t.StrLength())
```

**Output:**
```
a b c d e f
Length: 11

xy b c xy e f
Length: 13
```

---

---

## Text = [string] - ID: 857
/doc/reference/classes/ucalc.transformer/text-=-[string]/

**Description:** Gets or sets the primary source text string that the transformer will search or modify.

**Remarks:**

# 📝 The Core Text Property

The `Text` property is the primary interface for managing the source string that a [Transformer](/Reference/uCalcBase/Transformer/Constructor) operates on. It functions as both a getter to retrieve the current (potentially transformed) text and a setter to assign a new source string.

This property is a fundamental part of the transformation workflow:
1.  **Set**: You assign the initial input string to the `Text` property.
2.  **Process**: You call methods like [Find()](/Reference/uCalcBase/Transformer/Find) or [Transform()](/Reference/uCalcBase/Transformer/Transform) to process the text.
3.  **Get**: You retrieve the final, modified string from the `Text` property.

## ⚙️ Getter and Setter Behavior

*   **Getter**: Retrieves the current string content of the transformer.
    [pseudocode]`var currentText = myTransformer.@Text();`

*   **Setter**: Assigns a new source string, overwriting any previous content.
    [pseudocode]`myTransformer.@Text("new source text");`

## ✨ Shortcut Notations (Implicit Conversions)

To enhance developer experience and reduce boilerplate, the [Transformer](/Reference/uCalcBase/Transformer/Constructor) object (along with [uCalc.String](/Reference/uCalcBase/String/Constructor)) supports implicit conversions to and from the native string type. This makes the `Text` property feel like the default property of the object.

*   **Implicit Setter**: Assigning a string literal directly to a transformer variable is a shortcut for setting its `Text` property.
    *   **Verbose**: [pseudocode]`t.@Text("Hello World");`
    *   **Shortcut**: [pseudocode]`t = "Hello World";`

*   **Implicit Getter**: Using a transformer object in a context that expects a string (like assigning it to a string variable or passing it to `wl()`) is a shortcut for getting its `Text` property.
    *   **Verbose**: [pseudocode]`var result = t.@Text();`
    *   **Shortcut**: [pseudocode]`var result = t;`

For a detailed explanation of this feature, see the [Shortcut notations](/Concepts/Shortcut-notations) topic.

## 💡 Why uCalc? (Comparative Analysis)

In standard libraries, interacting with string-like objects often requires explicit method calls.

*   **C# `StringBuilder`**: You must call `.ToString()` to get the final string.
*   **C++ `std::stringstream`**: You must call `.str()` to retrieve the content.

While these are perfectly functional, uCalc's design choice to implement implicit conversions provides a more intuitive and seamless experience. The `Transformer` object can be treated almost like a native string, making the code more readable and less cluttered with ceremonial method calls. This focus on an ergonomic API design is a key differentiator, allowing developers to write more expressive code.

**Examples:**

### Example ID: 1132

**Description:** A basic example of setting the text, transforming it, and retrieving the result.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// 1. Set the initial text
t.@Text("The quick brown fox.");

// 2. Define a rule and transform
t.FromTo("brown", "red");
t.Transform();

// 3. Get the final text
wl(t.@Text())
```

**Output:**
```
The quick red fox.
```

---

### Example ID: 1133

**Description:** Demonstrates using the Text property with implicit conversions (shortcuts) to parse a simple config string.

**Code:**
```pseudocode
New(uCalc::Transformer, t)

// Implicitly set the Text property by assigning a string to the object
t = "user=admin; level=9; theme=dark;";

// Define a rule to extract the user value
t.FromTo("user={name};", "Username: {name}");
t.Transform();

// Implicitly get the Text property by using the object in a string context
var(string, result) = t;
wl(result)
```

**Output:**
```
Username: admin level=9; theme=dark;
```

---

### Example ID: 156

**Description:** Implicit Str(), Transform()

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("a", "XY");

t.@Text("a b c a b c");
wl(t.Transform().@Text()) // Text that was set before trasnform
wl(t.Transform("c b a c b a").@Text()) // text passed to Transform()
wl(t.Transform("a, b, a, b")) // Implicit; Text property can be omitted
```

**Output:**
```
XY b c XY b c
c b XY c b XY
XY, b, XY, b
```

---

### Example ID: 173

**Description:** Pattern: Simple Variable Capture

**Code:**
```pseudocode
var t = uc.NewTransformer();
t = "Here is the temperature: 98.6 F";

// Define the pattern first
t.Pattern("Temperature: {temp} F");

// Then execute the search
t.Find();

wl(t.@Matches()[0][cpp].@Text()[/cpp])
```

**Output:**
```
temperature: 98.6 F
```

---

### Example ID: 130

**Description:** Rule Name

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@Text("<b>(5+4)</b> this and that etc");
var a = t.Pattern("<{tg}>");
var b = t.Pattern("This {body} That");
var c = t.Pattern("etc");
var d = t.Pattern("({expr})");

t.Filter();
wl("--- Matches ---")
wl(t.@Matches().@Text())
wl("--- Pattern names ---")
wl(a.@Name())
wl(b.@Name())
wl(c.@Name())
wl(d.@Name())
wl("--- Pattern defs ---")
wl(a.@Pattern())
wl(b.@Pattern())
wl(c.@Pattern())
wl(d.@Pattern())
```

**Output:**
```
--- Matches ---
<b>
(5+4)
</b>
this and that
etc
--- Pattern names ---
<
this
etc
(
--- Pattern defs ---
<{tg}>
This {body} That
etc
({expr})
```

---

---

## Tokens = [Tokens] - ID: 420
/doc/reference/classes/ucalc.transformer/tokens-=-[tokens]/

**Description:** Provides access to the collection of token definitions, allowing for dynamic customization of the transformer's lexical rules.

**Remarks:**

The `@Tokens()` property is your gateway to the [Transformer's](/Reference/uCalcBase/Transformer/Constructor) lexical analysis engine. It returns the [Tokens](/Reference/uCalcBase/Tokens/Constructor) object that defines how an input string is broken down into fundamental units (tokens) before being processed by pattern-matching rules.

### Why Customize Tokens?

Modifying the default token set allows you to extend the `Transformer`'s syntax to support new language constructs. Common use cases include:

*   **Defining Custom Literals**: Add support for C-style hexadecimal (`0x...`) or binary (`0b...`) numbers.
*   **Extending Identifiers**: Change the rules for what constitutes a "word", for example, to allow characters like `-` or `$` in identifiers.
*   **Creating Custom Comment Styles**: Implement single-line (`//...`), multi-line (`/*...*/`), or other language-specific comment formats to be ignored by your rules via [SkipOver](/Reference/uCalcBase/Transformer/SkipOver).
*   **Adapting to Data Formats**: Tailor the tokenizer to a specific format like CSV or a custom log file structure.

### Token Precedence (LIFO)

By default, tokens are evaluated in a Last-In, First-Out (LIFO) order. **The most recently added token is checked first**, giving it the highest precedence. This is crucial for resolving ambiguity. For example, you should define specific keywords (like `if` or `else`) *after* you define the general-purpose alphanumeric token to ensure they are matched first.

### 💡 Why uCalc? (Comparative Analysis)

*   **vs. Static Lexer Generators (e.g., ANTLR, Lex/Flex)**: Traditional compiler tools require an external toolchain, a separate grammar file, and a code generation/build step. This process is static. uCalc's key advantage is that its token engine is **fully dynamic and programmatic**. You can add, remove, or modify token definitions at runtime using the `Tokens` API, without any external tools or recompilation. This provides unparalleled flexibility for creating adaptable and user-extendable DSLs.

*   **vs. Manual Regex & String Splitting**: Manually parsing input with string functions and regular expressions is complex and error-prone. Standard regex struggles with nested structures (like parentheses) and context (distinguishing an operator from a character inside a string). uCalc's tokenizer is structured, context-aware, and handles these challenges automatically.

**Examples:**

### Example ID: 1135

**Description:** Adds a C-style single-line comment token and categorizes it as whitespace to be ignored by other rules.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("this", "THAT");

var(string, text) = "transform this but not // this in a comment";

wl("--- Before --- ")
// Initially, the comment is treated as regular text.
wl(t.Transform(text))

// Add a token for C-style comments and classify it as whitespace.
t.@Tokens().Add("//.*", TokenType::Whitespace);

wl("")
wl("--- After --- ")
// Re-run the transform. The comment is now ignored.
wl(t.Transform(text))
```

**Output:**
```
--- Before --- 
transform THAT but not // THAT in a comment

--- After --- 
transform THAT but not // this in a comment
```

---

### Example ID: 1136

**Description:** Practical: Modifies the default alphanumeric token to include hyphens, allowing it to match hyphenated identifiers as single words.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("{@Alpha:word}", "[{word}]");
var(string, text) = "id-E123 is a special-identifier.";

wl("--- Before --- ")
// By default, 'id-123' is tokenized as three separate parts: 'id', '-', and '123'.
wl(t.Transform(text))

// Get the alphanumeric token item by its name and modify its regex.
var alphaToken = t.@Tokens()["_token_alphanumeric"];
alphaToken.@Regex("[a-zA-Z0-9-]+");

wl("")
wl("--- After --- ")
// Now, hyphenated words are matched as single alphanumeric tokens.
wl(t.Transform(text))
```

**Output:**
```
--- Before --- 
[id]-[E123] [is] [a] [special]-[identifier].

--- After --- 
[id-E123] [is] [a] [special-identifier].
```

---

### Example ID: 155

**Description:** Transformer: Matching by tokens vs match by character; also whitespace sensitivity

**Code:**
```pseudocode
// This examples shows the default match by
// token mode, as well as how to reconfigure
// it in order to do match by character
// along with a whitespace variation

var t = uc.NewTransformer();
var txt = "This is an island test, I said.";
t.FromTo("is", "<is>");

wl(t.Transform(txt))
wl("")

t.@Tokens().@Description("Match by character");
t.@Tokens().Add("."); // This overrides existing tokens
t.FromTo("is", "<is>");
wl(t.@Tokens().@Description())
wl(t.Transform(txt))
wl("")

// Note: whitespace sensitivity is off by default
// Whitespace token is re-introduced
// (after being overridden in the previous Token Add())
t.@Tokens().@Description("By char + whitespace ignored");
t.@Tokens().Add("[\\t\\v ]+", TokenType::Whitespace);
t.FromTo("is", "<{@Self}>");
wl(t.@Tokens().@Description())
wl(t.Transform(txt))
```

**Output:**
```
This <is> an island test, I said.

Match by character
Th<is> <is> an <is>land test, I said.

By char + whitespace ignored
Th<is> <is> an <is>land test, <I s>aid.
```

---

### Example ID: 1364

**Description:** Returns the default list of tokens (index, description, name, regex) in a transformer

**Code:**
```pseudocode
var t = uc.NewTransformer();
wl("Token Count: ", t.@Tokens().@Count())
wl("")
wl("Index  Type  Name: regex")
wl("========================")

foreach (var token in t.@Tokens())
   w(t.@Tokens().IndexOf(token))
   wl("  ", token.@Description(), "  ", token.@Name(), ": ", token.@Regex())
end for
```

**Output:**
```
Token Count: 27

Index  Type  Name: regex
========================
0  generic  _token_line: .*
1  generic  _token_catchall: .
2  generic  _token_catchall_utf8_other: [\xf0-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf][\x80-\xbf]|[\xc0-\xdf][\x80-\xbf]
3  generic  _token_punctuation: (--|\.{3}|\xE2\x80\xA6|[!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]|\xE2\x80[\x90-\x95])
4  generic  _token_quotechar: ("){3}|"|'
5  generic  _token_quotechar_single: '
6  generic  _token_quotechar_double: "
7  generic  _token_quotechar_tripledouble: """
8  memberaccess  _token_memberaccess: \.
9  generic  _token_variableargs: \.\.\.
10  reducible  _token_reducible2: [-:|+/*^&=%@!`\\<>?#$~]+
11  bracket  _token_parenthesis: \(
12  bracketclose  _token_parenthesis_close: \)
13  bracket  _token_curlybrace: \{
14  bracketclose  _token_curlybrace_close: \}
15  bracket  _token_squarebracket: \[
16  bracketclose  _token_squarebracket_close: \]
17  argseparator  _token_argseparator: ,
18  statementseparator  _token_newline: (?:\r?\n)|\r
19  statementseparator  _token_semicolon: ;
20  literal  _token_string_singlequoted: '([^']*(?:''[^']*)*)'
21  literal  _token_string_doublequoted: "([^"]*(?:""[^"]*)*)"
22  literal  _token_string_tripledoublequoted: """([\s\S]*?)"""
23  whitespace  _token_whitespace: [\t\v ]+
24  reducible  _token_reducible: [-:|+/*^&=%@!`\\<>?]+
25  literal  _token_floatnumber: [0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?
26  alphanumeric  _token_alphanumeric: [a-zA-Z_][a-zA-Z0-9_]*
```

---

---

## TraceTransform - ID: 424
/doc/reference/classes/ucalc.transformer/tracetransform/

**Description:** Captures each intermediate step of a cascading or recursive transformation, returning a list of strings for debugging and analysis.

**Syntax:** TraceTransform(string)
**Parameters:**
expressionString - string - The expression string to transform and trace.
**Return:** String - A [uCalc.String](/Reference/uCalcBase/String/Constructor) object that acts as a list. Each item in the list is a string representing one step in the transformation process.
**Remarks:**

The `TraceTransform` method is a powerful debugging and introspection tool that executes a transformation and returns a complete history of every intermediate step. It is particularly useful for understanding how rules with the [RewindOnChange](/Reference/uCalcBase/Rule/RewindOnChange) property create cascading or recursive transformations.

### How It Works

Instead of returning just the final transformed string, `TraceTransform` captures the state of the string after each successful rule application. It returns a [uCalc.String](/Reference/uCalcBase/String/Constructor) object that acts as a list, where each item in the list is a snapshot of the string at one point in the transformation sequence.

This is invaluable for debugging complex rule sets where the output of one rule becomes the input for another.

### Handling the Result: A List-like `uCalc.String`

The returned [uCalc.String](/Reference/uCalcBase/String/Constructor) object is a collection of strings. You can format its output using its list-formatting methods before retrieving the final text:

*   **[ListSeparator()](/Reference/uCalcBase/String/ListSeparator)**: Sets the separator string to be inserted between each step (e.g., a newline `"{@nl}"`).
*   **[ListFormat()](/Reference/uCalcBase/String/ListFormat)**: Provides advanced control over the output, allowing you to define prefixes, postfixes, and a custom formatting expression for each step.
*   **Iteration**: You can iterate through the returned object to process each step individually.

### 💡 Why uCalc? (Comparative Analysis)

Without `TraceTransform`, debugging a multi-step transformation is a manual, imperative process:

*   **Manual Logging**: You would have to insert logging statements or set breakpoints inside your application's logic to see how the string changes after each pass of a `while` loop that simulates a recursive transform.
*   **Step-Through Debugging**: While possible, it can be difficult to visualize the overall flow and see all intermediate states at once.

`TraceTransform` provides a **declarative** and **integrated** solution. It's a built-in feature of the engine that captures the entire history of a transformation automatically. This allows you to get a complete, high-level overview of the process in a single call, making it significantly easier to diagnose complex rule interactions, identify infinite loops, and verify that a transformation is behaving as expected.

**Examples:**

### Example ID: 1138

**Description:** A simple cascading transformation (`A` -> `B` -> `C` -> `D`) shows the step-by-step output.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// RewindOnChange is necessary for cascading rules to be re-evaluated.
t.FromTo("A", "B").@RewindOnChange(true);
t.FromTo("B", "C").@RewindOnChange(true);
t.FromTo("C", "D").@RewindOnChange(true);

// Trace the transformation of "A"
var(uCalc::String, trace) = t.TraceTransform("A");

// Format the output list with ' -> ' for readability
trace.ListSeparator(" -> ");

wl(trace)
```

**Output:**
```
A -> B -> C -> D
```

---

### Example ID: 1139

**Description:** Practical: Traces the recursive expansion of a custom `MySum` function, showing how it is broken down into a standard arithmetic expression.

**Code:**
```pseudocode
var t = uc.@ExpressionTransformer();

// Assume these rules are pre-defined to create a recursive sum
t.FromTo("MySum({x})", "{x}");
t.FromTo("MySum({x}, {y})", "({x} + MySum({y}))").@RewindOnChange(true);

var(uCalc::String, trace) = t.TraceTransform("MySum(1,2,3,4)");
trace.ListSeparator([c]"\n"[/c][vb]vbCrLf[/vb]);

wl(trace)
```

**Output:**
```
MySum(1,2,3,4)
(1 + MySum(2,3,4))
(1 + (2 + MySum(3,4)))
(1 + (2 + (3 + MySum(4))))
(1 + (2 + (3 + 4)))
```

---

### Example ID: 1140

**Description:** Internal Test: Verifies advanced formatting of the trace output using `ListFormat` to create a custom, detailed step-by-step log.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("A", "B").@RewindOnChange(true);
t.FromTo("B", "C").@RewindOnChange(true);
t.FromTo("C", "D").@RewindOnChange(true);

var(uCalc::String, trace) = t.TraceTransform("A");

// Apply a custom format to each step in the list
trace.ListFormat("!", "(", ")", "$'{txt}->{n+1}/{c}'", "txt", "n", "c");

wl(trace)
```

**Output:**
```
(A->1/4!B->2/4!C->3/4!D->4/4)
```

---

---

## Transform - ID: 421
/doc/reference/classes/ucalc.transformer/transform/

---

## Transform() - ID: 422
/doc/reference/classes/ucalc.transformer/transform/transform-void/

**Description:** Applies all defined find-and-replace rules to the source text, modifying the transformer's internal text buffer.

**Syntax:** Transform()
**Return:** Transformer - Returns the current `Transformer` object, allowing for a fluent, chainable interface.
**Remarks:**

# ⚙️ Executing a Transformation

The `Transform()` method is the primary function for executing find-and-replace operations. It processes the text currently held by the [Transformer](/Reference/uCalcBase/Transformer/Constructor) against all active rules, updating the internal text buffer with the result.

### Transformation Workflow

A typical operation follows these steps:
1.  **Set Source Text**: Load the input string into the transformer, usually via the [Text](/Reference/uCalcBase/Transformer/Text) property (e.g., [pseudocode]`t.Text("input string");`).
2.  **Define Rules**: Add one or more rules using methods like [FromTo()](/Reference/uCalcBase/Transformer/FromTo), [Pattern()](/Reference/uCalcBase/Transformer/Pattern), and [SkipOver()](/Reference/uCalcBase/Transformer/SkipOver).
3.  **Execute Transform**: Call `Transform()`. The engine scans the text, applies the rules, and modifies its internal buffer.
4.  **Retrieve Result**: Get the modified string, typically by reading the [Text](/Reference/uCalcBase/Transformer/Text) property (e.g., [pseudocode]`var result = t.Text();`).

### In-Place Modification & Fluent Interface

`Transform()` modifies the transformer's internal state. The method also returns the `Transformer` object itself, allowing for a fluent, chainable syntax:

[pseudocode]`wl(t.Transform().Text());`

## 🆚 Comparative Analysis: `Transform()` vs. `Find()` vs. `Filter()`

It is crucial to choose the correct method for your task, as each serves a different purpose:

| Method                                               | Purpose                     | Result                                                                                               | Use Case                                                    |
| :--------------------------------------------------- | :-------------------------- | :--------------------------------------------------------------------------------------------------- | :---------------------------------------------------------- |
| **`Find()`**                                         | **Locate**                  | Populates the [Matches](/Reference/uCalcBase/Transformer/Matches) collection. **Does not modify text.**                | When you only need to know *if* and *where* patterns exist. |
| **[`Filter()`](/Reference/uCalcBase/Transformer/Filter)**      | **Extract & Transform**     | Creates a **new string** consisting only of the transformed results of each match, separated by newlines. | Extracting all log errors, URLs, or specific data points from a document into a clean list. |
| **`Transform()`** (This Method)                      | **Modify In-Place**         | Modifies the **original text**, replacing matches according to rules but preserving all other content.   | Performing a search-and-replace operation on a document.    |

## 💡 Why uCalc? `Transform()` vs. Regex

In many languages, `Regex.Replace` is the standard tool for find-and-replace. uCalc's `Transform()` offers significant advantages for structured text:

*   **Token-Awareness**: Regex is character-based and can easily fail on nested structures like `func(a, (b+c))` or make incorrect replacements inside string literals. `Transform()` operates on tokens, so it inherently understands and respects these boundaries by default.
*   **Stateful Engine**: A `Transformer` is a stateful object. It maintains a set of rules with a clear precedence order (last-in, first-out) and configurable properties (e.g., `CaseSensitive`). A regex is typically a stateless pattern.
*   **Embedded Logic**: `Transform()` leverages rules that can contain embedded logic like `{@Eval}` or conditionals, capabilities that would require complex callback functions with standard regex.

**Examples:**

### Example ID: 1141

**Description:** A simple find-and-replace transformation to replace all occurrences of a word.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Define a simple replacement rule
t.FromTo("Hello", "Greetings");

// Execute the transformation on an input string
t.@Text("Hello World, and Hello again.");
wl(t.Transform())
```

**Output:**
```
Greetings World, and Greetings again.
```

---

### Example ID: 1142

**Description:** A practical example sanitizing user input by removing script tags and normalizing excess whitespace in a single pass.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
// Rule 1: Remove script tags and their content (case-insensitive, multi-line)
t.FromTo("<script>{content}</script>", "");
t.@DefaultRuleSet().SetCaseSensitive(false).SetStatementSensitive(false);

// Rule 2: Normalize one or more whitespace characters to a single space
t.FromTo("{@Whitespace:ws}", " ");

// Transform the input in one go and print the result
t.@Text("  Welcome!  <SCRIPT>alert('bad');</SCRIPT>Please enjoy.  ");
wl("Sanitized: '", t.Transform(), "'")
```

**Output:**
```
Sanitized: ' Welcome! Please enjoy. '
```

---

### Example ID: 156

**Description:** Implicit Str(), Transform()

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("a", "XY");

t.@Text("a b c a b c");
wl(t.Transform().@Text()) // Text that was set before trasnform
wl(t.Transform("c b a c b a").@Text()) // text passed to Transform()
wl(t.Transform("a, b, a, b")) // Implicit; Text property can be omitted
```

**Output:**
```
XY b c XY b c
c b XY c b XY
XY, b, XY, b
```

---

### Example ID: 132

**Description:** ParentTransformer

**Code:**
```pseudocode
var Txt = "Test a b c. x y z";

var FirstTransform = uc.NewTransformer().SetText(Txt).SetDescription("First Transformer");
var aaa = FirstTransform.FromTo("Test {etc}.", "[{etc}]");

var SecondTransform = uc.NewTransformer().SetDescription("Second Transformer");
var bbb = SecondTransform.FromTo("Test {etc}.", "({etc})");

wl(aaa.@ParentTransformer().@Description())
wl(FirstTransform.Transform().@Text())
wl("")

wl(SecondTransform.@Description())
wl(bbb.@ParentTransformer().Transform(Txt).@Text())
```

**Output:**
```
First Transformer
[a b c] x y z

Second Transformer
(a b c) x y z
```

---

### Example ID: 137

**Description:** SkipOver(),  Str(), Implicit Str()

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "a b c (a b c a b c) a b c";
t.FromTo("a", "AA");

// You can either set the string before or pass it to Transform()
t.Str(txt);
wl(t.Transform().@Text())

t.SkipOver("({text})");
wl(t.Transform(txt)) // Implicit Text property
```

**Output:**
```
AA b c (AA b c AA b c) AA b c
AA b c (a b c a b c) AA b c
```

---

---

## Transform(string) - ID: 423
/doc/reference/classes/ucalc.transformer/transform/transform-string/

**Description:** Sets the source text and runs a find-and-replace operation in a single step, modifying the text according to the transformer's defined rules.

**Syntax:** Transform(string)
**Parameters:**
inputText - string - The source text string to be transformed.
**Return:** Transformer - Returns the current `Transformer` object, allowing for a fluent, chainable interface.
**Remarks:**

The `Transform(string)` method is a convenience overload that combines two operations into one: it first sets the transformer's internal source text to the provided string and then immediately executes the transformation process.

This is functionally equivalent to calling [`.Text = inputText`](/Reference/uCalcBase/Transformer/Text) followed by the parameterless [`.Transform()`](/Reference/uCalcBase/Transformer/Transform/Transform) method.

### ⚙️ The Transformation Process

When called, the method executes the full transformation pipeline:
1.  The `inputText` overwrites any text currently held by the transformer.
2.  The engine scans the text, finding all segments that match the defined rules ([`FromTo()`](/Reference/uCalcBase/Transformer/FromTo), [`Pattern()`](/Reference/uCalcBase/Transformer/Pattern)).
3.  Rule precedence is respected: [`SkipOver()`](/Reference/uCalcBase/Transformer/SkipOver) rules are evaluated first, followed by other rules in LIFO (Last-In, First-Out) order.
4.  Matched segments are replaced according to their replacement strings.
5.  The transformer's internal text is updated with the result, which can then be retrieved using the [`.Text`](/Reference/uCalcBase/Transformer/Text) property.

### `Transform(string)` vs. `Transform()`

| Method | Behavior | Use Case |
| :--- | :--- | :--- |
| `Transform(string)` | Sets the text *and* transforms it. | Ideal for stateless, one-off transformations where the `Transformer` object is primarily a container for rules. |
| `Transform()` | Transforms the text *already present* in the object. | Useful for multi-stage processing where you perform several distinct operations on the same text buffer. |

### `Transform` vs. `Find` vs. `Filter`

| Method | Effect on Text | Primary Purpose |
| :--- | :--- | :--- |
| **`Transform()`** | **Modifies in-place**. Replaces matches while preserving all other content. | Performing a search-and-replace on a document. |
| **[`Find()`](/Reference/uCalcBase/Transformer/Find)** | **None**. The text is not modified. | Locating patterns and populating the [Matches](/Reference/uCalcBase/Transformer/Matches) collection for analysis. |
| **[`Filter()`](/Reference/uCalcBase/Transformer/Filter)** | **Extracts**. Creates a new string consisting *only* of the transformed results. | Extracting all log errors, URLs, or specific data points into a clean list. |

### Fluent Interface

This method returns the current `Transformer` instance, allowing for a fluent, chainable syntax:

[pseudocode]`wl(t.Transform("input").Text());`

**Examples:**

### Example ID: 1144

**Description:** A simple find-and-replace transformation to replace all occurrences of a word.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
// Define a simple replacement rule
t.FromTo("Hello", "Greetings");

// Execute the transformation on an input string
wl(t.Transform("Hello World, and Hello again."))
End Using
```

**Output:**
```
Greetings World, and Greetings again.
```

---

### Example ID: 1145

**Description:** A practical example sanitizing user input by removing script tags and normalizing excess whitespace in a single pass.

**Code:**
```pseudocode
NewUsing(uCalc::Transformer, t)
// Rule 1: Remove script tags and their content (case-insensitive, multi-line)
t.FromTo("<script>{content}</script>", "");
t.@DefaultRuleSet().SetCaseSensitive(false).SetStatementSensitive(false);

// Rule 2: Normalize one or more whitespace characters to a single space
t.FromTo("{@Whitespace:ws}", " ");
        
var(string, userInput) = "  Welcome!  <SCRIPT>alert('bad');</SCRIPT>Please enjoy.  ";
        
// Transform the input in one go and print the result
wl("Sanitized: '", t.Transform(userInput), "'")
End Using
```

**Output:**
```
Sanitized: ' Welcome! Please enjoy. '
```

---

### Example ID: 156

**Description:** Implicit Str(), Transform()

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("a", "XY");

t.@Text("a b c a b c");
wl(t.Transform().@Text()) // Text that was set before trasnform
wl(t.Transform("c b a c b a").@Text()) // text passed to Transform()
wl(t.Transform("a, b, a, b")) // Implicit; Text property can be omitted
```

**Output:**
```
XY b c XY b c
c b XY c b XY
XY, b, XY, b
```

---

### Example ID: 152

**Description:** RewindOnChange

**Code:**
```pseudocode
var ExprT = uc.@ExpressionTransformer();  // Transformer used for Eval() and Evaluate()

ExprT.@DefaultRuleSet().@RewindOnChange(true);

ExprT.FromTo("AddUp({x})", "{x}");
ExprT.FromTo("AddUp({x}, {y})", "({x} + AddUp({y}))");

ExprT.FromTo("ArgCount({x})", "1");
ExprT.FromTo("ArgCount({x}, {y})", "(1 + ArgCount({y}))");

ExprT.FromTo("Average({x}, {y})", "AddUp({x}, {y}) / ArgCount({x}, {y})");

var Expression = "Average(1, 2, 3, 4)";
wl("Input: ", Expression)
wl("Transform: ", ExprT.Transform(Expression))
wl("Eval: ", uc.Eval(Expression))
```

**Output:**
```
Input: Average(1, 2, 3, 4)
Transform: (1 + (2 + (3 + 4))) / (1 + (1 + (1 + 1)))
Eval: 2.5
```

---

### Example ID: 132

**Description:** ParentTransformer

**Code:**
```pseudocode
var Txt = "Test a b c. x y z";

var FirstTransform = uc.NewTransformer().SetText(Txt).SetDescription("First Transformer");
var aaa = FirstTransform.FromTo("Test {etc}.", "[{etc}]");

var SecondTransform = uc.NewTransformer().SetDescription("Second Transformer");
var bbb = SecondTransform.FromTo("Test {etc}.", "({etc})");

wl(aaa.@ParentTransformer().@Description())
wl(FirstTransform.Transform().@Text())
wl("")

wl(SecondTransform.@Description())
wl(bbb.@ParentTransformer().Transform(Txt).@Text())
```

**Output:**
```
First Transformer
[a b c] x y z

Second Transformer
(a b c) x y z
```

---

### Example ID: 137

**Description:** SkipOver(),  Str(), Implicit Str()

**Code:**
```pseudocode
var t = uc.NewTransformer();
var txt = "a b c (a b c a b c) a b c";
t.FromTo("a", "AA");

// You can either set the string before or pass it to Transform()
t.Str(txt);
wl(t.Transform().@Text())

t.SkipOver("({text})");
wl(t.Transform(txt)) // Implicit Text property
```

**Output:**
```
AA b c (AA b c AA b c) AA b c
AA b c (a b c a b c) AA b c
```

---

### Example ID: 158

**Description:** Transformer.uCalc

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@uCalc().DefineVariable("xyz = 123");

t.FromTo("xyz", "{@Eval: xyz * 10}");
wl(t.Transform("The answer is: xyz"))
```

**Output:**
```
The answer is: 1230
```

---

---

## uCalc = [uCalc] - ID: 546
/doc/reference/classes/ucalc.transformer/ucalc-=-[ucalc]/

**Description:** Gets or sets the parent uCalc instance that provides the execution context for the transformer's rules and expressions.

**Remarks:**

Every [Transformer](/Reference/uCalcBase/Transformer/Constructor) object is intrinsically linked to a parent [uCalc](/Reference/uCalcBase/uCalc/Constructor) instance. This parent instance acts as its **execution context**, holding the complete set of variables, functions, and settings required to evaluate any expressions within its rules, such as those in an `{@Eval}` directive.

The `uCalc` property is a powerful feature that allows you to both retrieve and modify this context at runtime.

### ⚙️ Getter and Setter Behavior

*   **Getter**: When called without arguments, [pseudocode]`myTransformer.@uCalc()` retrieves the `uCalc` instance that currently owns the transformer. This is essential for introspection and for performing other operations within the same context (e.g., defining a variable that a rule will need).

*   **Setter**: When called with a `uCalc` instance as an argument, [pseudocode]`myTransformer.@uCalc(new_uc)` re-parents the transformer. From that point on, all its rules will be executed within the context of the new instance. This allows a single, complex transformer configuration to be applied to different data contexts.

### 🎯 Primary Use Cases

*   **Contextual Introspection**: Get a handle to the parent instance to query its state, such as its [Description](/Reference/uCalcBase/uCalc/Description) or defined [Items](/Reference/uCalcBase/uCalc/Items).
*   **Dynamic Re-scoping**: Create a generic set of transformation rules and then apply them to different `uCalc` instances, each with its own set of variables and functions. This is ideal for multi-tenant applications or for processing data against different configuration profiles.
*   **Shared Logic**: A single rule can access variables or functions from its parent context, allowing for tight integration between the transformation logic and the application's state.

### 💡 Comparative Analysis

In many programming environments, the context for an operation is immutable or passed as a parameter during execution. uCalc's model, where the execution context is a mutable property of the transformer itself, provides a unique level of flexibility.

*   **vs. Dependency Injection**: While DI frameworks inject dependencies at creation time, `Transformer.uCalc` allows the dependency (the execution context) to be hot-swapped at any point in the object's lifecycle. This is a form of dynamic, runtime dependency injection.

*   **vs. Global State**: Instead of relying on a single global `uCalc` instance, this property promotes better encapsulation. Each transformer can have its own private context, but that context can be changed programmatically, offering the benefits of isolation with the flexibility of dynamic redirection.

**Examples:**

### Example ID: 158

**Description:** Transformer.uCalc

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.@uCalc().DefineVariable("xyz = 123");

t.FromTo("xyz", "{@Eval: xyz * 10}");
wl(t.Transform("The answer is: xyz"))
```

**Output:**
```
The answer is: 1230
```

---

### Example ID: 160

**Description:** Changing the parent uCalc object for a Transformer

**Code:**
```pseudocode
uc.DefineVariable("x = 1");
uc.DefineVariable("y = 2");
uc.DefineFunction("f(x) = x * 10");

var t = uc.NewTransformer();
var text = "Adding {x} and {y} gives: {x + y}. f(5) = {f(5)}";

new(uCalc, uNew)
uNew.DefineVariable("x = 111");
uNew.DefineVariable("y = 222");
uNew.DefineFunction("f(x) = x * 1000");

// Note: {@@Eval: txt} is equivalent of {@Eval: Eval(txt)}
// which is what's needed for to evaluate the expression
// resulting from the match that is not known ahead of time
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");
wl(t.Transform(text))

t.@uCalc(uNew);
t.FromTo("'{' {expr} '}'", "{@@Eval: expr}");
wl(t.Transform(text))

```

**Output:**
```
Adding 1 and 2 gives: 3. f(5) = 50
Adding 111 and 222 gives: 333. f(5) = 5000
```

---

---

## WasModified = [bool] - ID: 426
/doc/reference/classes/ucalc.transformer/wasmodified-=-[bool]/

**Description:** Checks if the most recent transformation operation resulted in any changes to the text.

**Remarks:**

# ⚡️ Performance Optimization: The `WasModified` Property

The `@WasModified` property is a boolean flag that indicates whether the most recent transformation operation resulted in any changes to the source text. It is a crucial tool for optimizing applications by avoiding unnecessary work when no modifications have occurred.

## ⚙️ How It Works

After calling [Transform()](/Reference/uCalcBase/Transformer/Transform), [Filter()](/Reference/uCalcBase/Transformer/Filter), or even [Find()](/Reference/uCalcBase/Transformer/Find), this property will be `true` if any rule successfully replaced or altered the text. If no rules matched, or if all matching rules were find-only ([Pattern()](/Reference/uCalcBase/Transformer/Pattern)), the property will be `false`.

The state of this flag is reset with each new transformation call.

## 🎯 Primary Use Case: Avoiding Unnecessary Operations

Retrieving a large string from the transformer (e.g., via [@Text()](/Reference/uCalcBase/Transformer/Text)) involves a data copy. For multi-megabyte documents, this can be an expensive operation. `@WasModified` allows you to skip this copy, as well as any subsequent processing (like writing to a file, updating a UI, or logging), if the content is unchanged.

```pseudocode
// Perform the transformation
t.Transform();

// Only proceed if the text was actually changed
if (t.@WasModified())
    // Perform expensive operations here
    var newText = t.@Text();
    // SaveToFile(newText);
end if
```

## 💡 Why uCalc? (Comparative Analysis)

Without this built-in property, a developer would have to implement this check manually, which is inefficient and verbose.

**Typical Manual Approach:**
```pseudocode
// Store the original text
var originalText = t.@Text();

// Perform the transformation
t.Transform();

// Manually compare the strings to see if a change occurred
if (t.@Text() != originalText)
    wl("Text was modified.");
end if
```
This manual comparison is very inefficient, especially for large strings, as it requires the entire string to be scanned character by character.

`@WasModified` is superior because it relies on a simple internal flag that the transformer engine sets during its processing. Checking this boolean flag is an O(1) operation, providing an instantaneous result regardless of the text size. This makes it the ideal, high-performance solution for change detection in transformation pipelines.

**Examples:**

### Example ID: 1150

**Description:** Demonstrates the basic true/false state of the WasModified flag.

**Code:**
```pseudocode
New(uCalc::Transformer, t)
t.FromTo("a", "*a good*");

// Case 1: A match occurs, text is modified.
t.@Text("This is a test");
t.Transform();
wl("Modified: ", bool(t.@WasModified()))

// Case 2: No match occurs, text is unchanged.
t.@Text("This is another test");
t.Transform();
wl("Modified: ", bool(t.@WasModified()))
```

**Output:**
```
Modified: True
Modified: False
```

---

### Example ID: 1151

**Description:** Shows how to use WasModified to avoid an expensive operation, like saving to a file, if no changes were made during a data sanitization process.

**Code:**
```pseudocode
New(uCalc::Transformer, sanitizer)
sanitizer.FromTo("error", "ERROR");

// Simulate processing multiple logs
var(string, log1) = "status: ok";
var(string, log2) = "status: error";

wl("--- Processing Log 1 ---")
sanitizer.@Text(log1);
sanitizer.Transform();
if (sanitizer.@WasModified())
    wl("Change detected. Saving updated log...")
    // SaveToFile(sanitizer.GetText());
else
    wl("No changes. Skipping save.")
end if

wl("")
wl("--- Processing Log 2 ---")
sanitizer.@Text(log2);
sanitizer.Transform();
if (sanitizer.@WasModified())
    wl("Change detected. Saving updated log...")
    // SaveToFile(sanitizer.GetText());
    wl("Updated log: ", sanitizer.@Text())
else
    wl("No changes. Skipping save.")
end if
```

**Output:**
```
--- Processing Log 1 ---
No changes. Skipping save.

--- Processing Log 2 ---
Change detected. Saving updated log...
Updated log: status: ERROR
```

---

### Example ID: 159

**Description:** WasModified

**Code:**
```pseudocode
var t = uc.NewTransformer();
t.FromTo("a", "*a good*");

t.@Text("This is a test");
wl(t.Transform())
wl("Modified: ", bool(t.@WasModified()))
wl("")

t.@Text("This is another test");
wl(t.Transform())
wl("Modified: ", bool(t.@WasModified()))
```

**Output:**
```
This is *a good* test
Modified: True

This is another test
Modified: False
```

---

---

## What's New - ID: 1031
/doc/what's-new/

**Description:** Here's what's new in the uCalc SDK

**Remarks:**

# The Next Generation of uCalc: Smarter and Fully Documented

Welcome to the most significant update in uCalc's history. The uCalc SDK has been completely overhauled to provide advanced expression parsing and token-aware text transformation. Whether upgrading from a legacy version or discovering uCalc for the first time, this release introduces a modernized architecture, deep language integration (C++, C#, VB), and a brand-new, interactive learning experience.

## Stop reading. Start interacting.

The best way to learn an SDK is by using it. That is why a massive new documentation hub has been launched, featuring over 600 live, interactive examples. Test string manipulations, math parsing, and code transformations directly in the browser without writing a single line of setup code.

[Interactive Examples](/interactive-examples/)

## The Unified SDK Architecture

The uCalc SDK is now a unified toolkit featuring three core, seamlessly integrated components:

* [The Expression Parser](/fast-math-parser/): Mathematical and logical evaluation built upon the proven "Parse-Once, Evaluate-Many" architecture from previous versions. 

* [The Transformer](/transformer/): An intelligent, token-aware engine for complex find-and-replace operations (superior to standard RegEx).

* [The String Library](/string/): Robust data cleaning and manipulation.


## Ready to dive into the technical details?

Read the full [Release Notes & Changelog](/doc/release-notes/)

---

## Release Notes - ID: 1032
/doc/release-notes/

**Description:** changelog

**Remarks:**

This page contains the technical changelog for the uCalc SDK. For a high-level overview of major new features, please see [What's New](/doc/whats-new/).

**Upgrading from a legacy version?** Because of the massive architectural improvements made in recent years, the release notes is starting with a clean slate, instead of listing every change since old versions.

**%UCALC_SDK_VERSION%** July 23, 2026

### 🚀 Major Features & Additions

Major relaunch of uCalc with smarter functionality and extensive documentation, including 600+ interactive online examples, and AI assistant.

### 🛠️ Improvements & Refinements

### 🐛 Bug Fixes

### ⚠️ Deprecations & Breaking Changes




---

## License - ID: 1033
/doc/license/

**Description:** uCalc SDK End User License Agreement (EULA)

**Remarks:**

# uCalc SDK End User License Agreement (EULA)

Copyright (c) 2026 uCalc Software / Daniel Corbier

This License Agreement ("Agreement") governs the use of the uCalc software component ("Software"). By downloading, installing, or using the Software, you agree to the terms of this Agreement.

## 1. COMMUNITY LICENSE (FREE)

Subject to the terms and conditions of this Agreement, uCalc Software (Daniel Corbier) grants you a non-exclusive, non-transferable, royalty-free license to use, and integrate the Software for commercial and non-commercial purposes, strictly provided that you meet one of the following criteria:

Academic/Non-Profit: You are using the Software for academic research, education, or within a registered non-profit organization.

Indie Developer / Small Business: You are an individual developer or a business entity with annual gross revenues (or funding) of less than $100,000 USD (or local equivalent). This license allows the use of the uCalc SDK for internal and commercial projects, provided the revenue threshold is not exceeded.

## 2. ENTERPRISE COMMERCIAL USE (PAID LICENSE REQUIRED)

If you or your organization generates $100,000 USD or more in annual gross revenue, you are no longer eligible for the Community License. Any use of the Software in this capacity requires the purchase of a valid Commercial License.

A Commercial License must be purchased prior to deploying the Software in a production environment.

To purchase a Commercial License, please visit: www.uCalc.com/pricing.

### Perpetual Fallback and Updates

Commercial licenses include 12 months of updates and priority technical support. Upon expiration of the 12-month period, the Licensee retains a perpetual, non-exclusive right to continue using the specific major version of the software released during their active subscription.

## 3. BECOMING A SPONSOR OR SUPPORTER

By paying to become a sponsor or supporter, you are also purchasing a license for the uCalc SDK product.

## 4. PREVIEW STATUS AND PERFORMANCE (AS-IS)

The Software is currently provided as a "Preview Release." The Licensee acknowledges that the current version of the library (including the core engine and string manipulation components) is not fully optimized for execution speed or memory efficiency, and functionality may not always match what is documented or intended. The Software is provided "AS IS," without warranty of any kind, express or implied.

## 5. MARKETING AND LOGO USAGE

In order for your avatar, personal name, or company logo to be featured on the website's customer/sponsor roster, you must first opt in for this during checkout, or send an email with explicit consent for this afterwards. For a logo, you should submit a high resolution image.

## 6. CROSS-LANGUAGE AND PLATFORM USAGE

The Licensee is permitted to use the same uCalc SDK license to develop applications targeting supported programming languages, including C#, C++, and VB.NET across Windows, macOS, and Linux operating systems.

## 7. RESTRICTIONS

Whether using the Community or Commercial license, you may not:

Sell, rent, lease, or sub-license the Software as a standalone component.

Create a direct competitor product that exposes the uCalc API as its primary functionality.

Remove or alter any copyright notices or proprietary markings within the Software.

Reverse engineer the Software.


## 8. REFUND POLICY AND RIGHT OF WITHDRAWEL

The uCalc SDK provides a fully functional Free Community edition with no time limits, allowing users to thoroughly test the software for compatibility and feature fit prior to purchasing a commercial license.

Due to the immediate delivery license of digital goods, all sales are final. By completing a purchase, the Licensee expressly consents to the immediate provision of the digital license and acknowledges the waiver of any statutory right of withdrawal or refund (including the EU 14-day right of withdrawal).


## 9. DISCLAIMER OF WARRANTY

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

In no event shall uCalc be liable for any direct, indirect, incidental, or consequential damages arising out of the use or inability to use the Software.

---

## FAQ - ID: 668
/doc/faq/

---

## Common troubleshooting questions - ID: 697
/doc/faq/common-troubleshooting-questions/

**Remarks:**

For now, please submit your questions directly via the [contact page](/contact) until contents for the FAQ page are built.

---

