('AND', c1, c1), ('OR', c1, c2), ('NOT', c1),
('==', e1, e2), ('!=', e1, e2) where e1, e2 are `ConfigExpression`s.
"""
- def __init__(self, text, clause, parent=None):
+ def __init__(self, formula, text=None, parent=None):
"""
- Condition defined by `text` (informative), `clause` as in class definition,
+ Condition defined by `text` (informative), `formula` as in class definition,
`parent` is the parent condition (if any).
"""
+ if not text:
+ text = self.formula_string(formula)
super(ConfigVar, self).__init__(text)
- self.clause = clause
+ self.formula = formula
self.parent = parent
# Setup dependencies on used variables (not on the parent condition)
for v in self.variables():
if self.parent:
self.parent.dependants.add(self)
def variables(self, cl=None):
- "Return an iterator of variables used in clause `cl`"
+ "Return an iterator of variables used in formula `cl`"
if not cl:
- cl = self.clause
+ cl = self.formula
if cl[0] in ['==','!=']:
return itertools.chain(cl[1].variables(), cl[2].variables())
if cl[0] in ['AND','OR']:
if self.parent:
self.parent.dependants.discard(self)
def evaluate(self, cl=None, depth=0):
- """Evaluate clause `cl` (or the entire condition).
+ """Evaluate formula `cl` (or the entire condition).
Partial evaluation for AND and OR. Tests the parent condition first."""
check_depth(depth)
if not cl:
- cl = self.clause
+ cl = self.formula
if self.parent and not self.parent.value():
return False
if cl[0] in ['==','!=']:
if cl[0] == 'OR' and v1: return True
if cl[0] == 'AND' and not v1: return False
return self.evaluate(cl[2], depth+1)
+ def formula_string(self, formula):
+ "Create a string representation of a formula."
+ if formula[0] == 'AND':
+ return itertools.chain(['('], self.formula_string(formula[1]), [' and '], self.formula_string(formula[2]),[')'])
+ elif formula[0] == 'OR':
+ return itertools.chain(['('], self.formula_string(formula[1]), [' or '], self.formula_string(formula[2]),[')'])
+ elif formula[0] == 'NOT':
+ return itertools.chain(['(not '], self.formula_string(formula[1]),[')'])
+ elif formula[0] in ['==', '!=']:
+ return itertools.chain(formula[1], formula[0], formula[2])
+ return iter(['<invalid formula>'])
def str(self, parents=False):
"Retur the defining expression, if `parents` set, then prefixed with parent conditions."
if parents and self.parent: