strux_pr 0.8.8
strux_pr: ^0.8.8 copied to clipboard
Runtime annotations and deterministic structural precedence engine for pure-Dart rule dispatch.
strux_pr #
A deterministic structural precedence engine code generator for Dart (usable in Flutter applications).
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 strux_pr_generator plus build_runner
to your development dependencies.
dependencies:
strux_pr: ^0.8.8
dev_dependencies:
strux_pr_generator: ^0.8.8
build_runner: ^2.16.1
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.
Topological sort resolves declared relationships first. Declaration order is used as a deterministic tie-breaker among ready rules, so a rule that is unrelated to a delayed dependency may move before an earlier-declared rule. The engine never invents a precedence relationship that was not declared.
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.
- A
@PrecedenceEngineclass that is abstract. - A generic
@PrecedenceEngineclass. - A
@PrecedenceEngineclass with adispatchRulemember collision. - A
@PrecedenceEngineclass whose context type is not concrete. - Empty
Predicate.rawexpressions. - Invalid
Predicate.equalsfield paths or unsupported values.
Predicates #
Rules may include an optional when expression evaluated against activeContext:
@Rule(id: 'admin', when: Predicate.raw('activeContext == "admin"'))
String admin() => 'admin';
Supported when mechanisms are:
Predicate.rawPredicate.equalsPredicate.andPredicate.orPredicate.not
Supported Predicate.equals values are:
nullStringboolintdouble
Unknown value types fail generation. Empty raw expressions and invalid Predicate.equals field paths also fail generation.
Invalid reference example #
For example, this is invalid:
@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.
Structural graph helper #
Advanced callers can inspect a validated rule graph directly:
import 'package:strux_pr/strux_pr.dart';
final graph = buildPrecedenceGraph(analyzePrecedenceEngine(rules));
PrecedenceGraph is immutable, uses identity equality, and is structural graph data rather than validation behavior. It assumes its input already passed analyzePrecedenceEngine; unknown explicit targets are intentionally absent from its edge sets.
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 NoMatchingRuleException, a StateError subtype.
Example #
A complete example is available in:
example/main.dart
Run it with:
dart run example/main.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 -> NoMatchingRuleException: 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.
Intervals are inclusive on both ends, so ranges that merely touch also overlap.
Identical intervals always require an explicit subscope or overrideTarget edge.
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.
API stability #
This package is at version 0.8.x. Public APIs, helper exports, diagnostics, exception names, and interval behavior are subject to change before a 1.0 release. Deprecated compatibility aliases remain for one 0.x release cycle.
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
Security and trust boundaries #
Predicate.rawis Dart source code, not runtime data.strict_overlapdefaults tofalse.- Verification artifacts are disabled by default.
- Generated dispatchers throw
NoMatchingRuleException, aStateErrorsubtype, when no rule matches.
License #
MIT