| 
539
 | 
     1 """
 | 
| 
 | 
     2 Parsing utilities for gene rules (GPRs).
 | 
| 
 | 
     3 
 | 
| 
 | 
     4 This module provides:
 | 
| 
 | 
     5 - RuleErr: structured errors for malformed rules
 | 
| 
 | 
     6 - RuleOp: valid logical operators (AND/OR)
 | 
| 
 | 
     7 - OpList: nested list structure representing parsed rules with explicit operator
 | 
| 
 | 
     8 - RuleStack: helper stack to build nested OpLists during parsing
 | 
| 
 | 
     9 - parseRuleToNestedList: main entry to parse a rule string into an OpList
 | 
| 
 | 
    10 """
 | 
| 
 | 
    11 from enum import Enum
 | 
| 
 | 
    12 from typing import List, Union, Optional
 | 
| 
 | 
    13 
 | 
| 
542
 | 
    14 try:
 | 
| 
 | 
    15     from . import general_utils as utils
 | 
| 
 | 
    16 except:
 | 
| 
 | 
    17     import general_utils as utils
 | 
| 
 | 
    18 
 | 
| 
539
 | 
    19 class RuleErr(utils.CustomErr):
 | 
| 
 | 
    20     """
 | 
| 
 | 
    21     Error type for rule syntax errors.
 | 
| 
 | 
    22     """
 | 
| 
 | 
    23     errName = "Rule Syntax Error"
 | 
| 
 | 
    24     def __init__(self, rule :str, msg = "no further details provided") -> None:
 | 
| 
 | 
    25         super().__init__(
 | 
| 
 | 
    26             f"rule \"{rule}\" is malformed, {msg}",
 | 
| 
 | 
    27             "please verify your input follows the validity guidelines")
 | 
| 
 | 
    28 
 | 
| 
 | 
    29 class RuleOp(Enum):
 | 
| 
 | 
    30     """
 | 
| 
 | 
    31     Valid logical operators for gene rules.
 | 
| 
 | 
    32     """
 | 
| 
 | 
    33     OR  = "or"
 | 
| 
 | 
    34     AND = "and"
 | 
| 
 | 
    35 
 | 
| 
 | 
    36     @classmethod
 | 
| 
 | 
    37     def isOperator(cls, op :str) -> bool:
 | 
| 
 | 
    38         return op.upper() in cls.__members__
 | 
| 
 | 
    39 
 | 
| 
 | 
    40     def __str__(self) -> str: return self.value
 | 
| 
 | 
    41 
 | 
| 
 | 
    42 class OpList(List[Union[str, "OpList"]]):
 | 
| 
 | 
    43     """
 | 
| 
 | 
    44     Parsed rule structure: a list with an associated operator for that level.
 | 
| 
 | 
    45     """
 | 
| 
 | 
    46     def __init__(self, op :Optional[RuleOp] = None) -> None:
 | 
| 
 | 
    47         """
 | 
| 
 | 
    48         (Private) Initializes an instance of OpList.
 | 
| 
 | 
    49 
 | 
| 
 | 
    50         Args:
 | 
| 
 | 
    51             op (str): Operator to be assigned to the OpList. Defaults to "".
 | 
| 
 | 
    52         
 | 
| 
 | 
    53         Returns:
 | 
| 
 | 
    54             None : practically, an OpList instance.
 | 
| 
 | 
    55         """
 | 
| 
 | 
    56         self.op = op
 | 
| 
 | 
    57 
 | 
| 
 | 
    58     def setOpIfMissing(self, op :RuleOp) -> None:
 | 
| 
 | 
    59         """
 | 
| 
 | 
    60         Sets the operator of the OpList if it's missing.
 | 
| 
 | 
    61 
 | 
| 
 | 
    62         Args:
 | 
| 
 | 
    63             op (str): Operator to be assigned to the OpList.
 | 
| 
 | 
    64         
 | 
| 
 | 
    65         Returns:
 | 
| 
 | 
    66             None
 | 
| 
 | 
    67         """
 | 
| 
 | 
    68         if not self.op: self.op = op
 | 
| 
 | 
    69 
 | 
| 
 | 
    70     def __repr__(self, indent = "") -> str:
 | 
| 
 | 
    71         """
 | 
| 
 | 
    72         (Private) Returns a string representation of the current OpList instance.
 | 
| 
 | 
    73 
 | 
| 
 | 
    74         Args:
 | 
| 
 | 
    75             indent (str): Indentation level . Defaults to "".
 | 
| 
 | 
    76 
 | 
| 
 | 
    77         Returns:
 | 
| 
 | 
    78             str: A string representation of the current OpList instance.
 | 
| 
 | 
    79         """
 | 
| 
 | 
    80         nextIndent = indent + "  "
 | 
| 
 | 
    81         return f"<{self.op}>[\n" + ",\n".join([
 | 
| 
 | 
    82             f"{nextIndent}{item.__repr__(nextIndent) if isinstance(item, OpList) else item}"
 | 
| 
 | 
    83             for item in self ]) + f"\n{indent}]"
 | 
| 
 | 
    84 
 | 
| 
 | 
    85 class RuleStack:
 | 
| 
 | 
    86     """
 | 
| 
 | 
    87     FILO stack used during parsing to build nested OpLists; the top is the current level.
 | 
| 
 | 
    88     """
 | 
| 
 | 
    89     def __init__(self) -> None:
 | 
| 
 | 
    90         """
 | 
| 
 | 
    91         (Private) initializes an instance of RuleStack.
 | 
| 
 | 
    92 
 | 
| 
 | 
    93         Returns:
 | 
| 
 | 
    94             None : practically, a RuleStack instance.
 | 
| 
 | 
    95         """
 | 
| 
 | 
    96         self.__stack = [OpList()] # the stack starts out with the result list already allocated
 | 
| 
 | 
    97         self.__updateCurrent()
 | 
| 
 | 
    98 
 | 
| 
 | 
    99     def pop(self) -> None:
 | 
| 
 | 
   100         """
 | 
| 
 | 
   101         Removes the OpList on top of the stack, also flattening it once when possible.
 | 
| 
 | 
   102 
 | 
| 
 | 
   103         Side Effects:
 | 
| 
 | 
   104             self : mut
 | 
| 
 | 
   105 
 | 
| 
 | 
   106         Returns:
 | 
| 
 | 
   107             None
 | 
| 
 | 
   108         """
 | 
| 
 | 
   109         oldTop = self.__stack.pop()
 | 
| 
 | 
   110         if len(oldTop) == 1 and isinstance(oldTop[0], OpList): self.__stack[-1][-1] = oldTop[0]
 | 
| 
 | 
   111         self.__updateCurrent()
 | 
| 
 | 
   112 
 | 
| 
 | 
   113     def push(self, operator = "") -> None:
 | 
| 
 | 
   114         """
 | 
| 
 | 
   115         Adds a new nesting level, in the form of a new OpList on top of the stack.
 | 
| 
 | 
   116 
 | 
| 
 | 
   117         Args:
 | 
| 
 | 
   118             operator : the operator assigned to the new OpList.
 | 
| 
 | 
   119 
 | 
| 
 | 
   120         Side Effects:
 | 
| 
 | 
   121             self : mut
 | 
| 
 | 
   122         
 | 
| 
 | 
   123         Returns:
 | 
| 
 | 
   124             None
 | 
| 
 | 
   125         """
 | 
| 
 | 
   126         newLevel = OpList(operator)
 | 
| 
 | 
   127         self.current.append(newLevel)
 | 
| 
 | 
   128         self.__stack.append(newLevel)
 | 
| 
 | 
   129         self.__updateCurrent()
 | 
| 
 | 
   130 
 | 
| 
 | 
   131     def popForward(self) -> None:
 | 
| 
 | 
   132         """
 | 
| 
 | 
   133         Moves the last "actual" item from the 2nd to last list to the beginning of the top list, as per
 | 
| 
 | 
   134         the example below:
 | 
| 
 | 
   135         stack  : [list_a, list_b]
 | 
| 
 | 
   136         list_a : [item1, item2, list_b] --> [item1, list_b]
 | 
| 
 | 
   137         list_b : [item3, item4]         --> [item2, item3, item4]
 | 
| 
 | 
   138 
 | 
| 
 | 
   139         This is essentially a "give back as needed" operation.
 | 
| 
 | 
   140 
 | 
| 
 | 
   141         Side Effects:
 | 
| 
 | 
   142             self : mut
 | 
| 
 | 
   143         
 | 
| 
 | 
   144         Returns:
 | 
| 
 | 
   145             None
 | 
| 
 | 
   146         """
 | 
| 
 | 
   147         self.current.insert(0, self.__stack[-2].pop(-2))
 | 
| 
 | 
   148 
 | 
| 
 | 
   149     def currentIsAnd(self) -> bool:
 | 
| 
 | 
   150         """
 | 
| 
 | 
   151         Checks if the current OpList's assigned operator is "and".
 | 
| 
 | 
   152 
 | 
| 
 | 
   153         Returns:
 | 
| 
 | 
   154             bool : True if the current OpList's assigned operator is "and", False otherwise.
 | 
| 
 | 
   155         """
 | 
| 
 | 
   156         return self.current.op is RuleOp.AND
 | 
| 
 | 
   157 
 | 
| 
 | 
   158     def obtain(self, err :Optional[utils.CustomErr] = None) -> Optional[OpList]:
 | 
| 
 | 
   159         """
 | 
| 
 | 
   160         Obtains the first OpList on the stack, only if it's the only element.
 | 
| 
 | 
   161 
 | 
| 
 | 
   162         Args:
 | 
| 
 | 
   163             err : The error to raise if obtaining the result is not possible.
 | 
| 
 | 
   164 
 | 
| 
 | 
   165         Side Effects:
 | 
| 
 | 
   166             self : mut    
 | 
| 
 | 
   167         
 | 
| 
 | 
   168         Raises:
 | 
| 
 | 
   169             err: If given, otherwise None is returned.
 | 
| 
 | 
   170 
 | 
| 
 | 
   171         Returns:
 | 
| 
 | 
   172             Optional[OpList]: The first OpList on the stack, only if it's the only element.
 | 
| 
 | 
   173         """
 | 
| 
 | 
   174 
 | 
| 
 | 
   175         if len(self.__stack) == 1: return self.__stack.pop()
 | 
| 
 | 
   176         if err: raise err
 | 
| 
 | 
   177         return None
 | 
| 
 | 
   178 
 | 
| 
 | 
   179     def __updateCurrent(self) -> None:
 | 
| 
 | 
   180         """
 | 
| 
 | 
   181         (Private) Updates the current OpList to the one on top of the stack.
 | 
| 
 | 
   182 
 | 
| 
 | 
   183         Side Effects:
 | 
| 
 | 
   184             self : mut
 | 
| 
 | 
   185         
 | 
| 
 | 
   186         Returns:
 | 
| 
 | 
   187             None
 | 
| 
 | 
   188         """
 | 
| 
 | 
   189         self.current = self.__stack[-1]
 | 
| 
 | 
   190 
 | 
| 
 | 
   191 def parseRuleToNestedList(rule :str) -> OpList:
 | 
| 
 | 
   192     """
 | 
| 
 | 
   193     Parse a rule string into an OpList, making operator precedence explicit via nesting.
 | 
| 
 | 
   194 
 | 
| 
 | 
   195     Args:
 | 
| 
 | 
   196         rule: Rule string to parse (supports parentheses, 'and', 'or').
 | 
| 
 | 
   197     
 | 
| 
 | 
   198     Raises:
 | 
| 
 | 
   199         RuleErr: If the rule is malformed (e.g., mismatched parentheses or misplaced operators).
 | 
| 
 | 
   200     
 | 
| 
 | 
   201     Returns:
 | 
| 
 | 
   202         OpList: Parsed rule as an OpList structure.
 | 
| 
 | 
   203     """
 | 
| 
 | 
   204     source = iter(rule
 | 
| 
 | 
   205         .replace("(", "( ").replace(")", " )") # single out parentheses as words
 | 
| 
 | 
   206         .strip()  # trim edges
 | 
| 
 | 
   207         .split()) # split by spaces
 | 
| 
 | 
   208 
 | 
| 
 | 
   209     stack = RuleStack()
 | 
| 
 | 
   210     nestingErr = RuleErr(rule, "mismatch between open and closed parentheses")
 | 
| 
 | 
   211     try:
 | 
| 
 | 
   212         while True: # read until source ends
 | 
| 
 | 
   213             while True:
 | 
| 
 | 
   214                 operand = next(source, None) # expect operand or '('
 | 
| 
 | 
   215                 if operand is None: raise RuleErr(rule, "found trailing open parentheses")
 | 
| 
 | 
   216                 if operand in ("and", "or", ")"): # unexpected operator position
 | 
| 
 | 
   217                     raise RuleErr(rule, f"found \"{operand}\" in unexpected position")
 | 
| 
 | 
   218 
 | 
| 
 | 
   219                 if operand != "(": break # got a name
 | 
| 
 | 
   220 
 | 
| 
 | 
   221                 # found rule opening: add a new nesting level
 | 
| 
 | 
   222                 stack.push()
 | 
| 
 | 
   223 
 | 
| 
 | 
   224             stack.current.append(operand)
 | 
| 
 | 
   225 
 | 
| 
 | 
   226             while True: # read until operator found or source ends
 | 
| 
 | 
   227                 operator = next(source, None) # expect operator or ')'
 | 
| 
 | 
   228                 if operator and operator != ")": break # got operator
 | 
| 
 | 
   229 
 | 
| 
 | 
   230                 if stack.currentIsAnd(): stack.pop() # close current AND chain
 | 
| 
 | 
   231 
 | 
| 
 | 
   232                 if not operator: break
 | 
| 
 | 
   233                 stack.pop() # close parentheses
 | 
| 
 | 
   234 
 | 
| 
 | 
   235             if not operator: break
 | 
| 
 | 
   236             
 | 
| 
 | 
   237             if not RuleOp.isOperator(operator): raise RuleErr(
 | 
| 
 | 
   238                 rule, f"found \"{operator}\" in unexpected position, expected operator")
 | 
| 
 | 
   239             
 | 
| 
 | 
   240             operator = RuleOp(operator)
 | 
| 
 | 
   241             if operator is RuleOp.OR and stack.currentIsAnd():
 | 
| 
 | 
   242                 stack.pop()
 | 
| 
 | 
   243 
 | 
| 
 | 
   244             elif operator is RuleOp.AND and not stack.currentIsAnd():
 | 
| 
 | 
   245                 stack.push(operator)
 | 
| 
 | 
   246                 stack.popForward()
 | 
| 
 | 
   247 
 | 
| 
 | 
   248             stack.current.setOpIfMissing(operator)
 | 
| 
 | 
   249 
 | 
| 
 | 
   250     except RuleErr as err: raise err # bubble up proper errors
 | 
| 
 | 
   251     except: raise nestingErr # everything else is interpreted as a nesting error.
 | 
| 
 | 
   252 
 | 
| 
 | 
   253     parsedRule = stack.obtain(nestingErr)
 | 
| 
 | 
   254     return parsedRule[0] if len(parsedRule) == 1 and isinstance(parsedRule[0], list) else parsedRule |