strux_pr 0.8.0
strux_pr: ^0.8.0 copied to clipboard
Structural precedence engine runtime and annotations.
strux_pr #
A deterministic structural precedence engine code generator for Dart and Flutter.
strux_pr resolves rule precedence at build time using a directed acyclic graph (DAG), then generates a deterministic dispatcher for your rule container.
Features #
- Compile-time precedence resolution.
- Explicit rule relationships using
subscopeandoverrideTarget. - Circular dependency detection.
- Duplicate rule ID detection.
- Validation of rule references.
- Validation of rule methods.
- Deterministic declaration ordering for unrelated rules.
- Generated dispatch code with no runtime graph traversal.
- Support for rule IDs containing quotes, backslashes, newlines, and Unicode.
- Compatible with Dart
build_runnerandsource_gen.
Installation #
Add strux_pr to your dependencies and build_runner to your development dependencies.
dependencies:
strux_pr: ^0.8.0
Usage #
Annotate a class with @PrecedenceEngine() and implement PrecedenceRuleContainer<TContext>.
Annotate executable rule methods with @Rule().
import 'package:strux_pr/strux_pr.dart';
part 'my_engine.g.dart';
@PrecedenceEngine()
class RulesContainer implements PrecedenceRuleContainer<String> {
@Rule(id: 'base')
String executeBase() => 'BASE';
@Rule(
id: 'specific',
subscope: 'base',
)
String executeSpecific() => 'SPECIFIC';
@Rule(
id: 'emergency',
overrideTarget: 'specific',
)
String executeEmergency() => 'EMERGENCY';
@override
bool canExecuteRule(String ruleId, String context) {
switch (ruleId) {
case 'emergency':
return context == 'EMERGENCY';
case 'specific':
return context == 'SPECIFIC';
case 'base':
return context == 'NORMAL';
default:
return false;
}
}
}
Run the generator with:
dart run build_runner build
The generated part provides:
final result = engine.dispatchRule(context);
The dispatcher evaluates rules in the precedence order determined at build time.
Precedence #
A rule can reference another rule using either:
subscopeoverrideTarget
For example:
@Rule(id: 'base')
String base() => 'base';
@Rule(
id: 'specific',
subscope: 'base',
)
String specific() => 'specific';
@Rule(
id: 'emergency',
overrideTarget: 'specific',
)
String emergency() => 'emergency';
The relationships form a precedence graph:
emergency
|
v
specific
|
v
base
Rules with explicit precedence relationships are ordered according to the dependency graph.
Rules that are unrelated by explicit precedence relationships retain their declaration order. This provides deterministic output without inventing precedence relationships that were not specified by the user.
Rule validation #
The generator validates the rule graph and rule declarations during code generation.
Generation fails for invalid configurations such as:
- Duplicate rule IDs.
- Unknown
subscopereferences. - Unknown
overrideTargetreferences. - A rule using itself as its
subscope. - A rule using itself as its
overrideTarget. - Circular precedence dependencies.
- An engine containing no
@Rulemethods. - A
@PrecedenceEngineclass that does not implementPrecedenceRuleContainer<TContext>. - Rule methods that accept parameters.
- Static rule methods.
- Abstract rule methods.
- Getter, setter, and operator rule methods.
void-returning rule methods.Future-returning rule methods.- Empty or whitespace-only rule IDs.
Predicates #
Rules may include an optional when expression evaluated against activeContext:
@Rule(id: 'admin', when: Predicate.raw('activeContext == "admin"'))
String admin() => 'admin';
For example, this is invalid:
```dart
@Rule(
id: 'specific',
subscope: 'does_not_exist',
)
String specific() => 'specific';
The generator reports the invalid reference during the build instead of allowing an invalid precedence graph to reach runtime.
Rule methods #
Rule methods are invoked by the generated dispatcher and therefore must be instance methods with no parameters.
Valid:
@Rule(id: 'payment')
String processPayment() => 'payment';
Invalid:
@Rule(id: 'payment')
String processPayment(String value) => value;
Invalid:
@Rule(id: 'payment')
static String processPayment() => 'payment';
Invalid:
@Rule(id: 'payment')
String processPayment();
Rule IDs #
Rule IDs are strings and may contain characters that require escaping in generated Dart source, including:
@Rule(id: 'user "admin"')
String quoted() => 'quoted';
@Rule(id: r'path\to\rule')
String pathRule() => 'path';
@Rule(id: 'line\nbreak')
String newlineRule() => 'newline';
@Rule(id: '支付_规则_🚀')
String unicodeRule() => 'unicode';
The generator escapes rule IDs when emitting generated Dart code.
Runtime contract #
PrecedenceRuleContainer<TContext> provides the runtime precondition check:
abstract class PrecedenceRuleContainer<TContext> {
bool canExecuteRule(String ruleId, TContext context);
}
The generated dispatcher calls canExecuteRule() for each rule in the resolved precedence order.
For example:
@override
bool canExecuteRule(String ruleId, String context) {
switch (ruleId) {
case 'emergency':
return context == 'EMERGENCY';
case 'specific':
return context == 'SPECIFIC';
case 'base':
return context == 'NORMAL';
default:
return false;
}
}
If no rule matches the supplied context, the generated dispatcher throws a StateError.
Example #
A complete example is available in:
example/strux_pr_example.dart
Run it with:
dart run example/strux_pr_example.dart
Example output:
Context: NORMAL -> Processed Standard Card Payment
Context: EXCEEDS_LIMIT -> Payment Denied: Exceeds allowed limit
Context: SYSTEM_EMERGENCY -> Emergency Stop: All transactions suspended
Context: UNSUPPORTED_CONTEXT -> Bad state: No deterministic rule matched the given context.
Verification artifacts #
When enabled, the artifact builder emits a .strux_pr.json file through the build cache/output path associated with the input. It is controlled by strux_pr_generator:strux_pr_artifact_builder, not by the main builder.
{
"source": "test/a.dart",
"generated_by": "strux_pr",
"engines": [
{
"engine": "E",
"order": ["r"],
"rules": [{"id": "r", "methodName": "r", "subscope": null, "overrideTarget": null, "when": null}],
"edges": []
}
]
}
Enable via build.yaml:
targets:
$default:
builders:
strux_pr_generator:strux_pr_artifact_builder:
enabled: true
options:
emit_verification_artifacts: true
Overlap checking #
Rules with no precedence path between them are reported as potential overlaps.
Enable strict mode in build.yaml:
targets:
$default:
builders:
strux_pr_generator:strux_pr_builder:
options:
strict_overlap: true
In strict mode, generation fails when overlapping pairs are detected.
Interval specificity #
Rules may declare an interval scope:
@Rule(id: 'outer', scopeStart: 0, scopeEnd: 10)
String outer() => 'outer';
@Rule(id: 'inner', scopeStart: 2, scopeEnd: 5)
String inner() => 'inner';
If one interval is contained in another, the inner rule is evaluated first.
Overlapping intervals without containment require explicit subscope/overrideTarget edges (fail-closed).
Benchmarks #
A reproducible benchmark scaffold is available in benchmark/. Run:
dart run benchmark/run_generation.dart
No performance numbers are published yet; the scaffold is for reproducible measurement.
Known limitations #
- The dispatcher is generated at build time; it is not suitable for runtime-loaded or dynamically modified rule graphs.
- Rule methods cannot be parameterized, asynchronous, mixin-provided, or superclass-provided.
- Only methods declared directly in the annotated class are scanned; rules defined via mixins or superclasses are not included.
- Rule methods must return a non-
voidvalue. - Rule methods should have compatible return types; otherwise generation fails.
Requirements #
- Dart SDK >=3.11.0
Testing #
Run the package checks with:
dart format lib test
dart analyze
dart test
To regenerate source files:
dart run build_runner clean
dart run build_runner build
License #
MIT