Attributes
An attribute is a tag on a field, function, or object: #[name], or #[name(value)] with a value. You've already used some, like #[main] and #[type]. Attributes are data, so a document can read them while it runs, and so can your app.
Built-In Attributes
Stof gives these a meaning:
| Attribute | On | Meaning |
|---|---|---|
#[main] | function | Runs when the document is run (stof run, doc.run()) |
#[test], #[test(value)], #[errors] | function | A test, run by stof test. See Testing |
#[run], #[run(order)] | function, field | A step run by obj.run(). See Object Run |
#[init] | function | Runs once, right after the document is parsed |
#[async] | function | The function is async (same as async fn). See Async |
#[type], #[extends('Name')] | object | A type, and the type it builds on. See Prototypes & Schemas |
#[constructor], #[dropped], #[static] | function in a type | Runs on new, runs when an instance is dropped, called on the type |
#[schema(...)], #[schema_optional] | field in a type | A validation rule |
#[readonly], #[private] | field | Can't be assigned; visible only to its own object |
#[no-export] | field | Left out of exports like JSON and HTML |
#[tag('name')], #[attr], #[text] | field, function, object | How an object is written as HTML or XML: the element's name, an attribute, text inside it. See Formats |
Any other name is yours to use.
Your Own Attributes
An attribute's value can be any value: a string, a number, a map, a function. That makes attributes a place to keep metadata next to what it describes:
#[unit('requests')]
#[range((0, 1000))]
calls: 120
#[main]
fn main() {
const attrs = self.attributes('calls');
const (low, high) = attrs.get('range');
pln(`${self.calls} ${attrs.get('unit')}, allowed ${low} to ${high}`);
}self.attributes('name') gives a field's or function's attributes as a map. Inside a function, this.attributes() gives its own.
Finding Functions by Attribute
self.funcs('name') lists the functions on an object that have an attribute, and funcs(attributes = 'name') lists them across the whole document, in the order they're written. That turns an attribute into an event or a plugin point: anything tagged joins in, with nothing else to register:
order: { total: 120 }
#[on_order]
fn add_tax(order: obj) {
order.tax = order.total * 0.2;
}
#[on_order]
fn flag_large(order: obj) {
order.large = order.total > 100;
}
#[main]
fn main() {
for (const handler in funcs(attributes = 'on_order')) {
handler(self.order);
}
pln(stringify('json', self.order));
}Add another #[on_order] function anywhere in the document, from any file or at runtime, and it runs too.
Changing Attributes
Attributes can change while a document runs. set_attribute adds one (or replaces its value) and remove_attribute takes one away, on an object, or on the field, function, or object at a path, and the change counts right away: funcs(attributes = ..) sees it, doc.run(..) runs by it, #[readonly] and #[private] enforce it, and exports write it. A function value has the same two methods:
order: { total: 120 }
#[on_order]
fn add_tax(order: obj) { order.tax = order.total * 0.2; }
fn add_discount(order: obj) { order.discount = 10; }
#[main]
fn main() {
// turn one handler off and another on
self.remove_attribute('on_order', 'add_tax');
(self.add_discount).set_attribute('on_order');
for (const handler in funcs(attributes = 'on_order')) handler(self.order);
pln(stringify('json', self.order));
// lock a field
self.order.set_attribute('readonly', null, 'total');
try self.order.total = 0;
catch (e, message) pln(message);
}A value of null is an attribute with no value, like #[flag]. #[type] and #[init] do their work when a document is parsed, so setting them later doesn't make a type or run anything. On a sealed object, attributes never change, even when its fields may.
The Agreement with Your App
The same idea is how an app runs logic it didn't write. The app runs functions by attribute, doc.run('on_order'), and the document can have any number of them, with any names:
- TypeScript
- Python
- Rust
// whatever the model wrote, like:
// #[on_order]
// fn add_tax() { self.order.tax = self.order.total * 0.2; }
const doc = await StofDoc.new(rulesFromAModel);
doc.parse({ order: { total: 120 } });
await doc.run('on_order'); // every #[on_order] function
doc.get('order.tax'); // 24
# whatever the model wrote, like:
# #[on_order]
# fn add_tax() { self.order.tax = self.order.total * 0.2; }
doc = Doc()
doc.parse(rules_from_a_model)
doc.string_import('{"order": {"total": 120}}', 'json')
doc.run('on_order') # every #[on_order] function
doc.get('order.tax') # 24.0
// whatever the model wrote, like:
// #[on_order]
// fn add_tax() { self.order.tax = self.order.total * 0.2; }
let mut graph = Graph::default();
graph.parse_stof_src(rules_from_a_model, None, Default::default())?;
graph.string_import("json", r#"{"order": {"total": 120}}"#, None, &Default::default())?;
let attributes: stof::rustc_hash::FxHashSet<String> = ["on_order".to_string()].into_iter().collect();
Runtime::run_attribute_functions(&mut graph, None, &Some(attributes), true) // every #[on_order] function
.expect("an #[on_order] function failed");
graph.field_value("order.tax", graph.main_root()); // Some(24.0)
The attribute is the only thing the app and the document have to agree on. See Using Stof in Your App. Next, Object Run.