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 subscope and overrideTarget.
  • 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_runner and source_gen.

Installation

Add strux_pr to your dependencies and strux_pr_generator plus build_runner to your development dependencies.

dependencies:
  strux_pr: ^0.8.12

dev_dependencies:
  strux_pr_generator: ^0.8.12
  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:

  • subscope
  • overrideTarget

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 subscope references.
  • Unknown overrideTarget references.
  • A rule using itself as its subscope.
  • A rule using itself as its overrideTarget.
  • Circular precedence dependencies.
  • An engine containing no @Rule methods.
  • A @PrecedenceEngine class that does not implement PrecedenceRuleContainer<TContext>.
  • Rule methods that accept more than one parameter.
  • Rule methods with a parameter whose type does not match the engine context.
  • Supported: static rule methods with zero or one matching-context parameter and a compatible non-void, non-Future return type.
  • Supported: abstract rule methods on abstract engine classes when a concrete runtime implementation supplies them.
  • Getter, setter, and operator rule methods.
  • void-returning rule methods.
  • Future-returning rule methods.
  • Empty or whitespace-only rule IDs.
  • A generic @PrecedenceEngine class.
  • A @PrecedenceEngine class with a dispatchRule member collision.
  • A @PrecedenceEngine class whose context type is not concrete.
  • Empty Predicate.raw expressions.
  • Invalid Predicate.equals field 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.raw
  • Predicate.equals
  • Predicate.and
  • Predicate.or
  • Predicate.not

Supported Predicate.equals values are:

  • null
  • String
  • bool
  • int
  • double

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, which implements Exception. A deprecated StateError compatibility alias is retained for one 0.x release cycle.

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-void value.
  • 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.5.0 at runtime. The workspace and generator require newer SDK versions because of build and analyzer; see the repository root for the effective compiled-development floor.
  • Coverage policy: runtime handwritten source targets at least 90% line coverage, with critical behavior branches covered by named scenarios.
  • Dependency review is a manual release gate because this SDK does not expose dart pub audit.

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.raw is Dart source code, not runtime data.
  • strict_overlap defaults to false.
  • Verification artifacts are disabled by default.
  • Generated dispatchers throw NoMatchingRuleException, which implements Exception, when no rule matches. A deprecated StateError compatibility alias is retained for one 0.x release cycle.

License

MIT

Libraries

strux_pr
Runtime annotations and the shared precedence analysis helper for strux_pr.