def __init__(self, raw_pattern, raw_previous, weight, alternates, method, rulename): """ Create a new Rule object based on information supplied to the @rule decorator. Arguments: raw_pattern - simplified regular expression string supplied to @rule raw_previous - simplified regular expression string supplied to @rule weight - weight supplied to @rule alternates - dictionary of variable names and values that can be substituted in the patterns method - reference to method decorated by @rule rulename - modulename.classname.methodname, used to make better error messages Raises PatternError, PatternVariableNotFoundError, PatternVariableValueError """ try: previous = "" if not raw_pattern: raise PatternError("Empty string found") self.pattern = Pattern(raw_pattern, alternates) previous = "previous " self.previous = Pattern(raw_previous, alternates) except (TypeError, PatternError, PatternVariableValueError, PatternVariableNotFoundError) as e: msg = " in {0}pattern of {1}".format(previous, rulename) e.args = (e.args[0] + msg,) + e.args[1:] raise self.weight = weight self.method = method self.rulename = rulename
def _parse_alternates(self, alternates, script_class_name): """Construct Pattern objects for all the values in the alternates instance variable (hopefully a dictionary) of a Script subclass, and construct a dictionary of the keys from alternates and the pattern object. Wrap that in another dictionary keyed by 'a' so it can be used by %a:varname in other patterns. """ valid = {} k = "" try: for k, v in alternates.items(): valid[k] = Pattern(v, simple=True).formatted_pattern except Exception as e: msg = " in alternates" if k: msg += '["{0}"]'.format(k) msg += " of {0}".format(script_class_name) e.args = (e.args[0] + msg,) + e.args[1:] raise return {"a": valid}