Skip to main content

Developer Resource Center

Blueprint grammar

The formal grammar for writing a Blueprint by hand, with a download of the full text.

Developer Resource Center

This is the formal grammar for a Blueprint written in ThriveScript. It lists every section, every attribute and every allowed value in EBNF, a standard notation for describing a language.

Use it when you want an exact answer to β€œis this allowed?” or when you are building a tool that reads or checks ThriveScript files. If you want to learn how to write a Blueprint, start with the ThriveScript guide instead. It explains each section in plain terms with examples.

How to read the grammar

  • Text in quotes is written exactly as shown, for example "simulation_count".
  • Square brackets [ ... ] mean the part is optional.
  • Curly braces { ... } mean the part can repeat. A trailing + means at least once.
  • A vertical bar | separates choices.
  • Text between (* and *) is a comment.

A ThriveScript file is plain text. Indentation shows how the parts nest. All values are plain numbers, true or false, or text.

Top-level sections

A Blueprint has ten top-level sections. Seven are required. portfolio_scope, transfer_strategies and transfer_rules are optional. cash_flows is required but can be an empty list.

Download

You can download the grammar as a text file to use in your own tools.

Full grammar

The complete grammar is also available as a plain text file.

Download the grammar (blueprint-grammar.ebnf.txt)

(* ============================================================ *)
(* Blueprint Grammar -- EBNF                                    *)
(* ============================================================ *)
(* Formal grammar for a Blueprint document: a plain text file with *)
(* named accounts, strategies, transfer rules and bracket       *)
(* notation variables.                                          *)
(* Suitable for implementing a recursive descent parser.        *)
(* All terminals are plain scalar values unless noted otherwise.*)
(* ============================================================ *)
(* ------------------------------------------------------------ *)
(* Top-Level Document                                           *)
(* ------------------------------------------------------------ *)
(* 7 required sections + 3 optional (portfolio_scope,          *)
(* transfer_strategies, transfer_rules). cash_flows is required *)
(* but may be an empty list.                                    *)

Document
    = JobSection
      CustomVariablesSection
      RetireeProfileSection
      StrategiesSection
      AccountsSection
      [ PortfolioScopeSection ]
      CashFlowsSection
      [ TransferStrategiesSection ]
      [ TransferRulesSection ]
      WithdrawalRulesSection
    ;

(* ------------------------------------------------------------ *)
(* 1. Job Section                                               *)
(* ------------------------------------------------------------ *)
(* return_timing lives directly on job (no nested strategy      *)
(* block). Rebalancing is implicit -- each account grows at its *)
(* strategy's weighted rate with no drift tracking.             *)
(* variance_seed (optional) pins the RNG used for range-form    *)
(* return_variance/inflation_variance draws. Determinism:       *)
(*   - present  -> range draws reproducible, independent of     *)
(*                 job.seed (changing job.seed leaves the        *)
(*                 variance draw sequence unchanged).            *)
(*   - absent + job.seed present -> range draws derived          *)
(*                 deterministically from job.seed.              *)
(*   - both absent -> range draws are non-deterministic.        *)

JobSection
    = "job" ":"
        "simulation_count" ":" PositiveInteger          (* 1-10,000 *)
        "time_horizon"     ":" PositiveInteger          (* 1-100 *)
        AssetClassesBlock
        "return_timing"    ":" ReturnTiming
        [ "follow_on_years"    ":" PositiveInteger ]    (* default: 4 *)
        [ "seed"               ":" ( SeedInteger | Null ) ] (* default: null; 0..2^32-1 *)
        [ "variance_seed"      ":" ( SeedInteger | Null ) ] (* default: null; 0..2^32-1 *)
        [ "start_dates"        ":" StartDatesList ]
        [ "include_date_range" ":" IncludeDateRange ]
        [ "exclude_dates"      ":" ExcludeDatesList ]
        [ "debug"              ":" Boolean ]            (* default: false *)
    ;

(* 1a. Asset Classes *)
AssetClassesBlock
    = "asset_classes" ":"
        { AssetClassEntry }+
    ;

AssetClassEntry
    = Identifier ":"                                    (* user-defined name *)
        "return_source" ":" ReturnSource
        [ ProjectionBlock ]                             (* required if resolved source = "linear" *)
        [ "aum_fee" ":" AumFee ]                        (* default: 0.0 *)
        [ "return_variance"    ":" VarianceModifier ]   (* default: none (no-op) *)
        [ "inflation_variance" ":" VarianceModifier ]   (* default: none (no-op) *)
    ;

(* return_source is either a builtin generator OR the name of    *)
(* another asset class (aliasing). An alias reuses the           *)
(* referenced class's base return/inflation/dividend series but  *)
(* carries its OWN aum_fee and variance modifiers (never         *)
(* inherited). The referenced name must resolve, through the     *)
(* alias chain, to a class with a builtin return_source. Unknown *)
(* references and alias cycles are rejected at parse time.       *)
ReturnSource
    = "monte_carlo"
    | "historical"
    | "linear"
    | "parametric"                                      (* draws from a fitted distribution; see note *)
    | Identifier                                        (* alias: another asset-class name *)
    ;

(* parametric: an asset class with return_source "parametric"    *)
(* has its per-year return/inflation/dividend_yield DRAWN from    *)
(* fitted statistical parameters (preset-driven, auto-calibrated) *)
(* instead of historical replay. It takes an optional per-asset   *)
(* `parametric` block (preset, expected_return, volatility,       *)
(* mean_type, distribution, dividend_yield) and a job-level       *)
(* `parametric` block (volatility_lever, inflation_mean,          *)
(* inflation_volatility, correlations). See the Blueprint guide.  *)
ProjectionBlock
    = "projection" ":"
        "annual_return"    ":" Decimal
        "annual_inflation" ":" Decimal
        "dividend_yield"   ":" Decimal
        "volatility"       ":" NonNegativeDecimal       (* 0 = deterministic *)
    ;

(* 1d. AUM Management Fee *)
(* Annual management fee as a decimal fraction, subtracted from  *)
(* the asset class's weighted return where returns are applied   *)
(* (net_return = weighted_return - fee). Respects return_timing  *)
(* automatically. Attaches ONLY to asset classes, never to       *)
(* accounts.                                                     *)
AumFee
    = /0(\.[0-9]+)?/ | /1(\.0+)?/                        (* 0.0 <= fee <= 1.0 *)
    ;

(* 1e. Variance Modifier (return_variance / inflation_variance)  *)
(* An ADDITIVE percentage-point adjustment to the base rate      *)
(* (effective = base + modifier). Two forms: a flat value        *)
(* applied every active cycle year, or a [min, max] range        *)
(* redrawn uniformly each active cycle year and snapped to the   *)
(* nearest basis point (0.0001). Optional from_year/to_year      *)
(* bound the active window in CYCLE years (1-based; see below).  *)
VarianceModifier
    = FlatModifier
    | RangeModifier
    ;

(* Flat form: single value, applied every active cycle year.     *)
FlatModifier
    = "value"       ":" ModifierValue                   (* -100.0 <= value <= 100.0 *)
      [ "from_year" ":" CycleYear ]                     (* default: 1 *)
      [ "to_year"   ":" ( CycleYear | Null ) ]          (* default: through final year *)
    ;

(* Range form: [min, max], redrawn each active cycle year,       *)
(* min <= max, both in [-100.0, 100.0].                          *)
RangeModifier
    = "range"       ":" "[" ModifierValue "," ModifierValue "]"
      [ "from_year" ":" CycleYear ]                     (* default: 1 *)
      [ "to_year"   ":" ( CycleYear | Null ) ]          (* default: through final year *)
    ;

ModifierValue
    = Number                                            (* -100.0 <= value <= 100.0 *)
    ;

(* Cycle year: 1-based counter matching the simulator's per-year    *)
(* cycle index. DISTINCT from cash-flow start_year/end_year,     *)
(* which are calendar years. A modifier is active when           *)
(* from_year <= cycle_year AND (to_year is null OR               *)
(* cycle_year <= to_year); inactive years contribute 0.0.        *)
CycleYear
    = PositiveInteger                                   (* >= 1; to_year >= from_year *)
    ;

(* 1b. Return Timing *)
ReturnTiming
    = "beginning_of_year"
    | "end_of_year"
    ;

(* 1c. Date Filtering *)
StartDatesList
    = "[" Year { "," Year }* "]"
    ;

IncludeDateRange
    = "{" "start_year" ":" Year "," "end_year" ":" Year "}"
    ;

ExcludeDatesList
    = "[" ExcludeDatesEntry { "," ExcludeDatesEntry }* "]"
    ;

ExcludeDatesEntry
    = "{" "start_year" ":" Year "," "end_year" ":" Year "}"
    ;

(* ------------------------------------------------------------ *)
(* 2. Custom Variables Section                                  *)
(* ------------------------------------------------------------ *)
CustomVariablesSection
    = "custom_variables" ":"
        [ "static"  ":" { StaticVariable }+ ]
        [ "dynamic" ":" { DynamicVariable }+ ]
    ;

(* Static variables can be scalars, person-age references,
   or computed values using formula/steps syntax *)
StaticVariable
    = Identifier ":" StaticValue
    ;

StaticValue
    = ScalarValue                                       (* number, boolean, or string *)
    | PersonAge                                         (* { person: "Name", age: N } *)
    | SimpleFormula                                     (* { formula: [...] } *)
    | MultiStepFormula                                  (* { steps: { ... } } *)
    ;

PersonAge
    = "{" "person" ":" String "," "age" ":" PositiveInteger "}"
    ;

DynamicVariable
    = Identifier ":"
        ( SimpleFormula | MultiStepFormula )
    ;

SimpleFormula
    = "formula" ":" FormulaElements
    ;

MultiStepFormula
    = "steps" ":"
        { StepEntry }+                                  (* last step = final value *)
    ;

StepEntry
    = Identifier ":"                                    (* step name *)
        "formula" ":" FormulaElements
    ;

FormulaElements
    = FormulaElement { FormulaElement }*
    ;

FormulaElement
    = "variable" ":" VariableName                       (* reference to a variable *)
    | "value"    ":" Number                             (* literal numeric value *)
    | "operator" ":" Operator
    ;

Operator
    = "+" | "-" | "*" | "/" | "^"
    ;

(* ------------------------------------------------------------ *)
(* 3. Retiree Profile Section                                   *)
(* ------------------------------------------------------------ *)
RetireeProfileSection
    = "retiree_profile" ":"
        "simulation_start_year" ":" Year
        "standard_of_living"    ":" PositiveNumber
        [ "minimum_standard_of_living" ":" NonNegativeNumber ]  (* 0 = disabled *)
        [ "maximum_standard_of_living" ":" NonNegativeNumber ]  (* 0 = disabled *)
        "people" ":" { PersonEntry }+
    ;

PersonEntry
    = "-" "name"                ":" String
          "birth_year"          ":" Year
          "retirement_year"     ":" Year
          "income_contribution" ":" NonNegativeNumber
    ;

(* ------------------------------------------------------------ *)
(* 4. Strategies Section                                        *)
(* ------------------------------------------------------------ *)
(* Named, reusable investment strategies. Each strategy defines *)
(* an allocation map only (no rebalancing field). Rebalancing   *)
(* is implicit -- each account grows at the weighted rate.      *)

StrategiesSection
    = "strategies" ":"
        { StrategyEntry }+
    ;

(* A strategy declares EITHER a fixed allocation OR a glide path,   *)
(* never both. A fixed allocation is resolved once and frozen for    *)
(* the whole simulation (unchanged). A glide path is a time-varying  *)
(* schedule of allocation keyframes, linearly interpolated per       *)
(* cycle year (see below). Setting both is rejected at parse time,   *)
(* naming the strategy.                                              *)
StrategyEntry
    = Identifier ":"                                    (* strategy name *)
        ( AllocationBlock | GlidePathBlock )
    ;

AllocationBlock
    = "allocation" ":"
        { Identifier ":" Decimal }+                     (* must sum to 1.0 +/- 0.001 *)
    ;                                                   (* keys must be subset of asset_classes *)

(* Glide path: an ordered set of keyframes, each pairing a           *)
(* point-in-time with an allocation map. Each keyframe time is       *)
(* resolved to a single monotonic 1-based Cycle_Year axis; the       *)
(* effective allocation for a cycle year is linearly interpolated    *)
(* per asset class between the surrounding keyframes (end values held  *)
(* flat before the first / after the last keyframe). Fully           *)
(* deterministic -- draws no RNG. Requires at least one keyframe;     *)
(* keyframes are sorted strictly ascending by resolved Cycle_Year     *)
(* before interpolation, and two keyframes resolving to the same      *)
(* Cycle_Year are rejected, naming the strategy.                      *)
GlidePathBlock
    = "glide_path" ":"
        "keyframes" ":"
            { GlidePathKeyframe }+                      (* >= 1 keyframe *)
    ;

GlidePathKeyframe
    = "-" "at"         ":" KeyframePointInTime
          "allocation" ":" KeyframeAllocation
    ;

(* Keyframe point-in-time: either an age-based reference (resolved    *)
(* to a Cycle_Year via the person's birth_year and                    *)
(* simulation_start_year) or a literal 1-based Cycle_Year. An age      *)
(* naming a person absent from retiree_profile is rejected, naming     *)
(* the strategy and keyframe.                                          *)
KeyframePointInTime
    = AgeBased                                          (* { person: "Alice", age: 65 } *)
    | "{" "cycle_year" ":" PositiveInteger "}"          (* literal 1-based Cycle_Year *)
    ;

KeyframeAllocation
    = { Identifier ":" Decimal }+                       (* keys subset of asset_classes; *)
    ;                                                   (* each weight in [0.0, 1.0]; sum 1.0 +/- 0.001 *)

(* ------------------------------------------------------------ *)
(* 5. Accounts Section                                          *)
(* ------------------------------------------------------------ *)
(* Named accounts with type, owner, balance, and strategy ref.  *)
(* See PortfolioScopeSection (5b) for scoping portfolio_value.  *)
(* total_portfolio_value always equals all accounts.            *)

AccountsSection
    = "accounts" ":"
        { AccountEntry }+
    ;

AccountEntry
    = "-" "name"     ":" String                         (* unique account identifier *)
          "type"     ":" AccountType
          "balance"  ":" BalanceValue
          "strategy" ":" Identifier                     (* must reference strategies section *)
          [ "owner"  ":" String ]                       (* required for tax_deferred *)
    ;

AccountType
    = "tax_deferred"
    | "tax_exempt"
    | "taxable"
    | "custom"
    ;

BalanceValue
    = NonNegativeNumber                                 (* literal: 555000 *)
    | VariableReference                                 (* { variable: "bridge_fund" } *)
    ;

VariableReference
    = "{" "variable" ":" String "}"
    ;

(* ------------------------------------------------------------ *)
(* 5b. Portfolio Scope Section (optional, top-level)            *)
(* ------------------------------------------------------------ *)
(* Lists which accounts contribute to portfolio_value.          *)
(* If omitted, all accounts are included.                       *)
(* total_portfolio_value always equals the sum of all accounts  *)
(* regardless of scope.                                         *)
(* Note: This is a top-level key because the accounts section   *)
(* is a list and cannot have sibling mapping keys.     *)

PortfolioScopeSection
    = "portfolio_scope" ":" PortfolioScopeList
    ;

PortfolioScopeList
    = "[" String { "," String }* "]"                    (* account names *)
    ;

(* ------------------------------------------------------------ *)
(* 6. Cash Flows Section                                        *)
(* ------------------------------------------------------------ *)
(* Cash flow target is a named account reference.               *)
(* bridge_withdrawal uses source_account instead of target.     *)

CashFlowsSection
    = "cash_flows" ":"
        { CashFlowEntry }*
    ;

CashFlowEntry
    = "-" "name"      ":" String
          "type"      ":" CashFlowType
          CashFlowBody
    ;

CashFlowBody
    = GenericCashFlowBody                               (* recurring | one_time | income *)
    | SocialSecurityBody                                (* social_security *)
    | PensionBody                                       (* pension *)
    | BridgeWithdrawalBody                              (* bridge_withdrawal *)
    ;

(* Generic cash flow: target references a named account *)
GenericCashFlowBody
    = "direction" ":" Direction
      "target"    ":" String                            (* must reference a defined account name *)
      [ "owner"   ":" String ]
      "amount"    ":" AmountValue
      [ "inflation_adjusted" ":" Boolean ]              (* default: false *)
      [ "inflation_modifier"      ":" Number ]          (* default: none; see below *)
      [ "absolute_inflation_rate" ":" AbsoluteInflationRate ] (* default: none; mutually exclusive with inflation_modifier; see below *)
      [ "person"  ":" String ]
      [ SurvivorBenefitStartBlock ]
      "timing"    ":" TimingBlock
      [ StochasticOneTimeBlock ]                        (* one_time only; see below *)
    ;

(* inflation_modifier (optional, additive percentage points):     *)
(* when present AND inflation_adjusted is true, this cash flow     *)
(* escalates at (global_inflation + inflation_modifier) compounded *)
(* over its active years, instead of the shared cumulative         *)
(* inflation path. Primary use case: healthcare rising faster than *)
(* CPI (e.g. inflation_modifier: 0.03). When absent, the flow uses *)
(* the shared cumulative-inflation escalation (unchanged). When    *)
(* present but inflation_adjusted is false, the amount is left     *)
(* unescalated (neither global inflation nor modifier applied).    *)

(* absolute_inflation_rate (optional, flat annual escalation rate): *)
(* when present AND inflation_adjusted is true, this cash flow      *)
(* escalates at a FIXED annual rate DECOUPLED from CPI: the amount  *)
(* is multiplied by (1 + absolute_inflation_rate) once per active   *)
(* year, i.e. amount * (1 + absolute_inflation_rate)^(active-year   *)
(* count), independent of global_inflation and of the shared        *)
(* cumulative-inflation path. Primary use case: a fixed annuity     *)
(* payout, a mortgage, or a contract with a stated escalator        *)
(* (e.g. absolute_inflation_rate: 0.02 = flat 2%/yr). It is         *)
(* MUTUALLY EXCLUSIVE with inflation_modifier -- a cash flow that    *)
(* sets both is rejected at parse time, naming the cash flow (a      *)
(* cash flow escalates by exactly one of three paths: shared         *)
(* cumulative when neither field is set, relative-to-CPI via         *)
(* inflation_modifier, or decoupled via absolute_inflation_rate).    *)
(* When present but inflation_adjusted is false, the amount is left   *)
(* unescalated and the rate is ignored (a no-op). 0.0 is a valid     *)
(* no-op that leaves every active-year amount equal to the base.     *)
AbsoluteInflationRate
    = Number                                            (* in (-1.0, 100.0]: reject <= -1.0 and any value outside [-100.0, 100.0] *)
    ;

(* Stochastic one-time expense (one_time cash flows only):          *)
(* a one_time cash flow with neither occurrence_probability nor      *)
(* window fires deterministically at its resolved timing.year        *)
(* (unchanged). Supplying BOTH occurrence_probability and a window   *)
(* makes the flow stochastic: it fires zero or one time per          *)
(* simulation, with the occurrence decision and the sampled year     *)
(* drawn once from the per-simulation RNG at init. The two fields    *)
(* are MUTUALLY REQUIRED -- probability without window, or window     *)
(* without probability, is rejected at parse time naming the cash    *)
(* flow. Window bounds are INCLUSIVE and use the same YearValue       *)
(* forms as one-time timing; a window whose resolved end year is      *)
(* earlier than its resolved start year is rejected.                 *)
StochasticOneTimeBlock
    = "occurrence_probability" ":" OccurrenceProbability
      "window" ":"
          "start" ":" YearValue                         (* inclusive lower bound *)
          "end"   ":" YearValue                         (* inclusive upper bound; resolved end >= resolved start *)
    ;

OccurrenceProbability
    = Number                                            (* 0.0 <= p <= 1.0 *)
    ;

(* Social security: direction implied as contribution *)
SocialSecurityBody
    = "target"    ":" String                            (* must reference a defined account name *)
      "amount"    ":" AmountValue
      "person"    ":" String                            (* required *)
      [ "owner"   ":" String ]
      [ "inflation_adjusted" ":" Boolean ]              (* implied true *)
      [ SurvivorBenefitStartBlock_NoBenefit ]
      "timing"    ":" TimingBlock
    ;

(* Pension: direction implied as contribution *)
PensionBody
    = "target"    ":" String                            (* must reference a defined account name *)
      "amount"    ":" AmountValue
      "person"    ":" String                            (* required *)
      [ "owner"   ":" String ]
      [ "inflation_adjusted" ":" Boolean ]              (* default: false *)
      [ SurvivorBenefitStartBlock ]
      "timing"    ":" TimingBlock
    ;

(* Bridge withdrawal: draws from a named account, adds to income *)
BridgeWithdrawalBody
    = "source_account" ":" String                       (* must reference a defined account name *)
      "amount"         ":" AmountValue
      [ "person"       ":" String ]
      [ "inflation_adjusted" ":" Boolean ]              (* default: false *)
      "timing"         ":" TimingBlock
    ;

CashFlowType
    = "recurring"
    | "one_time"
    | "social_security"
    | "pension"
    | "income"
    | "bridge_withdrawal"
    ;

Direction
    = "contribution"
    | "withdrawal"
    ;

AmountValue
    = PositiveNumber                                    (* literal: 25000 *)
    | VariableReference                                 (* { variable: "rob_ss_amount" } *)
    ;

(* 6a. Timing *)
TimingBlock
    = RecurringTiming
    | OneTimeTiming
    ;

RecurringTiming
    = [ "phase"      ":" Phase ]
      [ "person"     ":" String ]
      [ "start_year" ":" YearValue ]
      [ "end_year"   ":" YearValue ]
    ;

OneTimeTiming
    = "year" ":" YearValue
    ;

(* YearValue is polymorphic -- can be expressed multiple ways *)
YearValue
    = Year                                              (* literal: 2027 *)
    | AgeBased                                          (* { person: "John", age: 67 } *)
    | VariableReference                                 (* { variable: "john_ss_start" } *)
    | VariableReferenceWithOffset                       (* { variable: "john_ss_start", offset: -1 } *)
    | String                                            (* named variable: "retirement_year_john" *)
    | Null                                              (* no bound *)
    ;

AgeBased
    = "{" "person" ":" String "," "age" ":" PositiveInteger "}"
    ;

VariableReferenceWithOffset
    = "{" "variable" ":" String "," "offset" ":" Integer "}"
    ;

Phase
    = "accumulation"
    | "drawdown"
    ;

(* 6b. Survivor Benefit Start *)
SurvivorBenefitStartBlock
    = "survivor_benefit_start" ":"
        "type" ":" SurvivorType
        [ "year_range" ":" "[" Year "," Year "]" ]      (* required if type = "random" *)
        [ "year"       ":" Year ]                       (* required if type = "fixed" *)
        [ "group"      ":" String ]                     (* required if type != "none" *)
        [ "benefit"    ":" BenefitMode ]
        [ "expose_as"  ":" String ]                     (* optional: variable name *)
    ;

(* Variant for social_security: benefit is always "greater_of" *)
SurvivorBenefitStartBlock_NoBenefit
    = "survivor_benefit_start" ":"
        "type" ":" SurvivorType
        [ "year_range" ":" "[" Year "," Year "]" ]
        [ "year"       ":" Year ]
        [ "group"      ":" String ]
        (* benefit NOT allowed -- always "greater_of" for social_security *)
        [ "expose_as"  ":" String ]
    ;

SurvivorType
    = "random"
    | "fixed"
    | "none"
    ;

BenefitMode
    = "greater_of"
    | "combined"
    ;

(* ------------------------------------------------------------ *)
(* 7. Transfer Strategies Section (optional)                    *)
(* ------------------------------------------------------------ *)
(* Named transfer strategies define tiered source account lists  *)
(* with weight modes. Used by transfer rules to determine where *)
(* to draw funds from during end-of-year positioning.           *)

TransferStrategiesSection
    = "transfer_strategies" ":"
        { TransferStrategyEntry }+
    ;

TransferStrategyEntry
    = Identifier ":"                                    (* transfer strategy name *)
        "sources" ":"
            { TransferSourceTier }+
    ;

TransferSourceTier
    = "-" "accounts" ":" AccountNameList                  (* primary β€” weight mode applies *)
          [ "fallback" ":" AccountNameList ]              (* secondary β€” sequential if primary exhausted *)
          "weight"   ":" WeightMode                      (* distribution method *)
    ;

AccountNameList
    = "[" String { "," String }* "]"                    (* references defined account names *)
    ;

WeightMode
    = "proportional"                                    (* distribute by account balance ratio *)
    | "equal"                                           (* distribute evenly *)
    | "sequential"                                      (* drain first before moving to next *)
    ;

(* ------------------------------------------------------------ *)
(* 8. Transfer Rules Section                                    *)
(* ------------------------------------------------------------ *)
(* Conditional account-to-account transfers executed after      *)
(* withdrawal at end-of-year. source_strategy selects which     *)
(* transfer strategy to use based on conditions.                *)

TransferRulesSection
    = "transfer_rules" ":"
        { TransferRuleEntry }*                          (* may be empty list *)
    ;

TransferRuleEntry
    = "-" "name"      ":" String
          "condition" ":" Condition
          "target"    ":" String                        (* must reference a defined account name *)
          "amount"    ":" FormulaElements
          [ "source_strategy" ":" SourceStrategyList ]
    ;

SourceStrategyList
    = { SourceStrategyEntry }+
    ;

SourceStrategyEntry
    = "-" "condition" ":" Condition
          "use"       ":" Identifier                    (* must reference transfer_strategies *)
    ;

(* ------------------------------------------------------------ *)
(* 9. Withdrawal Rules Section                                  *)
(* ------------------------------------------------------------ *)
(* Every withdrawal rule MUST have a source block specifying    *)
(* account + fallback. The last rule must have condition:       *)
(* default and continue: false. Ruin condition: all fallbacks   *)
(* exhausted.                                                   *)

WithdrawalRulesSection
    = "withdrawal_rules" ":"
        { WithdrawalRuleEntry }+
    ;

(* The final entry MUST be: condition = "default", continue = false *)

WithdrawalRuleEntry
    = "-" "name"        ":" String
        [ "description" ":" String ]
        [ "start_year"  ":" YearValue ]
        [ "end_year"    ":" YearValue ]
          "condition"   ":" Condition
          "action"      ":" ActionBlock
          "source"      ":" SourceBlock                 (* REQUIRED on every rule *)
        [ "continue"    ":" Boolean ]                   (* default: false *)
    ;

(* 9a. Conditions *)
Condition
    = SimpleCondition
    | AllOfCondition
    | AnyOfCondition
    | DefaultCondition
    ;

SimpleCondition
    = "variable"   ":" VariableName
      "operator"   ":" ComparisonOperator
      "compare_to" ":" CompareValue
    ;

AllOfCondition
    = "all_of" ":"
        { "-" SimpleCondition }+
    ;

AnyOfCondition
    = "any_of" ":"
        { "-" SimpleCondition }+
    ;

DefaultCondition
    = "default"                                         (* always matches *)
    ;

ComparisonOperator
    = "<" | "<=" | ">" | ">=" | "=" | "!="
    ;

CompareValue
    = Number                                            (* literal: 0, 73, 0.04 *)
    | Boolean                                           (* true / false *)
    | String                                            (* variable name or expression *)
    ;

(* 9b. Actions *)
ActionBlock
    = { ActionStep }*
      "withdrawal_amount" ":" ActionFormula
    ;

ActionStep
    = Identifier ":"                                    (* intermediate variable name *)
        ActionFormula
    ;

ActionFormula
    = "formula" ":" FormulaElements
    ;

(* 9c. Source Block -- required on every withdrawal rule *)
(* account: primary account to withdraw from              *)
(* fallback: ordered list of accounts if primary is empty *)
(* Ruin occurs when all accounts (primary + fallbacks)    *)
(* are exhausted.                                         *)

SourceBlock
    = "account"  ":" String                             (* must reference a defined account name *)
      [ "fallback" ":" SourceFallbackList ]             (* ordered fallback accounts *)
    ;

SourceFallbackList
    = "[" String { "," String }* "]"                    (* references defined account names *)
    ;

(* ------------------------------------------------------------ *)
(* 10. Bracket Notation Variables                               *)
(* ------------------------------------------------------------ *)
(* Variables use bracket notation: namespace["key"] to access   *)
(* per-account or per-person values. The namespace identifies   *)
(* the variable type and the key selects the specific instance. *)

VariableName
    = SimpleVariableName                                (* e.g., "portfolio_value" *)
    | BracketNotationVariable                           (* e.g., 'account_balance["Roth IRA"]' *)
    | FlatVariableReference                             (* e.g., "account_balance_roth_ira" *)
    ;

SimpleVariableName
    = Identifier                                        (* plain variable reference *)
    ;

BracketNotationVariable
    = Namespace "[\"" Key "\"]"                         (* namespace["key"] *)
    ;

(* Flat variable naming convention:
   An alternative to bracket notation. The variable name is
   formed by appending a normalized key to the namespace:
     namespace_<normalized_key>
   where normalized_key is the original name lowercased with
   spaces replaced by underscores.

   Examples:
     account_balance_taxable_brokerage  = account_balance["Taxable Brokerage"]
     account_balance_john's_401k        = account_balance["John's 401k"]
     rmd_amount_john                    = rmd_amount["John"]
     age_john                           = age["John"]

   Both conventions resolve to the same underlying value.
   Not all namespaces support flat naming -- retirement_year
   and is_retired are bracket-notation only.
*)

FlatVariableReference
    = Namespace "_" NormalizedKey                        (* namespace_normalized_key *)
    ;

NormalizedKey
    = /[a-z][a-z0-9_']*/                                (* lowercased, spaces as underscores *)
    ;

(* Known namespaces for bracket notation:
   account_balance["Account Name"]   - current balance of named account
   age["Person Name"]                - current age of named person
   years_retired["Person Name"]      - years since retirement for person
   income["Person Name"]             - income contribution for person
   rmd_amount["Person Name"]         - required minimum distribution for person
*)

Namespace
    = "account_balance"
    | "age"
    | "years_retired"
    | "income"
    | "rmd_amount"
    | Identifier                                        (* extensible for custom namespaces *)
    ;

Key
    = String                                            (* account name or person name *)
    ;

(* ------------------------------------------------------------ *)
(* Terminal Types                                               *)
(* ------------------------------------------------------------ *)
Identifier          = /[a-z][a-z0-9_]*/                 ;
String              = /".+"/ | /'.+'/ | /[a-zA-Z_]+/    ;
Year                = /[12][0-9]{3}/                    ;   (* 4-digit year *)
Integer             = /-?[0-9]+/                        ;
SeedInteger         = /[0-9]+/                          ;   (* 0 .. 2^32-1 *)
PositiveInteger     = /[1-9][0-9]*/                     ;
Number              = /-?[0-9]+(\.[0-9]+)?/             ;
PositiveNumber      = /[0-9]+(\.[0-9]+)?/               ;   (* > 0 *)
NonNegativeNumber   = /[0-9]+(\.[0-9]+)?/               ;   (* >= 0 *)
Decimal             = /-?[0-9]+\.[0-9]+/                ;
NonNegativeDecimal  = /[0-9]+\.[0-9]+/                  ;
Boolean             = "true" | "false"                  ;
Null                = "null"                            ;
ScalarValue         = Number | Boolean | String         ;

Results are estimates from simulations, not predictions. They are not investment, tax or legal advice.

Early access is coming soon.