Jon Ashburn | 154e270 | 2014-11-14 11:52:18 -0700 | [diff] [blame] | 1 | import argparse |
| 2 | import os |
| 3 | import sys |
| 4 | |
| 5 | # code_gen.py overview |
| 6 | # This script generates code based on input headers |
| 7 | # Initially it's intended to support Mantle and XGL headers and |
| 8 | # generate wrappers functions that can be used to display |
| 9 | # structs in a human-readable txt format, as well as utility functions |
| 10 | # to print enum values as strings |
| 11 | |
| 12 | |
| 13 | def handle_args(): |
| 14 | parser = argparse.ArgumentParser(description='Perform analysis of vogl trace.') |
| 15 | parser.add_argument('input_file', help='The input header file from which code will be generated.') |
| 16 | parser.add_argument('--rel_out_dir', required=False, default='glave_gen', help='Path relative to exec path to write output files. Will be created if needed.') |
| 17 | parser.add_argument('--abs_out_dir', required=False, default=None, help='Absolute path to write output files. Will be created if needed.') |
| 18 | parser.add_argument('--gen_graphviz', required=False, action='store_true', default=False, help='Enable generation of graphviz dot file.') |
| 19 | #parser.add_argument('--test', action='store_true', default=False, help='Run simple test.') |
| 20 | return parser.parse_args() |
| 21 | |
| 22 | # TODO : Ideally these data structs would be opaque to user and could be wrapped |
| 23 | # in their own class(es) to make them friendly for data look-up |
| 24 | # Dicts for Data storage |
| 25 | # enum_val_dict[value_name] = dict keys are the string enum value names for all enums |
| 26 | # |-------->['type'] = the type of enum class into which the value falls |
| 27 | # |-------->['val'] = the value assigned to this particular value_name |
| 28 | # '-------->['unique'] = bool designating if this enum 'val' is unique within this enum 'type' |
| 29 | enum_val_dict = {} |
| 30 | # enum_type_dict['type'] = the type or class of of enum |
| 31 | # '----->['val_name1', 'val_name2'...] = each type references a list of val_names within this type |
| 32 | enum_type_dict = {} |
| 33 | # struct_dict['struct_basename'] = the base (non-typedef'd) name of the struct |
| 34 | # |->[<member_num>] = members are stored via their integer placement in the struct |
| 35 | # | |->['name'] = string name of this struct member |
| 36 | # ... |->['full_type'] = complete type qualifier for this member |
| 37 | # |->['type'] = base type for this member |
| 38 | # |->['ptr'] = bool indicating if this member is ptr |
| 39 | # |->['const'] = bool indicating if this member is const |
| 40 | # |->['struct'] = bool indicating if this member is a struct type |
| 41 | # |->['array'] = bool indicating if this member is an array |
| 42 | # '->['array_size'] = int indicating size of array members (0 by default) |
| 43 | struct_dict = {} |
| 44 | # typedef_fwd_dict stores mapping from orig_type_name -> new_type_name |
| 45 | typedef_fwd_dict = {} |
| 46 | # typedef_rev_dict stores mapping from new_type_name -> orig_type_name |
| 47 | typedef_rev_dict = {} # store new_name -> orig_name mapping |
| 48 | # types_dict['id_name'] = identifier name will map to it's type |
| 49 | # '---->'type' = currently either 'struct' or 'enum' |
| 50 | types_dict = {} # store orig_name -> type mapping |
| 51 | |
| 52 | |
| 53 | # Class that parses header file and generates data structures that can |
| 54 | # Then be used for other tasks |
| 55 | class HeaderFileParser: |
| 56 | def __init__(self, header_file=None): |
| 57 | self.header_file = header_file |
| 58 | # store header data in various formats, see above for more info |
| 59 | self.enum_val_dict = {} |
| 60 | self.enum_type_dict = {} |
| 61 | self.struct_dict = {} |
| 62 | self.typedef_fwd_dict = {} |
| 63 | self.typedef_rev_dict = {} |
| 64 | self.types_dict = {} |
| 65 | |
| 66 | def setHeaderFile(self, header_file): |
| 67 | self.header_file = header_file |
| 68 | |
| 69 | def get_enum_val_dict(self): |
| 70 | return self.enum_val_dict |
| 71 | |
| 72 | def get_enum_type_dict(self): |
| 73 | return self.enum_type_dict |
| 74 | |
| 75 | def get_struct_dict(self): |
| 76 | return self.struct_dict |
| 77 | |
| 78 | def get_typedef_fwd_dict(self): |
| 79 | return self.typedef_fwd_dict |
| 80 | |
| 81 | def get_typedef_rev_dict(self): |
| 82 | return self.typedef_rev_dict |
| 83 | |
| 84 | def get_types_dict(self): |
| 85 | return self.types_dict |
| 86 | |
| 87 | # Parse header file into data structures |
| 88 | def parse(self): |
| 89 | # parse through the file, identifying different sections |
| 90 | parse_enum = False |
| 91 | parse_struct = False |
| 92 | member_num = 0 |
| 93 | # TODO : Comment parsing is very fragile but handles 2 known files |
| 94 | block_comment = False |
| 95 | with open(self.header_file) as f: |
| 96 | for line in f: |
| 97 | if block_comment: |
| 98 | if '*/' in line: |
| 99 | block_comment = False |
| 100 | continue |
| 101 | if '/*' in line: |
| 102 | block_comment = True |
| 103 | elif 0 == len(line.split()): |
| 104 | #print("Skipping empty line") |
| 105 | continue |
| 106 | elif line.split()[0].strip().startswith("//"): |
| 107 | #print("Skipping commentted line %s" % line) |
| 108 | continue |
| 109 | elif 'typedef enum' in line: |
| 110 | (ty_txt, en_txt, base_type) = line.strip().split(None, 2) |
| 111 | #print("Found ENUM type %s" % base_type) |
| 112 | parse_enum = True |
| 113 | self.types_dict[base_type] = 'enum' |
| 114 | elif 'typedef struct' in line: |
| 115 | (ty_txt, st_txt, base_type) = line.strip().split(None, 2) |
| 116 | #print("Found STRUCT type: %s" % base_type) |
| 117 | parse_struct = True |
| 118 | self.types_dict[base_type] = 'struct' |
| 119 | elif '}' in line and (parse_enum or parse_struct): |
| 120 | if len(line.split()) > 1: # deals with embedded union in one struct |
| 121 | parse_enum = False |
| 122 | parse_struct = False |
| 123 | member_num = 0 |
| 124 | # TODO : Can pull target of typedef here for remapping |
| 125 | (cur_char, targ_type) = line.strip().split(None, 1) |
| 126 | self.typedef_fwd_dict[base_type] = targ_type.strip(';') |
| 127 | self.typedef_rev_dict[targ_type.strip(';')] = base_type |
| 128 | elif parse_enum: |
| 129 | if '=' in line: |
| 130 | self._add_enum(line, base_type) |
| 131 | elif parse_struct: |
| 132 | if ';' in line: |
| 133 | self._add_struct(line, base_type, member_num) |
| 134 | member_num = member_num + 1 |
| 135 | #elif '(' in line: |
| 136 | #print("Function: %s" % line) |
| 137 | |
| 138 | # populate enum dicts based on enum lines |
| 139 | def _add_enum(self, line_txt, enum_type): |
| 140 | #print("Parsing enum line %s" % line_txt) |
| 141 | (enum_name, eq_char, enum_val) = line_txt.split(None, 2) |
| 142 | if '=' != eq_char: |
| 143 | print("ERROR: Couldn't parse enum line: %s" % line_txt) |
| 144 | self.enum_val_dict[enum_name] = {} |
| 145 | self.enum_val_dict[enum_name]['type'] = enum_type |
| 146 | # strip comma and comment, then extra split in case of no comma w/ comments |
| 147 | enum_val = enum_val.strip().split(',', 1)[0] |
| 148 | self.enum_val_dict[enum_name]['val'] = enum_val.split()[0] |
| 149 | # TODO : Make this more robust, to verify if enum value is unique |
| 150 | # Currently just try to cast to int which works ok but missed -(HEX) values |
| 151 | try: |
| 152 | #print("ENUM val:", self.enum_val_dict[enum_name]['val']) |
| 153 | int(self.enum_val_dict[enum_name]['val'], 0) |
| 154 | self.enum_val_dict[enum_name]['unique'] = True |
| 155 | #print("ENUM has num value") |
| 156 | except ValueError: |
| 157 | self.enum_val_dict[enum_name]['unique'] = False |
| 158 | #print("ENUM is not a number value") |
| 159 | # Update enum_type_dict as well |
| 160 | if not enum_type in self.enum_type_dict: |
| 161 | self.enum_type_dict[enum_type] = [] |
| 162 | self.enum_type_dict[enum_type].append(enum_name) |
| 163 | |
| 164 | # populate struct dicts based on struct lines |
| 165 | # TODO : Handle ":" bitfield, "**" ptr->ptr and "const type*const*" |
| 166 | def _add_struct(self, line_txt, struct_type, num): |
| 167 | #print("Parsing struct line %s" % line_txt) |
| 168 | if not struct_type in self.struct_dict: |
| 169 | self.struct_dict[struct_type] = {} |
| 170 | members = line_txt.strip().split(';', 1)[0] # first strip semicolon & comments |
| 171 | # TODO : Handle bitfields more correctly |
| 172 | members = members.strip().split(':', 1)[0] # strip bitfield element |
| 173 | (member_type, member_name) = members.rsplit(None, 1) |
| 174 | self.struct_dict[struct_type][num] = {} |
| 175 | self.struct_dict[struct_type][num]['full_type'] = member_type |
| 176 | if '*' in member_type: |
| 177 | self.struct_dict[struct_type][num]['ptr'] = True |
| 178 | member_type = member_type.strip('*') |
| 179 | else: |
| 180 | self.struct_dict[struct_type][num]['ptr'] = False |
| 181 | if 'const' in member_type: |
| 182 | self.struct_dict[struct_type][num]['const'] = True |
| 183 | member_type = member_type.strip('const').strip() |
| 184 | else: |
| 185 | self.struct_dict[struct_type][num]['const'] = False |
| 186 | if is_type(member_type, 'struct'): |
| 187 | self.struct_dict[struct_type][num]['struct'] = True |
| 188 | else: |
| 189 | self.struct_dict[struct_type][num]['struct'] = False |
| 190 | self.struct_dict[struct_type][num]['type'] = member_type |
| 191 | if '[' in member_name: |
| 192 | (member_name, array_size) = member_name.split('[', 1) |
| 193 | self.struct_dict[struct_type][num]['array'] = True |
| 194 | self.struct_dict[struct_type][num]['array_size'] = array_size.strip(']') |
| 195 | else: |
| 196 | self.struct_dict[struct_type][num]['array'] = False |
| 197 | self.struct_dict[struct_type][num]['array_size'] = 0 |
| 198 | self.struct_dict[struct_type][num]['name'] = member_name |
| 199 | |
| 200 | # check if given identifier if of specified type_to_check |
| 201 | def is_type(identifier, type_to_check): |
| 202 | #print("Checking if %s is type %s" % (identifier, type_to_check)) |
| 203 | if identifier in types_dict and type_to_check == types_dict[identifier]: |
| 204 | return True |
| 205 | if identifier in typedef_rev_dict: |
| 206 | new_id = typedef_rev_dict[identifier] |
| 207 | if new_id in types_dict and type_to_check == types_dict[new_id]: |
| 208 | return True |
| 209 | return False |
| 210 | |
| 211 | def recreate_structs(): |
| 212 | for struct_name in struct_dict: |
| 213 | sys.stdout.write("typedef struct %s\n{\n" % struct_name) |
| 214 | for mem_num in sorted(struct_dict[struct_name]): |
| 215 | sys.stdout.write(" ") |
| 216 | if struct_dict[struct_name][mem_num]['const']: |
| 217 | sys.stdout.write("const ") |
| 218 | #if struct_dict[struct_name][mem_num]['struct']: |
| 219 | # sys.stdout.write("struct ") |
| 220 | sys.stdout.write (struct_dict[struct_name][mem_num]['type']) |
| 221 | if struct_dict[struct_name][mem_num]['ptr']: |
| 222 | sys.stdout.write("*") |
| 223 | sys.stdout.write(" ") |
| 224 | sys.stdout.write(struct_dict[struct_name][mem_num]['name']) |
| 225 | if struct_dict[struct_name][mem_num]['array']: |
| 226 | sys.stdout.write("[") |
| 227 | sys.stdout.write(struct_dict[struct_name][mem_num]['array_size']) |
| 228 | sys.stdout.write("]") |
| 229 | sys.stdout.write(";\n") |
| 230 | sys.stdout.write("} ") |
| 231 | sys.stdout.write(typedef_fwd_dict[struct_name]) |
| 232 | sys.stdout.write(";\n\n") |
| 233 | |
| 234 | # class for writing common file elements |
| 235 | # Here's how this class lays out a file: |
| 236 | # COPYRIGHT |
| 237 | # HEADER |
| 238 | # BODY |
| 239 | # FOOTER |
| 240 | # |
| 241 | # For each of these sections, there's a "set*" function |
| 242 | # The class as a whole has a generate function which will write each section in order |
| 243 | class CommonFileGen: |
| 244 | def __init__(self, filename=None, copyright_txt="", header_txt="", body_txt="", footer_txt=""): |
| 245 | self.filename = filename |
| 246 | self.contents = {'copyright': copyright_txt, 'header': header_txt, 'body': body_txt, 'footer': footer_txt} |
| 247 | # TODO : Set a default copyright & footer at least |
| 248 | |
| 249 | def setFilename(self, filename): |
| 250 | self.filename = filename |
| 251 | |
| 252 | def setCopyright(self, c): |
| 253 | self.contents['copyright'] = c |
| 254 | |
| 255 | def setHeader(self, h): |
| 256 | self.contents['header'] = h |
| 257 | |
| 258 | def setBody(self, b): |
| 259 | self.contents['body'] = b |
| 260 | |
| 261 | def setFooter(self, f): |
| 262 | self.contents['footer'] = f |
| 263 | |
| 264 | def generate(self): |
| 265 | #print("Generate to file %s" % self.filename) |
| 266 | with open(self.filename, "w") as f: |
| 267 | f.write(self.contents['copyright']) |
| 268 | f.write(self.contents['header']) |
| 269 | f.write(self.contents['body']) |
| 270 | f.write(self.contents['footer']) |
| 271 | |
| 272 | # class for writing a wrapper class for structures |
| 273 | # The wrapper class wraps the structs and includes utility functions for |
| 274 | # setting/getting member values and displaying the struct data in various formats |
| 275 | class StructWrapperGen: |
| 276 | def __init__(self, in_struct_dict, prefix, out_dir): |
| 277 | self.struct_dict = in_struct_dict |
| 278 | self.include_headers = [] |
| 279 | self.api = prefix |
| 280 | self.header_filename = os.path.join(out_dir, self.api+"_struct_wrappers.h") |
| 281 | self.class_filename = os.path.join(out_dir, self.api+"_struct_wrappers.cpp") |
| 282 | self.string_helper_filename = os.path.join(out_dir, self.api+"_struct_string_helper.h") |
| 283 | self.hfg = CommonFileGen(self.header_filename) |
| 284 | self.cfg = CommonFileGen(self.class_filename) |
| 285 | self.shg = CommonFileGen(self.string_helper_filename) |
| 286 | #print(self.header_filename) |
| 287 | self.header_txt = "" |
| 288 | self.definition_txt = "" |
| 289 | |
| 290 | def set_include_headers(self, include_headers): |
| 291 | self.include_headers = include_headers |
| 292 | |
| 293 | # Return class name for given struct name |
| 294 | def get_class_name(self, struct_name): |
| 295 | class_name = struct_name.strip('_').lower() + "_struct_wrapper" |
| 296 | return class_name |
| 297 | |
| 298 | def get_file_list(self): |
| 299 | return [os.path.basename(self.header_filename), os.path.basename(self.class_filename), os.path.basename(self.string_helper_filename)] |
| 300 | |
| 301 | # Generate class header file |
| 302 | def generateHeader(self): |
| 303 | self.hfg.setCopyright(self._generateCopyright()) |
| 304 | self.hfg.setHeader(self._generateHeader()) |
| 305 | self.hfg.setBody(self._generateClassDeclaration()) |
| 306 | self.hfg.setFooter(self._generateFooter()) |
| 307 | self.hfg.generate() |
| 308 | |
| 309 | # Generate class definition |
| 310 | def generateBody(self): |
| 311 | self.cfg.setCopyright(self._generateCopyright()) |
| 312 | self.cfg.setHeader(self._generateCppHeader()) |
| 313 | self.cfg.setBody(self._generateClassDefinition()) |
| 314 | self.cfg.setFooter(self._generateFooter()) |
| 315 | self.cfg.generate() |
| 316 | |
| 317 | # Generate c-style .h file that contains functions for printing structs |
| 318 | def generateStringHelper(self): |
| 319 | print("Generating struct string helper") |
| 320 | self.shg.setCopyright(self._generateCopyright()) |
| 321 | self.shg.setHeader(self._generateHeader()) |
| 322 | self.shg.setBody(self._generateStringHelperFunctions()) |
| 323 | self.shg.generate() |
| 324 | |
| 325 | def _generateCopyright(self): |
| 326 | return "//This is the copyright\n" |
| 327 | |
| 328 | def _generateCppHeader(self): |
| 329 | header = [] |
| 330 | header.append("//#includes, #defines, globals and such...\n") |
| 331 | header.append("#include <stdio.h>\n#include <%s>\n#include <%s_string_helper.h>\n" % (os.path.basename(self.header_filename), self.api)) |
| 332 | return "".join(header) |
| 333 | |
| 334 | def _generateClassDefinition(self): |
| 335 | class_def = [] |
| 336 | if 'xgl' == self.api: # Mantle doesn't have pNext to worry about |
| 337 | class_def.append(self._generateDynamicPrintFunctions()) |
| 338 | for s in self.struct_dict: |
| 339 | class_def.append("\n// %s class definition" % self.get_class_name(s)) |
| 340 | class_def.append(self._generateConstructorDefinitions(s)) |
| 341 | class_def.append(self._generateDestructorDefinitions(s)) |
| 342 | class_def.append(self._generateDisplayDefinitions(s)) |
| 343 | return "\n".join(class_def) |
| 344 | |
| 345 | def _generateConstructorDefinitions(self, s): |
| 346 | con_defs = [] |
| 347 | con_defs.append("%s::%s() : m_struct(), m_indent(0), m_dummy_prefix('\\0'), m_origStructAddr(NULL) {}" % (self.get_class_name(s), self.get_class_name(s))) |
| 348 | # TODO : This is a shallow copy of ptrs |
| 349 | con_defs.append("%s::%s(%s* pInStruct) : m_indent(0), m_dummy_prefix('\\0')\n{\n m_struct = *pInStruct;\n m_origStructAddr = pInStruct;\n}" % (self.get_class_name(s), self.get_class_name(s), typedef_fwd_dict[s])) |
| 350 | con_defs.append("%s::%s(const %s* pInStruct) : m_indent(0), m_dummy_prefix('\\0')\n{\n m_struct = *pInStruct;\n m_origStructAddr = pInStruct;\n}" % (self.get_class_name(s), self.get_class_name(s), typedef_fwd_dict[s])) |
| 351 | return "\n".join(con_defs) |
| 352 | |
| 353 | def _generateDestructorDefinitions(self, s): |
| 354 | return "%s::~%s() {}" % (self.get_class_name(s), self.get_class_name(s)) |
| 355 | |
| 356 | def _generateDynamicPrintFunctions(self): |
| 357 | dp_funcs = [] |
| 358 | dp_funcs.append("\nvoid dynamic_display_full_txt(const XGL_VOID* pStruct, uint32_t indent)\n{\n // Cast to APP_INFO ptr initially just to pull sType off struct") |
| 359 | dp_funcs.append(" XGL_STRUCTURE_TYPE sType = ((XGL_APPLICATION_INFO*)pStruct)->sType; switch (sType)\n {") |
| 360 | for e in enum_type_dict: |
| 361 | class_num = 0 |
| 362 | if "_STRUCTURE_TYPE" in e: |
| 363 | for v in sorted(enum_type_dict[e]): |
| 364 | struct_name = v.replace("_STRUCTURE_TYPE", "") |
| 365 | class_name = self.get_class_name(struct_name) |
| 366 | # TODO : Hand-coded fixes for some exceptions |
| 367 | if 'XGL_PIPELINE_CB_STATE_CREATE_INFO' in struct_name: |
| 368 | struct_name = 'XGL_PIPELINE_CB_STATE' |
| 369 | elif 'XGL_SEMAPHORE_CREATE_INFO' in struct_name: |
| 370 | struct_name = 'XGL_QUEUE_SEMAPHORE_CREATE_INFO' |
| 371 | class_name = self.get_class_name(struct_name) |
| 372 | elif 'XGL_SEMAPHORE_OPEN_INFO' in struct_name: |
| 373 | struct_name = 'XGL_QUEUE_SEMAPHORE_OPEN_INFO' |
| 374 | class_name = self.get_class_name(struct_name) |
| 375 | instance_name = "swc%i" % class_num |
| 376 | dp_funcs.append(" case %s:\n {" % (v)) |
| 377 | dp_funcs.append(" %s %s((%s*)pStruct);" % (class_name, instance_name, struct_name)) |
| 378 | dp_funcs.append(" %s.set_indent(indent);" % (instance_name)) |
| 379 | dp_funcs.append(" %s.display_full_txt();" % (instance_name)) |
| 380 | dp_funcs.append(" }") |
| 381 | dp_funcs.append(" break;") |
| 382 | class_num += 1 |
| 383 | dp_funcs.append(" }") |
| 384 | dp_funcs.append("}\n") |
| 385 | return "\n".join(dp_funcs) |
| 386 | |
| 387 | def _get_sh_func_name(self, struct): |
| 388 | return "%s_print_%s" % (self.api, struct.lower().strip("_")) |
| 389 | |
| 390 | # Return elements to create formatted string for given struct member |
| 391 | def _get_struct_print_formatted(self, struct_member, pre_var_name="prefix", postfix = "\\n", struct_var_name="pStruct", struct_ptr=True, print_array=False): |
| 392 | struct_op = "->" |
| 393 | if not struct_ptr: |
| 394 | struct_op = "." |
| 395 | member_name = struct_member['name'] |
| 396 | print_type = "p" |
| 397 | cast_type = "" |
| 398 | member_post = "" |
| 399 | array_index = "" |
| 400 | member_print_post = "" |
| 401 | if struct_member['array'] and 'CHAR' in struct_member['type']: # just print char array as string |
| 402 | print_type = "s" |
| 403 | print_array = False |
| 404 | elif struct_member['array'] and not print_array: |
| 405 | # Just print base address of array when not full print_array |
| 406 | cast_type = "(void*)" |
| 407 | elif is_type(struct_member['type'], 'enum'): |
| 408 | cast_type = "string_%s" % struct_member['type'] |
| 409 | print_type = "s" |
| 410 | elif is_type(struct_member['type'], 'struct'): # print struct address for now |
| 411 | cast_type = "(void*)" |
| 412 | if not struct_member['ptr']: |
| 413 | cast_type = "(void*)&" |
| 414 | elif 'BOOL' in struct_member['type']: |
| 415 | print_type = "s" |
| 416 | member_post = ' ? "TRUE" : "FALSE"' |
| 417 | elif 'FLOAT' in struct_member['type']: |
| 418 | print_type = "f" |
| 419 | elif 'UINT64' in struct_member['type']: |
| 420 | print_type = "lu" |
| 421 | elif 'UINT8' in struct_member['type']: |
| 422 | print_type = "hu" |
Chia-I Wu | 54ed079 | 2014-12-27 14:14:50 +0800 | [diff] [blame] | 423 | elif '_SIZE' in struct_member['type']: |
| 424 | print_type = "zu" |
| 425 | elif True in [ui_str in struct_member['type'] for ui_str in ['UINT', '_FLAGS', '_SAMPLE_MASK']]: |
Jon Ashburn | 154e270 | 2014-11-14 11:52:18 -0700 | [diff] [blame] | 426 | print_type = "u" |
| 427 | elif 'INT' in struct_member['type']: |
| 428 | print_type = "i" |
| 429 | elif struct_member['ptr']: |
| 430 | #cast_type = "" |
| 431 | pass |
| 432 | else: |
| 433 | #print("Unhandled struct type: %s" % struct_member['type']) |
| 434 | cast_type = "(void*)" |
| 435 | if print_array and struct_member['array']: |
| 436 | member_print_post = "[%u]" |
| 437 | array_index = " i," |
| 438 | member_post = "[i]" |
| 439 | print_out = "%%s%s%s = %%%s%s" % (member_name, member_print_post, print_type, postfix) # section of print that goes inside of quotes |
| 440 | print_arg = ", %s,%s %s(%s%s%s)%s" % (pre_var_name, array_index, cast_type, struct_var_name, struct_op, member_name, member_post) # section of print passed to portion in quotes |
| 441 | return (print_out, print_arg) |
| 442 | |
| 443 | def _generateStringHelperFunctions(self): |
| 444 | sh_funcs = [] |
| 445 | # TODO : Need a nice way to unify all of the different struct type print formatting code |
| 446 | for s in self.struct_dict: |
| 447 | p_out = "" |
| 448 | p_args = "" |
| 449 | sh_funcs.append('char* %s(const %s* pStruct, const char* prefix)\n{\n char* str;\n str = (char*)malloc(sizeof(char)*1024);\n sprintf(str, "' % (self._get_sh_func_name(s), typedef_fwd_dict[s])) |
| 450 | for m in sorted(self.struct_dict[s]): |
| 451 | (p_out1, p_args1) = self._get_struct_print_formatted(self.struct_dict[s][m]) |
| 452 | p_out += p_out1 |
| 453 | p_args += p_args1 |
| 454 | p_out += '"' |
| 455 | p_args += ");\n return str;\n}\n" |
| 456 | sh_funcs.append(p_out) |
| 457 | sh_funcs.append(p_args) |
| 458 | return "".join(sh_funcs) |
| 459 | |
| 460 | |
| 461 | def _genStructMemberPrint(self, member, s, array, struct_array): |
| 462 | (p_out, p_arg) = self._get_struct_print_formatted(self.struct_dict[s][member], pre_var_name="&m_dummy_prefix", struct_var_name="m_struct", struct_ptr=False, print_array=True) |
| 463 | extra_indent = "" |
| 464 | if array: |
| 465 | extra_indent = " " |
| 466 | if is_type(self.struct_dict[s][member]['type'], 'struct'): # print struct address for now |
| 467 | struct_array.insert(0, self.struct_dict[s][member]) |
| 468 | elif self.struct_dict[s][member]['ptr']: |
| 469 | # Special case for VOID* named "pNext" |
| 470 | if "VOID" in self.struct_dict[s][member]['type'] and "pNext" == self.struct_dict[s][member]['name']: |
| 471 | struct_array.insert(0, self.struct_dict[s][member]) |
| 472 | return (' %sprintf("%%*s %s", m_indent, ""%s);' % (extra_indent, p_out, p_arg), struct_array) |
| 473 | |
| 474 | def _generateDisplayDefinitions(self, s): |
| 475 | disp_def = [] |
| 476 | struct_array = [] |
| 477 | # Single-line struct print function |
| 478 | disp_def.append("// Output 'structname = struct_address' on a single line") |
| 479 | disp_def.append("void %s::display_single_txt()\n{" % self.get_class_name(s)) |
| 480 | disp_def.append(' printf(" %%*s%s = %%p", m_indent, "", (void*)m_origStructAddr);' % typedef_fwd_dict[s]) |
| 481 | disp_def.append("}\n") |
| 482 | # Private helper function to print struct members |
| 483 | disp_def.append("// Private helper function that displays the members of the wrapped struct") |
| 484 | disp_def.append("void %s::display_struct_members()\n{" % self.get_class_name(s)) |
| 485 | i_declared = False |
| 486 | for member in sorted(self.struct_dict[s]): |
| 487 | # TODO : Need to display each member based on its type |
| 488 | # TODO : Need to handle pNext which are structs, but of XGL_VOID* type |
| 489 | # Can grab struct type off of header of struct pointed to |
| 490 | # TODO : Handle Arrays |
| 491 | if self.struct_dict[s][member]['array']: |
| 492 | # Create for loop to print each element of array |
| 493 | if not i_declared: |
| 494 | disp_def.append(' uint32_t i;') |
| 495 | i_declared = True |
| 496 | disp_def.append(' for (i = 0; i<%s; i++) {' % self.struct_dict[s][member]['array_size']) |
| 497 | (return_str, struct_array) = self._genStructMemberPrint(member, s, True, struct_array) |
| 498 | disp_def.append(return_str) |
| 499 | disp_def.append(' }') |
| 500 | else: |
| 501 | (return_str, struct_array) = self._genStructMemberPrint(member, s, False, struct_array) |
| 502 | disp_def.append(return_str) |
| 503 | disp_def.append("}\n") |
| 504 | i_declared = False |
| 505 | # Basic print function to display struct members |
| 506 | disp_def.append("// Output all struct elements, each on their own line") |
| 507 | disp_def.append("void %s::display_txt()\n{" % self.get_class_name(s)) |
| 508 | disp_def.append(' printf("%%*s%s struct contents at %%p:\\n", m_indent, "", (void*)m_origStructAddr);' % typedef_fwd_dict[s]) |
| 509 | disp_def.append(' this->display_struct_members();') |
| 510 | disp_def.append("}\n") |
| 511 | # Advanced print function to display current struct and contents of any pointed-to structs |
| 512 | disp_def.append("// Output all struct elements, and for any structs pointed to, print complete contents") |
| 513 | disp_def.append("void %s::display_full_txt()\n{" % self.get_class_name(s)) |
| 514 | disp_def.append(' printf("%%*s%s struct contents at %%p:\\n", m_indent, "", (void*)m_origStructAddr);' % typedef_fwd_dict[s]) |
| 515 | disp_def.append(' this->display_struct_members();') |
| 516 | class_num = 0 |
| 517 | # TODO : Need to handle arrays of structs here |
| 518 | for ms in struct_array: |
| 519 | swc_name = "class%s" % str(class_num) |
| 520 | if ms['array']: |
| 521 | if not i_declared: |
| 522 | disp_def.append(' uint32_t i;') |
| 523 | i_declared = True |
| 524 | disp_def.append(' for (i = 0; i<%s; i++) {' % ms['array_size']) |
| 525 | #disp_def.append(" if (m_struct.%s[i]) {" % (ms['name'])) |
| 526 | disp_def.append(" %s %s(&(m_struct.%s[i]));" % (self.get_class_name(ms['type']), swc_name, ms['name'])) |
| 527 | disp_def.append(" %s.set_indent(m_indent + 4);" % (swc_name)) |
| 528 | disp_def.append(" %s.display_full_txt();" % (swc_name)) |
| 529 | #disp_def.append(' }') |
| 530 | disp_def.append(' }') |
| 531 | elif 'pNext' == ms['name']: |
| 532 | # Need some code trickery here |
| 533 | # I'm thinking have a generated function that takes pNext ptr value |
| 534 | # then it checks sType and in large switch statement creates appropriate |
| 535 | # wrapper class type and then prints contents |
| 536 | disp_def.append(" if (m_struct.%s) {" % (ms['name'])) |
| 537 | #disp_def.append(' printf("%*s This is where we would call dynamic print function\\n", m_indent, "");') |
| 538 | disp_def.append(' dynamic_display_full_txt(m_struct.%s, m_indent);' % (ms['name'])) |
| 539 | disp_def.append(" }") |
| 540 | else: |
| 541 | if ms['ptr']: |
| 542 | disp_def.append(" if (m_struct.%s) {" % (ms['name'])) |
| 543 | disp_def.append(" %s %s(m_struct.%s);" % (self.get_class_name(ms['type']), swc_name, ms['name'])) |
| 544 | else: |
| 545 | disp_def.append(" if (&m_struct.%s) {" % (ms['name'])) |
| 546 | disp_def.append(" %s %s(&m_struct.%s);" % (self.get_class_name(ms['type']), swc_name, ms['name'])) |
| 547 | disp_def.append(" %s.set_indent(m_indent + 4);" % (swc_name)) |
| 548 | disp_def.append(" %s.display_full_txt();\n }" % (swc_name)) |
| 549 | class_num += 1 |
| 550 | disp_def.append("}\n") |
| 551 | return "\n".join(disp_def) |
| 552 | |
| 553 | def _generateHeader(self): |
| 554 | header = [] |
| 555 | header.append("//#includes, #defines, globals and such...\n") |
| 556 | for f in self.include_headers: |
| 557 | header.append("#include <%s>\n" % f) |
| 558 | return "".join(header) |
| 559 | |
| 560 | # Declarations |
| 561 | def _generateConstructorDeclarations(self, s): |
| 562 | constructors = [] |
| 563 | constructors.append(" %s();\n" % self.get_class_name(s)) |
| 564 | constructors.append(" %s(%s* pInStruct);\n" % (self.get_class_name(s), typedef_fwd_dict[s])) |
| 565 | constructors.append(" %s(const %s* pInStruct);\n" % (self.get_class_name(s), typedef_fwd_dict[s])) |
| 566 | return "".join(constructors) |
| 567 | |
| 568 | def _generateDestructorDeclarations(self, s): |
| 569 | return " virtual ~%s();\n" % self.get_class_name(s) |
| 570 | |
| 571 | def _generateDisplayDeclarations(self, s): |
| 572 | return " void display_txt();\n void display_single_txt();\n void display_full_txt();\n" |
| 573 | |
| 574 | def _generateGetSetDeclarations(self, s): |
| 575 | get_set = [] |
| 576 | get_set.append(" void set_indent(uint32_t indent) { m_indent = indent; }\n") |
| 577 | for member in sorted(self.struct_dict[s]): |
| 578 | # TODO : Skipping array set/get funcs for now |
| 579 | if self.struct_dict[s][member]['array']: |
| 580 | continue |
| 581 | get_set.append(" %s get_%s() { return m_struct.%s; }\n" % (self.struct_dict[s][member]['full_type'], self.struct_dict[s][member]['name'], self.struct_dict[s][member]['name'])) |
| 582 | if not self.struct_dict[s][member]['const']: |
| 583 | get_set.append(" void set_%s(%s inValue) { m_struct.%s = inValue; }\n" % (self.struct_dict[s][member]['name'], self.struct_dict[s][member]['full_type'], self.struct_dict[s][member]['name'])) |
| 584 | return "".join(get_set) |
| 585 | |
| 586 | def _generatePrivateMembers(self, s): |
| 587 | priv = [] |
| 588 | priv.append("\nprivate:\n") |
| 589 | priv.append(" %s m_struct;\n" % typedef_fwd_dict[s]) |
| 590 | priv.append(" const %s* m_origStructAddr;\n" % typedef_fwd_dict[s]) |
| 591 | priv.append(" uint32_t m_indent;\n") |
| 592 | priv.append(" const char m_dummy_prefix;\n") |
| 593 | priv.append(" void display_struct_members();\n") |
| 594 | return "".join(priv) |
| 595 | |
| 596 | def _generateClassDeclaration(self): |
| 597 | class_decl = [] |
| 598 | for s in self.struct_dict: |
| 599 | class_decl.append("\n//class declaration") |
| 600 | class_decl.append("class %s\n{\npublic:" % self.get_class_name(s)) |
| 601 | class_decl.append(self._generateConstructorDeclarations(s)) |
| 602 | class_decl.append(self._generateDestructorDeclarations(s)) |
| 603 | class_decl.append(self._generateDisplayDeclarations(s)) |
| 604 | class_decl.append(self._generateGetSetDeclarations(s)) |
| 605 | class_decl.append(self._generatePrivateMembers(s)) |
| 606 | class_decl.append("};\n") |
| 607 | return "\n".join(class_decl) |
| 608 | |
| 609 | def _generateFooter(self): |
| 610 | return "\n//any footer info for class\n" |
| 611 | |
| 612 | class EnumCodeGen: |
| 613 | def __init__(self, enum_type_dict=None, enum_val_dict=None, typedef_fwd_dict=None, in_file=None, out_file=None): |
| 614 | self.et_dict = enum_type_dict |
| 615 | self.ev_dict = enum_val_dict |
| 616 | self.tf_dict = typedef_fwd_dict |
| 617 | self.in_file = in_file |
| 618 | self.out_file = out_file |
| 619 | self.efg = CommonFileGen(self.out_file) |
| 620 | |
| 621 | def generateStringHelper(self): |
| 622 | self.efg.setHeader(self._generateSHHeader()) |
| 623 | self.efg.setBody(self._generateSHBody()) |
| 624 | self.efg.generate() |
| 625 | |
| 626 | def _generateSHBody(self): |
| 627 | body = [] |
| 628 | # with open(self.out_file, "a") as hf: |
| 629 | # bet == base_enum_type, fet == final_enum_type |
| 630 | for bet in self.et_dict: |
| 631 | fet = self.tf_dict[bet] |
| 632 | body.append("static const char* string_%s(%s input_value)\n{\n switch ((%s)input_value)\n {\n" % (fet, fet, fet)) |
| 633 | for e in sorted(self.et_dict[bet]): |
| 634 | if (self.ev_dict[e]['unique']): |
| 635 | body.append(' case %s:\n return "%s";\n' % (e, e)) |
| 636 | body.append(' }\n return "Unhandled %s";\n}\n\n' % fet) |
| 637 | return "\n".join(body) |
| 638 | |
| 639 | def _generateSHHeader(self): |
| 640 | return "#pragma once\n\n#include <%s>\n\n" % self.in_file |
| 641 | |
| 642 | |
| 643 | class CMakeGen: |
| 644 | def __init__(self, struct_wrapper=None, out_dir=None): |
| 645 | self.sw = struct_wrapper |
| 646 | self.add_lib_file_list = self.sw.get_file_list() |
| 647 | self.out_dir = out_dir |
| 648 | self.out_file = os.path.join(self.out_dir, "CMakeLists.txt") |
| 649 | self.cmg = CommonFileGen(self.out_file) |
| 650 | |
| 651 | def generate(self): |
| 652 | self.cmg.setBody(self._generateBody()) |
| 653 | self.cmg.generate() |
| 654 | |
| 655 | def _generateBody(self): |
| 656 | body = [] |
| 657 | body.append("project(%s)" % os.path.basename(self.out_dir)) |
| 658 | body.append("cmake_minimum_required(VERSION 2.8)\n") |
| 659 | body.append("add_library(${PROJECT_NAME} %s)\n" % " ".join(self.add_lib_file_list)) |
| 660 | body.append('set(COMPILE_FLAGS "-fpermissive")') |
| 661 | body.append('set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COMPILE_FLAGS}")\n') |
| 662 | body.append("include_directories(${SRC_DIR}/thirdparty/${GEN_API}/inc/)\n") |
| 663 | body.append("target_include_directories (%s PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})\n" % os.path.basename(self.out_dir)) |
| 664 | return "\n".join(body) |
| 665 | |
| 666 | class GraphVizGen: |
| 667 | def __init__(self, struct_dict=None): |
| 668 | self.struc_dict = struct_dict |
| 669 | self.out_file = os.path.join(os.getcwd(), "struct_gv.dot") |
| 670 | self.gvg = CommonFileGen(self.out_file) |
| 671 | |
| 672 | def generate(self): |
| 673 | self.gvg.setHeader(self._generateHeader()) |
| 674 | self.gvg.setBody(self._generateBody()) |
| 675 | self.gvg.setFooter('}') |
| 676 | self.gvg.generate() |
| 677 | |
| 678 | def _generateHeader(self): |
| 679 | hdr = [] |
| 680 | hdr.append('digraph g {\ngraph [\nrankdir = "LR"\n];') |
| 681 | hdr.append('node [\nfontsize = "16"\nshape = "plaintext"\n];') |
| 682 | hdr.append('edge [\n];\n') |
| 683 | return "\n".join(hdr) |
| 684 | |
| 685 | def _generateBody(self): |
| 686 | body = [] |
| 687 | for s in self.struc_dict: |
| 688 | field_num = 1 |
| 689 | body.append('"%s" [\nlabel = <<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0"> <TR><TD COLSPAN="2" PORT="f0">%s</TD></TR>' % (s, typedef_fwd_dict[s])) |
| 690 | for m in sorted(self.struc_dict[s]): |
| 691 | body.append('<TR><TD PORT="f%i">%s</TD><TD PORT="f%i">%s</TD></TR>' % (field_num, self.struc_dict[s][m]['full_type'], field_num+1, self.struc_dict[s][m]['name'])) |
| 692 | field_num += 2 |
| 693 | body.append('</TABLE>>\n];\n') |
| 694 | return "".join(body) |
| 695 | |
| 696 | |
| 697 | def main(argv=None): |
| 698 | opts = handle_args() |
| 699 | # Parse input file and fill out global dicts |
| 700 | hfp = HeaderFileParser(opts.input_file) |
| 701 | hfp.parse() |
| 702 | # TODO : Don't want these to be global, see note at top about wrapper classes |
| 703 | global enum_val_dict |
| 704 | global enum_type_dict |
| 705 | global struct_dict |
| 706 | global typedef_fwd_dict |
| 707 | global typedef_rev_dict |
| 708 | global types_dict |
| 709 | enum_val_dict = hfp.get_enum_val_dict() |
| 710 | enum_type_dict = hfp.get_enum_type_dict() |
| 711 | struct_dict = hfp.get_struct_dict() |
| 712 | typedef_fwd_dict = hfp.get_typedef_fwd_dict() |
| 713 | typedef_rev_dict = hfp.get_typedef_rev_dict() |
| 714 | types_dict = hfp.get_types_dict() |
| 715 | #print(enum_val_dict) |
| 716 | #print(typedef_dict) |
| 717 | #print(struct_dict) |
| 718 | if (opts.abs_out_dir is not None): |
| 719 | enum_filename = os.path.join(opts.abs_out_dir, os.path.basename(opts.input_file).strip(".h")+"_string_helper.h") |
| 720 | else: |
| 721 | enum_filename = os.path.join(os.getcwd(), opts.rel_out_dir, os.path.basename(opts.input_file).strip(".h")+"_string_helper.h") |
| 722 | enum_filename = os.path.abspath(enum_filename) |
| 723 | if not os.path.exists(os.path.dirname(enum_filename)): |
| 724 | print("Creating output dir %s" % os.path.dirname(enum_filename)) |
| 725 | os.mkdir(os.path.dirname(enum_filename)) |
| 726 | print("Generating enum string helper to %s" % enum_filename) |
| 727 | eg = EnumCodeGen(enum_type_dict, enum_val_dict, typedef_fwd_dict, os.path.basename(opts.input_file), enum_filename) |
| 728 | eg.generateStringHelper() |
| 729 | #for struct in struct_dict: |
| 730 | #print(struct) |
| 731 | sw = StructWrapperGen(struct_dict, os.path.basename(opts.input_file).strip(".h"), os.path.dirname(enum_filename)) |
| 732 | #print(sw.get_class_name(struct)) |
| 733 | sw.set_include_headers([os.path.basename(opts.input_file),os.path.basename(enum_filename),"stdint.h","stdio.h","stdlib.h"]) |
| 734 | print("Generating struct wrapper header to %s" % sw.header_filename) |
| 735 | sw.generateHeader() |
| 736 | print("Generating struct wrapper class to %s" % sw.class_filename) |
| 737 | sw.generateBody() |
| 738 | sw.generateStringHelper() |
| 739 | cmg = CMakeGen(sw, os.path.dirname(enum_filename)) |
| 740 | cmg.generate() |
| 741 | print("DONE! Check out the file, but we're still early so assume something's probably not quite right. :)") |
| 742 | gv = GraphVizGen(struct_dict) |
| 743 | gv.generate() |
| 744 | #print(typedef_rev_dict) |
| 745 | #print(types_dict) |
| 746 | #recreate_structs() |
| 747 | |
| 748 | if __name__ == "__main__": |
| 749 | sys.exit(main()) |
| 750 | |
| 751 | |
| 752 | ## Example class for GR_APPLICATION_INFO struct |
| 753 | ##include <mantle.h> |
| 754 | # |
| 755 | #class gr_application_info_struct_wrapper { |
| 756 | #public: |
| 757 | # // Constructors |
| 758 | # gr_application_info_struct_wrapper(); |
| 759 | # gr_application_info_struct_wrapper(GR_APPLICATION_INFO* pInStruct); |
| 760 | # // Destructor |
| 761 | # virtual ~gr_application_info_struct_wrapper(); |
| 762 | # |
| 763 | # void display_txt() |
| 764 | # // get functions |
| 765 | # // set functions for every non-const struct member |
| 766 | # |
| 767 | #private: |
| 768 | # GR_APPLICATION_INFO m_struct; |
| 769 | #}; |
| 770 | # |
| 771 | #gr_application_info_struct_wrapper::gr_application_info_struct_wrapper() : m_struct() {} |
| 772 | # |
| 773 | #// Output struct address on single line |
| 774 | #gr_application_info_struct_wrapper::display_single_txt() |
| 775 | #{ |
| 776 | # printf(" GR_APPLICATION_INFO = %p", &m_struct); |
| 777 | #} |
| 778 | #// Output struct in txt format |
| 779 | #gr_application_info_struct_wrapper::display_txt() |
| 780 | #{ |
| 781 | # printf("GR_APPLICATION_INFO struct contents:\n"); |
| 782 | # printf(" pAppName: %s\n", m_struct.pAppName); |
| 783 | # printf(" appVersion: %i\n", m_struct.appVersion); |
| 784 | # printf(" pEngineNmae: %s\n", m_struct.pEngineName); |
| 785 | # printf(" engineVersion: %i\n", m_struct.engineVersion); |
| 786 | # printf(" apiVersion: %i\n", m_struct.apiVersion); |
| 787 | #} |
| 788 | #// Output struct including detailed info on pointed-to structs |
| 789 | #gr_application_info_struct_wrapper::display_full_txt() |
| 790 | #{ |
| 791 | # |
| 792 | # printf("%*s%GR_APPLICATION_INFO struct contents:\n", indent, ""); |
| 793 | # printf(" pAppName: %s\n", m_struct.pAppName); |
| 794 | # printf(" appVersion: %i\n", m_struct.appVersion); |
| 795 | # printf(" pEngineNmae: %s\n", m_struct.pEngineName); |
| 796 | # printf(" engineVersion: %i\n", m_struct.engineVersion); |
| 797 | # printf(" apiVersion: %i\n", m_struct.apiVersion); |
| 798 | #} |
| 799 | |
| 800 | |
| 801 | # Example of helper function to pretty-print enum info |
| 802 | #static const char* string_GR_RESULT_CODE(GR_RESULT result) |
| 803 | #{ |
| 804 | # switch ((GR_RESULT_CODE)result) |
| 805 | # { |
| 806 | # // Return codes for successful operation execution |
| 807 | # case GR_SUCCESS: |
| 808 | # return "GR_SUCCESS"; |
| 809 | # case GR_UNSUPPORTED: |
| 810 | # return "GR_UNSUPPORTED"; |
| 811 | # case GR_NOT_READY: |
| 812 | # return "GR_NOT_READY"; |
| 813 | # case GR_TIMEOUT: |
| 814 | # return "GR_TIMEOUT"; |
| 815 | # } |
| 816 | # return "Unhandled GR_RESULT_CODE"; |
| 817 | #} |
| 818 | |
| 819 | # Dynamic print function |
| 820 | # void dynamic_display_full_txt(XGL_STRUCTURE_TYPE sType, void* pStruct, uint32_t indent) |
| 821 | # { |
| 822 | # switch (sType) |
| 823 | # { |
| 824 | # case XGL_STRUCTURE_TYPE_COLOR_BLEND_STATE_CREATE_INFO: |
| 825 | # xgl_color_blend_state_create_info_struct_wrapper swc((XGL_COLOR_BLEND_STATE_CREATE_INFO*)pStruct); |
| 826 | # swc.set_indent(indent); |
| 827 | # swc.display_full_txt(); |
| 828 | # } |
| 829 | # } |