Esempio n. 1
0
 def __init__(self, span, tokens):
     super(JsonObj, self).__init__(span)
     self.props = {}
     last_prop = None
     if len(tokens) > 0:
         for toks in tokens:
             for tok in toks:
                 if isinstance(tok, DotPath):
                     if last_prop is None:
                         last_prop = tok
                     else:
                         self._set_new_prop(last_prop, tok)
                         last_prop = None
                 elif isinstance(tok, StringLit):
                     if last_prop is None:
                         last_prop = tok
                     else:
                         self._set_new_prop(last_prop, tok)
                         last_prop = None
                 elif isinstance(tok, list):
                     if last_prop is None:
                         raise p.ParseFatalException(
                             "Bug Found in JsonObj!")
                     self._set_new_prop(last_prop,
                                        JsonObj.dictify_array(tok))
                     last_prop = None
                 else:
                     if last_prop is None:
                         raise p.ParseFatalException(
                             "Bug Found in JsonObj!")
                     self._set_new_prop(last_prop, tok)
                     last_prop = None
Esempio n. 2
0
def _ConvertRegexpValue(_, loc, toks):
    """Regular expression value for condition.

  """
    (regexp, flags) = toks[0]

    # Ensure only whitelisted flags are used
    unknown_flags = (frozenset(flags) - _KNOWN_REGEXP_FLAGS)
    if unknown_flags:
        raise pyp.ParseFatalException(
            "Unknown regular expression flags: '%s'" % "".join(unknown_flags),
            loc)

    if flags:
        re_flags = "(?%s)" % "".join(sorted(flags))
    else:
        re_flags = ""

    re_cond = re_flags + regexp

    # Test if valid
    try:
        re.compile(re_cond)
    except re.error, err:
        raise pyp.ParseFatalException("Invalid regular expression (%s)" % err,
                                      loc)
def periodValidation(instr, loc, tokens):
    period = int(tokens[0])
    if period == 0:
        raise pyparsing.ParseFatalException(instr, loc, "Period must not be 0")

    if (period % 60) != 0:
        raise pyparsing.ParseFatalException(
            instr, loc, "Period {} must be a multiple of 60".format(period))
    # Must return the string
    return tokens[0]
Esempio n. 4
0
def verify_length(s, l, t):
    t = t[0]
    if t.len is not None:
        t1len = len(t[1])
        if t1len != t.len:
            raise pp.ParseFatalException(s, l, "invalid data of length {}, expected {}".format(t1len, t.len))
    return t[1]
def periodsValidation(instr, loc, tokens):
    periods = int(tokens[0])
    if periods < 1:
        raise pyparsing.ParseFatalException(
            instr, loc, "Periods {} must be 1 or greater".format(periods))
    # Must return the string
    return tokens[0]
Esempio n. 6
0
 def makeDictAction(s,l,t):
     targs = {}
     for (k,v) in args.items():
         if isinstance(v, tuple) and len(v) == 2:
             try:
                 targs[k] = t.asList()[v[0]:v[1]]
             except:
                 targs[k] = t[v[0]:v[1]]
         elif not isinstance(v, (str, unicode, int)):
             targs[k] = v
         else: 
             try:
                 targs[k] = t[v].asList()
             except:
                 try:
                     targs[k] = t[v]
                 except:
                     if isinstance(k, int):
                         raise
     try:
         i = cls(**targs)
         # need to reset last error on first positive match
         self._lastParseError = None
         return i
     except types.TypeRecoverableInstanceCreationError as e:
         self._lastParseError = e.message
         raise pp.ParseException(s,l, self._lastParseError)
     except types.TypeInstanceCreationError as e:
         raise pp.ParseFatalException(s,l,e.message)
Esempio n. 7
0
 def changeScopeAction(s,l,t):
     moduleName = t[0].evaluate() # i assume a Symbol is here
     # need to valutate the currentScope
     myclips.logger.debug("Changing scope: %s -> %s", modulesManager.currentScope.moduleName, moduleName)
     if moduleName != modulesManager.currentScope.moduleName:
         try:
             modulesManager.currentScope.modules.changeCurrentScope(moduleName)
         except ValueError, e:
             raise pp.ParseFatalException(s,l,e.args[0])
Esempio n. 8
0
 def _parse_action(s, l, toks):
     try:
         name = next(toks.keys())
     except StopIteration:
         name = ""
     kwargs["name"] = name
     try:
         return typ(*toks, **kwargs)
     except Exception:
         msg = "Parse Exception\n" + traceback.format_exc()
         raise pp.ParseFatalException(s, l, msg=msg)
Esempio n. 9
0
 def changeScopeAction(s,l,t):
     constructName = t[0].evaluate() # i assume a Symbol is here
     splitted = constructName.split("::", 2)
     if len(splitted) == 2:
         # there is a module definition
         moduleName, _ = splitted
         # need to valutate the currentScope
         myclips.logger.debug("Changing scope: %s -> %s", modulesManager.currentScope.moduleName, moduleName)
         if moduleName != modulesManager.currentScope.moduleName:
             try:
                 modulesManager.currentScope.modules.changeCurrentScope(moduleName)
             except ValueError, e:
                 raise pp.ParseFatalException(s,l,e.args[0])
Esempio n. 10
0
 def _build_connection_cache(self):
     """
     Build a cache of connections keyed by where they start from.
     """
     for ident_from, ident_to in self.connections:
         if ident_from.val not in self.connections_cache:
             self.connections_cache[ident_from.val] = []
         if ident_to.val not in self.connections_cache:
             self.connections_cache[ident_to.val] = []
         self.connections_cache[ident_from.val].append(ident_to.val)
     # Sanity check
     for _, vals in self.connections_cache:
         if len(set(vals)) != len(vals):
             raise p.ParseFatalException("Bug found in Connection!!")
Esempio n. 11
0
def into_connection(ast_node):
    """
    Convert an ast node into a Connection node.
    :type ast_node: Connection | Ident
    :param ast_node: The ast node to convert.
    :rtype: Connection
    :return: Returns a Connection node
    """
    if isinstance(ast_node, Connection):
        return ast_node
    elif isinstance(ast_node, Ident):
        return Connection(ast_node.span, [ast_node], [ast_node])
    else:
        raise p.ParseFatalException("Bug found!")
Esempio n. 12
0
 def parse_list(space, n, t):
     if len(t) != n:
         raise pp.ParseFatalException(
             'Invalid number of values in list.')
     if space == 'hsl':
         t[0].value /= 360
     elif space == 'rgb':
         if not t[0].percent:
             t[0].value /= 255
         if not t[1].percent:
             t[1].value /= 255
         if not t[2].percent:
             t[2].value /= 255
     values = [x.value for x in t]
     return CSSColor(space, *values)
Esempio n. 13
0
    def evaluate(self, aString):

        try:
            parsed = self.parser.parseString(aString, True)[0]
        except pp.ParseBaseException, e:
            if self._network.getParser(
            )._lastParseError != None and e.msg != self._network.getParser(
            )._lastParseError:
                raise pp.ParseFatalException(
                    e.pstr,
                    e.loc,
                    #e.msg + ". Possible cause: " +
                    self._network.getParser()._lastParseError)
            else:
                raise
Esempio n. 14
0
 def parse_hex_color(t):
     s = t[0]
     if len(s) not in (3, 4, 6, 8):
         return pp.ParseFatalException(
             'Invalid number of hex characters.')
     if len(s) in (3, 4):
         return CSSColor('rgb',
                         *(int(ch + ch, 16) / 255 for ch in t[0]))
     if len(s) in (6, 8):
         r = int(s[0:2], 16) / 255
         g = int(s[2:4], 16) / 255
         b = int(s[4:6], 16) / 255
     if len(s) == 8:
         a = int(s[6:8], 16) / 255
         return CSSColor('rgb', r, g, b, a)
     return CSSColor('rgb', r, g, b)
Esempio n. 15
0
 def parse(self, text, filterReturn=False, extended=False):
     
     parserName = 'CLIPSProgramParser' if not extended else 'ExtendedCLIPSProgramParser'
     
     try:
         return [x for x 
                     in self.getSParser(parserName).parseString(text, True).asList() 
                         if not isinstance(x, (str, unicode)) # always filter simple strings
                             # filter functions/templates/modules constructs (they are loaded in the MM)
                             and (( filterReturn and isinstance(x, (types.DefFactsConstruct, types.DefRuleConstruct)))
                                  or not filterReturn )] 
                     
     except pp.ParseBaseException, e:
         if self._lastParseError != None and e.msg != self._lastParseError:
             raise pp.ParseFatalException(e.pstr,
                                          e.loc,
                                          e.msg + ". Possible cause: " + self._lastParseError )
         else:
             raise
Esempio n. 16
0
 def makeAction(s,l,t):
     argsToUse = None
     if position != None:
         try:
             argsToUse = t[position].asList()
         except:
             argsToUse = t[position]
     else:
         try:
             argsToUse = t.asList()
         except:
             argsToUse = t
     
     try:
         i = cls(argsToUse)
         # need to reset last error on first positive match
         self._lastParseError = None
         return i
     except types.TypeRecoverableInstanceCreationError as e:
         self._lastParseError = e.message
         raise pp.ParseException(s,l, self._lastParseError)
     except types.TypeInstanceCreationError as e:
         raise pp.ParseFatalException(s,l,e.message)
Esempio n. 17
0
def fail_block(s, unused_loc, expr, err):
    raise pp.ParseFatalException(s, err.loc, 'invalid statement in %s' % expr)
Esempio n. 18
0
 def _set_colorspace(self, colorspace):
     if self.colorspace is not None and colorspace != self.colorspace:
         raise pp.ParseFatalException('Colorspace must be all the same.')
     self.colorspace = colorspace