How to use the pycparser.c_ast.Constant function in pycparser

To help you get started, we’ve selected a few pycparser examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github blexim / synth / src / frontend / frontend.py View on Github external
b.init = c_ast.ArrayRef(c_ast.ID('in_vars'),
                              c_ast.Constant('int', str(vid)))

      decls.append(b)

  for id in sorted(rev_id_map.keys()):
    varname = rev_id_map[id]
    arr = c_ast.ArrayRef(c_ast.ID('out_vars'),
                         c_ast.Constant('int', str(id)))
    var = c_ast.ID(varname)

    copy_out.append(c_ast.Assignment("=", arr, var))


  prefix.block_items += copy_out
  prefix.block_items.append(c_ast.Return(c_ast.Constant('int', str('1'))))

  ofile.write("int prefix(word_t in_vars[%d], word_t out_vars[%d]) {\n" % (nids, nids))
  ofile.write(cgen.visit(prefix))
  ofile.write("}\n\n")

  ofile.write("int guard(word_t in_vars[%d]) {\n" % nids)
  guard_body = c_ast.Compound(copy.copy(decls))
  guard_body.block_items.append(c_ast.Return(loop.cond))
  ofile.write(cgen.visit(guard_body))
  ofile.write("}\n\n")

  ofile.write("void body(word_t in_vars[%d], word_t out_vars[%d]) {\n" % (nids, nids))
  loop_body = c_ast.Compound(copy.copy(decls))
  loop_body.block_items.append(loop.stmt)
  loop_body.block_items += copy_out
  ofile.write(cgen.visit(loop_body))
github revng / llvmcpy / llvmcpy / llvm.py View on Github external
# Check if enum has defined a value
                    if enum.value is not None:
                        value = handle_expression(context, enum.value)
                    name = remove_prefix(enum.name)
                    mapping[value] = name

                    # Add reverse lookup as well, ignoring aliases
                    if name not in mapping:
                        mapping[name] = value

                    # Save in the context, so that other entries can refere to
                    # it
                    context[enum.name] = value

                    # Rewrite using a constant
                    enum.value = pycparser.c_ast.Constant("int", str(value))

                    value += 1

                self.enums[self._name] = mapping

                # Clear the scope
                self._name = None
github jamie-pate / jstruct / parse / annotations.py View on Github external
# static array
            init_exprs.append(c_ast.NamedInitializer(
                [c_ast.ID('length')],
                arraydecl.dim
            ))
        elif types['json'] == 'json_type_array':
            # calculate length offset
            len_prop = AnnotatedProperty.LENGTH_NAME(prop_name)
            self.extra_decls[len_prop] = 'int'
            init_exprs.append(c_ast.NamedInitializer(
                [c_ast.ID('length_offset')],
                self.offsetof(struct.name, len_prop)
            ))
            init_exprs.append(c_ast.NamedInitializer(
                [c_ast.ID('dereference')],
                c_ast.Constant('int', '1')
            ))

        if types['json'] == 'json_type_array':
            # assume PtrDecl for now
            init_exprs.append(c_ast.NamedInitializer(
                [c_ast.ID('stride')],
                self.sizeof(decl.type.type)
            ))


        fi = getframeinfo(currentframe())
        self.init_list = c_ast.InitList(init_exprs, Coord(fi.filename, fi.lineno))
github XX-net / XX-Net / code / default / python27 / 1.0 / lib / win32 / cffi / cparser.py View on Github external
def _parse_constant(self, exprnode, partial_length_ok=False):
        # for now, limited to expressions that are an immediate number
        # or positive/negative number
        if isinstance(exprnode, pycparser.c_ast.Constant):
            s = exprnode.value
            if s.startswith('0'):
                if s.startswith('0x') or s.startswith('0X'):
                    return int(s, 16)
                return int(s, 8)
            elif '1' <= s[0] <= '9':
                return int(s, 10)
            elif s[0] == "'" and s[-1] == "'" and (
                    len(s) == 3 or (len(s) == 4 and s[1] == "\\")):
                return ord(s[-2])
            else:
                raise api.CDefError("invalid constant %r" % (s,))
        #
        if (isinstance(exprnode, pycparser.c_ast.UnaryOp) and
                exprnode.op == '+'):
            return self._parse_constant(exprnode.expr)
github andrewchambers / pycc / c / types.py View on Github external
def _parseArrayDecl(typeTable,node):
    dim = node.dim
    if type(dim)  == c_ast.Constant:
        dim = int(dim.value,10)
    else:
        raise Exception("XXX non constant array size not permitted")
    return Array(parseTypeDecl(typeTable,node.type),dim)
github blexim / synth / src / frontends / splitter.py View on Github external
assertion_block += [c_ast.Return(assertion_expr)]
  assertion.block_items = assertion_block

  f.write("int assertion(word_t in_vars[NARGS]) {\n")
  f.write(assertion)
  f.write("}\n\n")

  for id in sorted(rev_id_map.keys()):
    varname = rev_id_map[id]
    arr = c_ast.ArrayRef(c_ast.ID('out_vars'),
                         c_ast.Constant('int', str(id)))
    var = c_ast.ID(varname)

    copy_out.append(c_ast.Assignment("=", arr, var))

  copy_out.append(c_ast.Return(c_ast.Constant('int', str('1'))))

  prefix.block_items += copy_out

  f.write("int prefix(word_t in_vars[NARGS], word_t out_vars[NARGS]) {\n")
  f.write(prefix)
  f.write("}\n\n")

  f.write("int guard(word_t in_vars[NARGS]) {\n")
  guard_body = c_ast.Compound(copy.copy(decls))
  guard_body.block_items.append(c_ast.Return(loop.cond))
  f.write(guard_body)
  ofile.write("}\n\n")

  if is_nested_loop(loop):
    has_nested = True
github LedgerHQ / nanos-secure-sdk / pycparser / c_parser.py View on Github external
def p_unified_string_literal(self, p):
        """ unified_string_literal  : STRING_LITERAL
                                    | unified_string_literal STRING_LITERAL
        """
        if len(p) == 2: # single literal
            p[0] = c_ast.Constant(
                'string', p[1], self._coord(p.lineno(1)))
        else:
            p[1].value = p[1].value[:-1] + p[2][1:]
            p[0] = p[1]
github mabuchilab / NiceLib / nicelib / process.py View on Github external
def _const_from_val(val):
        if isinstance(val, int):
            return c_ast.Constant('int', str(int(val)))
        elif isinstance(val, float):
            return c_ast.Constant('float', str(val))
        elif isinstance(val, str):
            return c_ast.Constant('string', val)
        else:
            raise ConvertError("Unknown value type '{}'".format(val))
github mabuchilab / NiceLib / nicelib / process.py View on Github external
def _const_from_val(val):
        if isinstance(val, int):
            return c_ast.Constant('int', str(int(val)))
        elif isinstance(val, float):
            return c_ast.Constant('float', str(val))
        elif isinstance(val, str):
            return c_ast.Constant('string', val)
        else:
            raise ConvertError("Unknown value type '{}'".format(val))
github jamie-pate / jstruct / parse / annotations.py View on Github external
init_list = []

        prop_name = type_find(decl, c_ast.TypeDecl).declname

        # name the property if it hasn't already been named
        if 'name' not in self.values:
            self.values['name'] = prop_name

        # add string initializers
        for init_name in ('name', 'schema'):
            if init_name in self.values:
                literal = str_literal(self.values[init_name])
                init_exprs.append(
                    c_ast.NamedInitializer(
                        [c_ast.ID(init_name)],
                        c_ast.Constant('string', literal)
                    )
                )

        # assign types
        type_annotations = {
            name: t for name,t in self.values.iteritems()
            if isinstance(t, Annotation)
        }
        types, arraydecl = self.struct.annotations.get_types(decl, type_annotations)
        type_inits = [c_ast.NamedInitializer(
            [c_ast.ID(ttype)],
            c_ast.ID(t)
        ) for ttype, t in types.iteritems()]
        fi = getframeinfo(currentframe())
        init_exprs.append(c_ast.NamedInitializer(
            [c_ast.ID('type')],