3131import re
3232import sys
3333import uuid
34- from collections .abc import Mapping
34+ from collections .abc import Iterator , Mapping
3535from dataclasses import dataclass , field
3636from decimal import Decimal as _Decimal
3737from enum import Enum
6767_SAFE_PATH_SEGMENT_RE = re .compile (r"^[A-Za-z][A-Za-z0-9_]*$" )
6868
6969
70+ def _skip_powerfx_opaque_token (formula : str , start : int ) -> int :
71+ """Return the end of an ordinary quoted token or comment, or start if neither."""
72+ quote = formula [start ]
73+ if quote in ('"' , "'" ):
74+ pos = start + 1
75+ while pos < len (formula ):
76+ if formula [pos ] == quote :
77+ if pos + 1 < len (formula ) and formula [pos + 1 ] == quote :
78+ pos += 2
79+ continue
80+ return pos + 1
81+ pos += 1
82+ return pos
83+ if formula .startswith ("//" , start ):
84+ pos = start + 2
85+ while pos < len (formula ) and formula [pos ] not in "\r \n " :
86+ pos += 1
87+ return pos
88+ if formula .startswith ("/*" , start ):
89+ end = formula .find ("*/" , start + 2 )
90+ return len (formula ) if end == - 1 else end + 2
91+ return start
92+
93+
94+ def _iter_powerfx_expression_indices (formula : str ) -> Iterator [int ]:
95+ """Yield code positions, excluding literals/comments but including interpolation expressions."""
96+ # None denotes interpolated text; integers track record braces in expression sections.
97+ scopes : list [int | None ] = [0 ]
98+ cursor = 0
99+ while cursor < len (formula ):
100+ depth = scopes [- 1 ]
101+ char = formula [cursor ]
102+ if depth is None :
103+ if formula .startswith (('""' , "{{" , "}}" ), cursor ):
104+ cursor += 2
105+ continue
106+ if char == "{" :
107+ scopes .append (0 )
108+ elif char == '"' :
109+ scopes .pop ()
110+ cursor += 1
111+ continue
112+
113+ if formula .startswith ('$"' , cursor ):
114+ scopes .append (None )
115+ cursor += 2
116+ continue
117+
118+ token_end = _skip_powerfx_opaque_token (formula , cursor )
119+ if token_end != cursor :
120+ cursor = token_end
121+ continue
122+
123+ if char == "{" :
124+ scopes [- 1 ] = depth + 1
125+ elif char == "}" :
126+ if depth > 0 :
127+ scopes [- 1 ] = depth - 1
128+ elif len (scopes ) > 1 :
129+ scopes .pop ()
130+ cursor += 1
131+ continue
132+
133+ yield cursor
134+ cursor += 1
135+
136+
70137@dataclass (frozen = True )
71138class DeclarativeEnvConfig :
72139 """Configuration that populates the PowerFx ``Env`` symbol for a workflow.
@@ -670,7 +737,8 @@ def _preprocess_custom_functions(self, formula: str, temp_writes: list[tuple[str
670737 Results are stored in temporary state variables so untrusted message text is
671738 passed to PowerFx as data rather than inserted into formula source.
672739 Temporary names avoid existing Local keys and references in the original formula.
673- Quoted strings, quoted identifiers, and comments are left untouched.
740+ Literal text, quoted identifiers, and comments are left untouched; expression
741+ sections inside PowerFx interpolated strings are preprocessed as code.
674742
675743 Args:
676744 formula: The PowerFx formula to pre-process
@@ -683,71 +751,36 @@ def _preprocess_custom_functions(self, formula: str, temp_writes: list[tuple[str
683751 Returns:
684752 The rewritten formula.
685753 """
686-
687- def skip_opaque_token (start : int ) -> int :
688- """Return the end of a quoted token or comment, or start if neither."""
689- quote = formula [start ]
690- if quote in ('"' , "'" ):
691- pos = start + 1
692- while pos < len (formula ):
693- if formula [pos ] == quote :
694- if pos + 1 < len (formula ) and formula [pos + 1 ] == quote :
695- pos += 2
696- continue
697- return pos + 1
698- pos += 1
699- return pos
700- if formula .startswith ("//" , start ):
701- pos = start + 2
702- while pos < len (formula ) and formula [pos ] not in "\r \n " :
703- pos += 1
704- return pos
705- if formula .startswith ("/*" , start ):
706- end = formula .find ("*/" , start + 2 )
707- return len (formula ) if end == - 1 else end + 2
708- return start
709-
710754 temp_var_counter = 0
711755 reserved_names = {name .casefold () for name in self .get_state_data ().get ("Local" , {})}
712756 # Reserve formula references too, so previously undefined names stay undefined.
713757 folded_formula = formula .casefold ()
714758 function_name = "MessageText"
759+ call_prefix = f"{ function_name } ("
715760 result : list [str ] = []
716- cursor = 0
717-
718- while cursor < len (formula ):
719- token_end = skip_opaque_token (cursor )
720- if token_end != cursor :
721- result .append (formula [cursor :token_end ])
722- cursor = token_end
723- continue
761+ copied_until = 0
762+ positions = _iter_powerfx_expression_indices (formula )
724763
725- call_prefix = f" { function_name } ("
764+ for cursor in positions :
726765 if not formula .startswith (call_prefix , cursor ):
727- result .append (formula [cursor ])
728- cursor += 1
729766 continue
730767
731768 paren_start = cursor + len (function_name )
732769 depth = 1
733- pos = paren_start + 1
734- while pos < len (formula ) and depth > 0 :
735- token_end = skip_opaque_token (pos )
736- if token_end != pos :
737- pos = token_end
770+ for pos in positions :
771+ if pos <= paren_start :
738772 continue
739773 char = formula [pos ]
740774 if char == "(" :
741775 depth += 1
742776 elif char == ")" :
743777 depth -= 1
744- pos += 1
745-
746- if depth != 0 :
747- result .append (formula [cursor :])
778+ if depth == 0 :
779+ break
780+ else :
748781 break
749782
750- inner_expr = formula [paren_start + 1 : pos - 1 ]
783+ inner_expr = formula [paren_start + 1 : pos ]
751784 replacement = self ._eval_and_replace_message_text (inner_expr )
752785 while True :
753786 temp_var_name = f"_TempMessageText{ temp_var_counter } "
@@ -758,10 +791,12 @@ def skip_opaque_token(start: int) -> int:
758791 temp_var_path = f"Local.{ temp_var_name } "
759792 temp_writes .append ((temp_var_path , self .get (temp_var_path , default = self ._MISSING )))
760793 self .set (temp_var_path , replacement )
794+ result .append (formula [copied_until :cursor ])
761795 result .append (temp_var_path )
762796 logger .debug (f"Stored MessageText result ({ len (replacement )} chars) in temp variable { temp_var_name } " )
763- cursor = pos
797+ copied_until = pos + 1
764798
799+ result .append (formula [copied_until :])
765800 return "" .join (result )
766801
767802 def _eval_and_replace_message_text (self , inner_expr : str ) -> str :
0 commit comments