@@ -724,50 +724,61 @@ $Order = 2,
724724$Variable = @{}
725725)
726726
727+ # First, let us expand our axiom
727728$currentState = "$Axiom"
729+ # (at least, as long as we're supposed to)
728730if ($Order -ge 1) {
729731 $combinedPattern = "(?> $($Rule.Keys -join '|'))"
730732 foreach ($iteration in 1..$Order) {
733+ # To expand each iteration, we replace any matching characters
731734 $currentState = $currentState -replace $combinedPattern, {
732735 $match = $_
733736 $matchingRule = $rule["$match"]
737+ # a matching rule could be dynamically specified with a script block
734738 if ($matchingRule -is [ScriptBlock]) {
735739 return "$(. $matchingRule $match)"
736740 } else {
741+ # but is often statically expanded with a string.
737742 return $matchingRule
738743 }
739744 }
740745 }
741746}
742747
743- $localReplacement = [Ordered]@{}
744- foreach ($key in $variable.Keys) {
745- $localReplacement[$key] =
746- if ($variable[$key] -is [ScriptBlock]) {
747- [ScriptBlock]::Create($variable[$key])
748- } else {
749- $variable[$key]
750- }
751- }
752-
748+ # Now we know our final state
753749$finalState = $currentState
754750
751+ # and can add the appropriate data attributes.
755752$this.PathAttribute = [Ordered]@{
756753 "data-l-order" = $Order
757754 "data-l-axiom" = $Axiom
758755 "data-l-rules" = ConvertTo-Json $Rule
759756 "data-l-expanded" = $finalState
760757}
761758
759+ # Next, prepare our replacements.
760+ # The provided script block will almost always be scoped differently
761+ # so we need to recreate it.
762+ $localReplacement = [Ordered]@{}
763+ foreach ($key in $variable.Keys) {
764+ $localReplacement[$key] =
765+ if ($variable[$key] -is [ScriptBlock]) {
766+ [ScriptBlock]::Create($variable[$key])
767+ } else {
768+ $variable[$key]
769+ }
770+ }
771+
772+ # Now we need to find all potential matches
762773$MatchesAny = "(?> $($variable.Keys -join '|'))"
763774$allMatches = @([Regex]::Matches($finalState, $MatchesAny, 'IgnoreCase,IgnorePatternWhitespace'))
775+ # we want to minimize rematching, so create a temporary cache.
764776$matchCache = @{}
765777:nextMatch foreach ($match in $allMatches) {
766778 $m = "$match"
767779 if (-not $matchCache[$m]) {
768780 foreach ($key in $Variable.Keys) {
769- if (-not ($match -match $key)) { continue }
770- # if ($variable[$key] -isnot [ScriptBlock]) { continue }
781+ if (-not ($match -match $key)) { continue }
771782 $matchCache[$m] = $localReplacement[$key]
772783 break
773784 }
0 commit comments