from pygccxml import utils
from pygccxml import declarations
from pygccxml import parser
import sys
import os

class gcc_parser:
  def __init__(self, file_name):
    self.gen_path , self.gen_name = utils.find_xml_generator()
    self.xml_gen_conf = parser.xml_generator_configuration_t(
      xml_generator_path = self.gen_path,
      xml_generator = self.gen_name,
      compiler = 'gcc')
    self.global_ns = None
    self.file_path = os.path.abspath(file_name)
  #Parser and get global namespace of specific file
  def parse_file(self):
    decls = parser.parse([self.file_path], self.xml_gen_conf)
    self.global_ns = declarations.get_global_namespace(decls[0])
  #Parse and get declarations with specific decl_type
  def decl_match(self, type_n):
    decl_m = declarations.variable_matcher()
    decls = declarations.matcher.find(decl_m, 'int')
    return decls
  #Parse and get the functions with specific return type
  def func_return_match(self, type_n):
    re_t = declarations.calldef_matcher(return_type = type_n, header_file = self.file_path)
    func = declarations.matcher.find(re_t, self.global_ns)
    return func
  def get_decl(self):
    decls = []
    for decl in p.global_ns.declarations:
      if decl.location._file_name == self.file_path:
        decls.append([decl.name])
    return decls
  #Get local variables in this file
  def get_members(self):
    member = []
    for var in p.global_ns.variables():
      if var.location._file_name == p.file_path:
        member.append({'name': var.name, 'decl_type': var.type.decl_string, 'value': var.value})
    return member


if __name__ == '__main__':
  #Create parser
  p = gcc_parser(sys.argv[1])
  p.parse_file()
  int_type = declarations.cpptypes.int_t()
  char_type = declarations.cpptypes.char_t()
  mem = p.get_members()
  print mem
  funcs = p.func_return_match(int_type)
  for func in funcs:
    print func.name
    func = p.global_ns.member_functions(func.name)
