224 lines
5.9 KiB
Markdown
224 lines
5.9 KiB
Markdown
---
|
|
Title: 11 Advanced Topics
|
|
Prev: Generic Programming
|
|
Next: Standard Library
|
|
---
|
|
|
|
## 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 Testing and Assertions
|
|
|
|
The `assert` operator provides inline testing and verification.
|
|
|
|
**Syntax**: `{ expression } { condition } assert`
|
|
|
|
The assert operator evaluates the expression block, then evaluates the condition block. If the condition returns false (or a falsy value), the program halts with an assertion failure.
|
|
|
|
**Examples**:
|
|
```
|
|
// Simple assertion
|
|
{ 2 3 + } { 5 == } assert
|
|
|
|
// Testing a function
|
|
{ 5 square } { 25 == } assert
|
|
|
|
// Multiple assertions
|
|
{ 10 3 divmod } { 3 == swap 1 == and } assert
|
|
|
|
// Assertion with message (implementation-specific)
|
|
{ 2 3 + } { 5 == } "Addition should work" assert
|
|
```
|
|
|
|
**Use Cases**:
|
|
- Unit testing
|
|
- Invariant checking
|
|
- Contract programming
|
|
- Debugging
|
|
|
|
**Testing Framework (Future)**: A more comprehensive testing framework with `test` and `test_error` operators is planned for future versions. See [Appendix F](./memory_management.html) for details.
|
|
|
|
### 11.4 Reflection
|
|
|
|
Reflection operators provide runtime type and trait information for debugging and metaprogramming.
|
|
|
|
**type_of Operator**
|
|
|
|
**Syntax**: `value type_of`
|
|
**Signature**: `(Self -- Identifier)`
|
|
|
|
Returns the type of a value as an identifier literal.
|
|
|
|
**Examples**:
|
|
```
|
|
42 type_of // Pushes ::i64
|
|
"hello" type_of // Pushes ::String
|
|
3.14 type_of // Pushes ::f64
|
|
|
|
// Use with conditionals
|
|
value type_of ::i64 ==
|
|
{ "It's an integer" print }
|
|
{ "It's not an integer" print }
|
|
if
|
|
```
|
|
|
|
**implements Operator**
|
|
|
|
**Syntax**: `value ::TraitName implements`
|
|
**Signature**: `(Self Identifier -- bool)`
|
|
|
|
Checks if a value's type implements a specific trait.
|
|
|
|
**Examples**:
|
|
```
|
|
42 ::Addable implements // => true
|
|
42 ::Drawable implements // => false
|
|
|
|
"hello" ::String implements // => true
|
|
[1 2 3] ::Iterable implements // => true
|
|
|
|
// Use with conditionals
|
|
value ::Serializable implements
|
|
{ value serialize }
|
|
{ "Cannot serialize" print }
|
|
if
|
|
```
|
|
|
|
**Use Cases**:
|
|
- Runtime type checking
|
|
- Debugging and introspection
|
|
- Dynamic dispatch based on traits
|
|
- Building generic utilities
|
|
- Error messages with type information
|
|
|
|
**Examples**:
|
|
```
|
|
// Generic print function with type info
|
|
(Self -- ) {
|
|
dup type_of to_str "Type: " swap concat print
|
|
dup ::Stringifiable implements
|
|
{ to_str print }
|
|
{ drop "Cannot print this type" print }
|
|
if
|
|
} ::debug_print fn
|
|
|
|
// Trait-based dispatch
|
|
(Self -- ) {
|
|
dup ::Drawable implements
|
|
{ draw }
|
|
{ drop "Not drawable" print }
|
|
if
|
|
} ::try_draw fn
|
|
```
|
|
|
|
### 11.5 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
|
|
"hello world" "world" "Stack" replace // Replace substring
|
|
" hello " trim // Remove whitespace
|
|
"hello world" "world" find // Find substring position
|
|
"hello" "hel" starts_with // Check prefix
|
|
"hello" "llo" ends_with // Check suffix
|
|
"x=%d, y=%d" [5 10] format // Format string with values
|
|
```
|
|
|
|
**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`, `foldl`, `foldr`
|
|
- Utilities: `zip`, `enumerate`, `sum`, `mean`
|
|
- Manipulation: `concat`, `reverse`, `transpose`, `window`
|
|
|
|
> **Complete Reference**: See [Appendix A](./standard_library.html) for the full standard library reference with all functions, signatures, and examples.
|
|
|
|
---
|