Reflection
functions and helpers for retrieving runtime information about different objects, components, or types
Functions
Predicates
The Reflection module provides tools for runtime introspection and program analysis. From inspecting variables to benchmarking code, it offers comprehensive capabilities for understanding and analyzing your program's behavior.
Key Concepts
- Runtime information retrieval
- Symbol and attribute inspection
- Performance measurement
- Stack examination
Basic Usage
Inspecting Values
value: [1 2 #[name: "John"] [nested block]]
; detailed inspection
inspect value ; shows full structure with types
; get information about function/symbol
info 'print ; shows details about 'print function
info.get 'print ; returns info as dictionary
; get current stack
print stack ; shows current value stack (as a block)
Working with Attributes
doSth function [x][
; check if attribute exists
if attr? 'verbose ->
print "verbose mode on"
; get attribute value
level: attr 'level ; returns null if not set
; get all attributes
options: attrs ; returns dictionary of all set attributes
]
Symbol Management
; get all defined symbols
syms: symbols ; returns dictionary of all symbols
; check if symbol exists
print set? 'x ; true if 'x is defined
; get function arity
funcs: arity ; get dictionary of function arities
print arity\add ; 2 (which is the number of parameters `add` takes ;-))
Performance Measurement
; basic benchmarking
benchmark [
loop 1..1000 'x [
; some operation
]
]
; with the .get attribute
elapsed: benchmark.get [
; some operation
]
print ["Operation took:" elapsed]
; multiple runs for better accuracy
total: 0
loop 1..100 'run [
'total ++ benchmark.get [
; operation to measure
]
]
average: total / 100
Common Patterns
Function Analysis
; get complete function information
analyzeFunction: function [funcName][
info: info.get funcName
print ["Function:" funcName]
print ["Type:" info\type]
print ["Arguments:" info\args]
print ["Returns:" info\returns]
if key? info 'options [
print ["Options:" info\options]
]
]
analyzeFunction 'split
; Function: split
; Type: :function
; Arguments: [collection:[:string :literal :pathliteral :block]]
; Returns: [:block :nothing]
Performance Profiling
; simple profiling helper
profile: function [label operation][
print ["Profiling:" label]
; multiple runs for stability
times: []
loop 1..10 'run [
'times ++ to :floating benchmark.get operation
]
; calculate statistics
avg: average times
dev: deviation times
print ["Average:" avg "±" dev "seconds"]
]
; usage example
profile "array sorting" [
sort [5 3 8 1 9 2 7 4 6 0]
]
Tip
When benchmarking, always run multiple iterations to get stable results and consider system load variations.
Runtime Information
; check execution context
if standalone? [
; very useful in the case of "importable" modules/packages
; or when you want to inject some tiny bit of testing code, etc...
print "Running as standalone script"
]