YREA-SLS/docs/advanced_topics.md

108 lines
3.0 KiB
Markdown

## 11. Advanced Topics
### 11.1 Dynamic Code Evaluation
The `eval` operator executes code dynamically at runtime by parsing and executing a TokenString.
**Syntax**: `{ code } eval`
**Examples**:
```
// Evaluate simple expression
"2 3 +" eval // Pushes 5
// Build and execute code
"(Multiplyable -- Multiplyable) { dup * } ::square fn" eval
5 square // 25
// Dynamic dispatch
operation_name " get" concat eval
```
**Use Cases**:
- Building code at runtime
- Dynamic dispatch based on runtime values
- Implementing interpreters or REPLs
- Meta-programming
**Warnings**:
- Eval introduces runtime overhead (parsing)
- Type safety is reduced (types checked at eval time, not compile time)
- Security risk if evaluating untrusted code
- Use sparingly and prefer static alternatives when possible
### 11.2 Identifier Literals
Identifier literals use the `::` prefix to push an identifier as a value rather than executing it.
**Syntax**: `::name`
**Context-Dependent Rules**:
**In function bodies and eval**: `::` is required for identifier literals
```
::Point // Pushes identifier "Point"
::Addable // Pushes identifier "Addable"
```
**In trait definitions**: `::` is not allowed (identifiers are method names)
```
{
(Self -- ) draw: // "draw:" is a method name, not a literal
} ::Drawable trait
```
**In trait implementations**: `::` is not allowed (identifiers are method names)
```
::Drawable {
(Self -- ) { ... } draw: // "draw:" is a method name
} ::Rectangle impl
```
**Use Cases**:
- Defining structs: `(T T --) { x: y: } ::Point<T> struct`
- Defining traits: `{ ... } ::Drawable trait`
- Field access: `point ::x get`
- Dynamic trait operations
- Meta-programming
### 11.3 Standard Library
The standard library provides I/O, string operations, type conversions, and utility functions. All standard library functions are automatically in scope (no imports needed in current version).
**I/O Operations**:
```
"Hello" print // Print string to stdout
"Enter name: " input // Read line from stdin
"file.txt" read // Read file contents as string
"data" "file.txt" write // Write string to file
```
**String Operations**:
```
"hello" " world" concat // Concatenate strings
"hello" length // Get string length
"hello" 1 3 substr // Extract substring
"a,b,c" "," split // Split by delimiter
["a" "b"] "," join // Join with delimiter
```
**Type Conversion**:
```
42 to_f64 // Convert i32 to f64
3.14 to_i32 // Convert f64 to i32 (truncates)
"123" parse // Parse string to inferred type
42 to_str // Convert to string
```
**Array Operations**:
- Element access: `at`, `slice`
- Information: `length`, `shape`
- Combinators: `map`, `filter`, `reduce`, `each`
- Manipulation: `concat`, `reverse`, `transpose`, `window`
> **Complete Reference**: See Appendix A for the full standard library reference with all functions, signatures, and examples.
---