blob: 994b2b4e5ec6c2f163c6816f4097b53858c7a973 [file] [log] [blame]
Tobin Ehlis33267fd2014-11-10 16:03:19 -07001#!/usr/bin/env python3
2#
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06003# VK
Tobin Ehlis33267fd2014-11-10 16:03:19 -07004#
5# Copyright (C) 2014 LunarG, Inc.
6#
7# Permission is hereby granted, free of charge, to any person obtaining a
8# copy of this software and associated documentation files (the "Software"),
9# to deal in the Software without restriction, including without limitation
10# the rights to use, copy, modify, merge, publish, distribute, sublicense,
11# and/or sell copies of the Software, and to permit persons to whom the
12# Software is furnished to do so, subject to the following conditions:
13#
14# The above copyright notice and this permission notice shall be included
15# in all copies or substantial portions of the Software.
16#
17# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23# DEALINGS IN THE SOFTWARE.
Tobin Ehlis6442dca2014-10-22 15:13:53 -060024import argparse
25import os
26import sys
Tobin Ehlisa30e7e52015-07-06 14:02:36 -060027import vulkan
Tobin Ehlis08fafd02015-06-12 12:49:01 -060028from source_line_info import sourcelineinfo
Tobin Ehlis6442dca2014-10-22 15:13:53 -060029
Tobin Ehlis08fafd02015-06-12 12:49:01 -060030# vk_helper.py overview
31# This script generates code based on vulkan input header
32# It generate wrappers functions that can be used to display
Tobin Ehlis6442dca2014-10-22 15:13:53 -060033# structs in a human-readable txt format, as well as utility functions
34# to print enum values as strings
35
Tobin Ehlis6442dca2014-10-22 15:13:53 -060036def handle_args():
37 parser = argparse.ArgumentParser(description='Perform analysis of vogl trace.')
38 parser.add_argument('input_file', help='The input header file from which code will be generated.')
Mark Lobodzinski28b8f022015-08-27 15:30:29 -060039 parser.add_argument('--rel_out_dir', required=False, default='vktrace_gen', help='Path relative to exec path to write output files. Will be created if needed.')
Tobin Ehlis6442dca2014-10-22 15:13:53 -060040 parser.add_argument('--abs_out_dir', required=False, default=None, help='Absolute path to write output files. Will be created if needed.')
41 parser.add_argument('--gen_enum_string_helper', required=False, action='store_true', default=False, help='Enable generation of helper header file to print string versions of enums.')
42 parser.add_argument('--gen_struct_wrappers', required=False, action='store_true', default=False, help='Enable generation of struct wrapper classes.')
Jon Ashburnea65e492015-08-06 17:27:49 -060043 parser.add_argument('--gen_struct_sizes', required=False, action='store_true', default=False, help='Enable generation of struct sizes.')
Tobin Ehlis6442dca2014-10-22 15:13:53 -060044 parser.add_argument('--gen_cmake', required=False, action='store_true', default=False, help='Enable generation of cmake file for generated code.')
45 parser.add_argument('--gen_graphviz', required=False, action='store_true', default=False, help='Enable generation of graphviz dot file.')
46 #parser.add_argument('--test', action='store_true', default=False, help='Run simple test.')
47 return parser.parse_args()
48
49# TODO : Ideally these data structs would be opaque to user and could be wrapped
50# in their own class(es) to make them friendly for data look-up
51# Dicts for Data storage
52# enum_val_dict[value_name] = dict keys are the string enum value names for all enums
53# |-------->['type'] = the type of enum class into which the value falls
54# |-------->['val'] = the value assigned to this particular value_name
55# '-------->['unique'] = bool designating if this enum 'val' is unique within this enum 'type'
56enum_val_dict = {}
57# enum_type_dict['type'] = the type or class of of enum
58# '----->['val_name1', 'val_name2'...] = each type references a list of val_names within this type
59enum_type_dict = {}
60# struct_dict['struct_basename'] = the base (non-typedef'd) name of the struct
61# |->[<member_num>] = members are stored via their integer placement in the struct
62# | |->['name'] = string name of this struct member
63# ... |->['full_type'] = complete type qualifier for this member
64# |->['type'] = base type for this member
65# |->['ptr'] = bool indicating if this member is ptr
66# |->['const'] = bool indicating if this member is const
67# |->['struct'] = bool indicating if this member is a struct type
68# |->['array'] = bool indicating if this member is an array
Tobin Ehlisbd6a9162015-03-13 07:18:05 -060069# |->['dyn_array'] = bool indicating if member is a dynamically sized array
70# '->['array_size'] = For dyn_array, member name used to size array, else int size for static array
Tobin Ehlis6442dca2014-10-22 15:13:53 -060071struct_dict = {}
72# typedef_fwd_dict stores mapping from orig_type_name -> new_type_name
73typedef_fwd_dict = {}
74# typedef_rev_dict stores mapping from new_type_name -> orig_type_name
75typedef_rev_dict = {} # store new_name -> orig_name mapping
76# types_dict['id_name'] = identifier name will map to it's type
77# '---->'type' = currently either 'struct' or 'enum'
78types_dict = {} # store orig_name -> type mapping
79
80
81# Class that parses header file and generates data structures that can
82# Then be used for other tasks
83class HeaderFileParser:
84 def __init__(self, header_file=None):
85 self.header_file = header_file
86 # store header data in various formats, see above for more info
87 self.enum_val_dict = {}
88 self.enum_type_dict = {}
89 self.struct_dict = {}
90 self.typedef_fwd_dict = {}
91 self.typedef_rev_dict = {}
92 self.types_dict = {}
Tobin Ehlis5178bd72015-03-06 10:38:25 -070093 self.last_struct_count_name = ''
Mark Lobodzinski28b8f022015-08-27 15:30:29 -060094
Tobin Ehlis6442dca2014-10-22 15:13:53 -060095 def setHeaderFile(self, header_file):
96 self.header_file = header_file
97
98 def get_enum_val_dict(self):
99 return self.enum_val_dict
100
101 def get_enum_type_dict(self):
102 return self.enum_type_dict
103
104 def get_struct_dict(self):
105 return self.struct_dict
106
107 def get_typedef_fwd_dict(self):
108 return self.typedef_fwd_dict
109
110 def get_typedef_rev_dict(self):
111 return self.typedef_rev_dict
112
113 def get_types_dict(self):
114 return self.types_dict
115
116 # Parse header file into data structures
117 def parse(self):
118 # parse through the file, identifying different sections
119 parse_enum = False
120 parse_struct = False
121 member_num = 0
122 # TODO : Comment parsing is very fragile but handles 2 known files
123 block_comment = False
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700124 prev_count_name = ''
Ian Elliott7e40db92015-08-21 15:09:33 -0600125 exclude_struct_list = ['VkPlatformHandleXcbKHR', 'VkPlatformHandleX11KHR']
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600126 with open(self.header_file) as f:
127 for line in f:
128 if block_comment:
129 if '*/' in line:
130 block_comment = False
131 continue
132 if '/*' in line:
Courtney Goeltzenleuchter82e72392015-07-10 09:06:56 -0600133 if '*/' in line: # single line block comment
134 continue
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600135 block_comment = True
136 elif 0 == len(line.split()):
137 #print("Skipping empty line")
138 continue
139 elif line.split()[0].strip().startswith("//"):
Jon Ashburnfe6113c2015-01-09 09:11:44 -0700140 #print("Skipping commented line %s" % line)
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600141 continue
142 elif 'typedef enum' in line:
143 (ty_txt, en_txt, base_type) = line.strip().split(None, 2)
144 #print("Found ENUM type %s" % base_type)
Courtney Goeltzenleuchter82e72392015-07-10 09:06:56 -0600145 if '{' == base_type:
146 base_type = 'tmp_enum'
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600147 parse_enum = True
Jon Ashburnfe6113c2015-01-09 09:11:44 -0700148 default_enum_val = 0
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600149 self.types_dict[base_type] = 'enum'
Courtney Goeltzenleuchter82e72392015-07-10 09:06:56 -0600150 elif 'typedef struct' in line or 'typedef union' in line:
Jon Ashburnea65e492015-08-06 17:27:49 -0600151 if True in [ex_type in line for ex_type in exclude_struct_list]:
152 continue
Chia-I Wu44c99b62015-10-27 19:55:29 +0800153
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600154 (ty_txt, st_txt, base_type) = line.strip().split(None, 2)
Chia-I Wu44c99b62015-10-27 19:55:29 +0800155 if ' ' in base_type:
156 (ignored, base_type) = base_type.strip().split(None, 1)
157
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600158 #print("Found STRUCT type: %s" % base_type)
Cody Northrop22b7fae2015-08-11 11:21:48 -0600159 # Note: This really needs to be updated to handle one line struct definition, like
160 # typedef struct obj##_T { uint64_t handle; } obj;
161 if ('{' == base_type or not (' ' in base_type)):
Courtney Goeltzenleuchter82e72392015-07-10 09:06:56 -0600162 base_type = 'tmp_struct'
Cody Northrop22b7fae2015-08-11 11:21:48 -0600163 parse_struct = True
164 self.types_dict[base_type] = 'struct'
Courtney Goeltzenleuchter82e72392015-07-10 09:06:56 -0600165# elif 'typedef union' in line:
166# (ty_txt, st_txt, base_type) = line.strip().split(None, 2)
167# print("Found UNION type: %s" % base_type)
168# parse_struct = True
169# self.types_dict[base_type] = 'struct'
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600170 elif '}' in line and (parse_enum or parse_struct):
171 if len(line.split()) > 1: # deals with embedded union in one struct
172 parse_enum = False
173 parse_struct = False
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700174 self.last_struct_count_name = ''
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600175 member_num = 0
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600176 (cur_char, targ_type) = line.strip().split(None, 1)
Courtney Goeltzenleuchter82e72392015-07-10 09:06:56 -0600177 if 'tmp_struct' == base_type:
178 base_type = targ_type.strip(';')
Ian Elliott7e40db92015-08-21 15:09:33 -0600179 if True in [ex_type in base_type for ex_type in exclude_struct_list]:
180 del self.struct_dict['tmp_struct']
181 continue
Courtney Goeltzenleuchter82e72392015-07-10 09:06:56 -0600182 #print("Found Actual Struct type %s" % base_type)
183 self.struct_dict[base_type] = self.struct_dict['tmp_struct']
184 self.struct_dict.pop('tmp_struct', 0)
185 self.types_dict[base_type] = 'struct'
186 self.types_dict.pop('tmp_struct', 0)
187 elif 'tmp_enum' == base_type:
188 base_type = targ_type.strip(';')
189 #print("Found Actual ENUM type %s" % base_type)
190 for n in self.enum_val_dict:
191 if 'tmp_enum' == self.enum_val_dict[n]['type']:
192 self.enum_val_dict[n]['type'] = base_type
193# self.enum_val_dict[base_type] = self.enum_val_dict['tmp_enum']
194# self.enum_val_dict.pop('tmp_enum', 0)
195 self.enum_type_dict[base_type] = self.enum_type_dict['tmp_enum']
196 self.enum_type_dict.pop('tmp_enum', 0)
197 self.types_dict[base_type] = 'enum'
198 self.types_dict.pop('tmp_enum', 0)
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600199 self.typedef_fwd_dict[base_type] = targ_type.strip(';')
200 self.typedef_rev_dict[targ_type.strip(';')] = base_type
Courtney Goeltzenleuchter95487bc2015-04-14 18:48:46 -0600201 #print("fwd_dict: %s = %s" % (base_type, targ_type))
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600202 elif parse_enum:
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -0600203 #if 'VK_MAX_ENUM' not in line and '{' not in line:
Courtney Goeltzenleuchter82e72392015-07-10 09:06:56 -0600204 if True not in [ens in line for ens in ['{', '_MAX_ENUM', '_BEGIN_RANGE', '_END_RANGE', '_NUM = ', '_ENUM_RANGE']]:
Jon Ashburnfe6113c2015-01-09 09:11:44 -0700205 self._add_enum(line, base_type, default_enum_val)
206 default_enum_val += 1
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600207 elif parse_struct:
208 if ';' in line:
209 self._add_struct(line, base_type, member_num)
210 member_num = member_num + 1
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600211
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600212 # populate enum dicts based on enum lines
Jon Ashburnfe6113c2015-01-09 09:11:44 -0700213 def _add_enum(self, line_txt, enum_type, def_enum_val):
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600214 #print("Parsing enum line %s" % line_txt)
Jon Ashburnfe6113c2015-01-09 09:11:44 -0700215 if '=' in line_txt:
216 (enum_name, eq_char, enum_val) = line_txt.split(None, 2)
217 else:
218 enum_name = line_txt.split(',')[0]
219 enum_val = str(def_enum_val)
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600220 self.enum_val_dict[enum_name] = {}
221 self.enum_val_dict[enum_name]['type'] = enum_type
222 # strip comma and comment, then extra split in case of no comma w/ comments
223 enum_val = enum_val.strip().split(',', 1)[0]
224 self.enum_val_dict[enum_name]['val'] = enum_val.split()[0]
Tobin Ehlisd3350652015-04-22 13:59:43 -0600225 # Perform conversion of VK_BIT macro
226 if 'VK_BIT' in self.enum_val_dict[enum_name]['val']:
227 vk_bit_val = self.enum_val_dict[enum_name]['val']
228 bit_shift = int(vk_bit_val[vk_bit_val.find('(')+1:vk_bit_val.find(')')], 0)
229 self.enum_val_dict[enum_name]['val'] = str(1 << bit_shift)
230 else:
231 # account for negative values surrounded by parens
232 self.enum_val_dict[enum_name]['val'] = self.enum_val_dict[enum_name]['val'].strip(')').replace('-(', '-')
Tobin Ehlis43ebcac2014-12-05 12:13:07 -0700233 # Try to cast to int to determine if enum value is unique
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600234 try:
235 #print("ENUM val:", self.enum_val_dict[enum_name]['val'])
236 int(self.enum_val_dict[enum_name]['val'], 0)
237 self.enum_val_dict[enum_name]['unique'] = True
238 #print("ENUM has num value")
239 except ValueError:
240 self.enum_val_dict[enum_name]['unique'] = False
241 #print("ENUM is not a number value")
242 # Update enum_type_dict as well
243 if not enum_type in self.enum_type_dict:
244 self.enum_type_dict[enum_type] = []
245 self.enum_type_dict[enum_type].append(enum_name)
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700246
Jon Ashburnea65e492015-08-06 17:27:49 -0600247 # Return True if struct member is a dynamic array
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700248 # RULES : This is a bit quirky based on the API
249 # NOTE : Changes in API spec may cause these rules to change
250 # 1. There must be a previous uint var w/ 'count' in the name in the struct
251 # 2. Dynam array must have 'const' and '*' qualifiers
252 # 3a. Name of dynam array must end in 's' char OR
253 # 3b. Name of count var minus 'count' must be contained in name of dynamic array
254 def _is_dynamic_array(self, full_type, name):
255 if '' != self.last_struct_count_name:
256 if 'const' in full_type and '*' in full_type:
257 if name.endswith('s') or self.last_struct_count_name.lower().replace('count', '') in name.lower():
258 return True
Chia-I Wud50a7d72015-10-26 20:48:51 +0800259
260 # VkWriteDescriptorSet
261 if self.last_struct_count_name == "descriptorCount":
262 return True
263
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700264 return False
265
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600266 # populate struct dicts based on struct lines
267 # TODO : Handle ":" bitfield, "**" ptr->ptr and "const type*const*"
268 def _add_struct(self, line_txt, struct_type, num):
269 #print("Parsing struct line %s" % line_txt)
Courtney Goeltzenleuchter82e72392015-07-10 09:06:56 -0600270 if '{' == struct_type:
271 print("Parsing struct '{' w/ line %s" % line_txt)
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600272 if not struct_type in self.struct_dict:
273 self.struct_dict[struct_type] = {}
274 members = line_txt.strip().split(';', 1)[0] # first strip semicolon & comments
275 # TODO : Handle bitfields more correctly
276 members = members.strip().split(':', 1)[0] # strip bitfield element
277 (member_type, member_name) = members.rsplit(None, 1)
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700278 # Store counts to help recognize and size dynamic arrays
Tobin Ehlisb4934382015-04-15 16:01:16 -0600279 if 'count' in member_name.lower() and 'samplecount' != member_name.lower() and 'uint' in member_type:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700280 self.last_struct_count_name = member_name
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600281 self.struct_dict[struct_type][num] = {}
282 self.struct_dict[struct_type][num]['full_type'] = member_type
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700283 self.struct_dict[struct_type][num]['dyn_array'] = False
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600284 if '*' in member_type:
285 self.struct_dict[struct_type][num]['ptr'] = True
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700286 # TODO : Need more general purpose way here to reduce down to basic type
287 member_type = member_type.replace(' const*', '')
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600288 member_type = member_type.strip('*')
289 else:
290 self.struct_dict[struct_type][num]['ptr'] = False
291 if 'const' in member_type:
292 self.struct_dict[struct_type][num]['const'] = True
Courtney Goeltzenleuchter95487bc2015-04-14 18:48:46 -0600293 member_type = member_type.replace('const', '').strip()
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600294 else:
295 self.struct_dict[struct_type][num]['const'] = False
Tobin Ehlis5a487e52014-11-11 12:28:12 -0700296 # TODO : There is a bug here where it seems that at the time we do this check,
297 # the data is not in the types or typedef_rev_dict, so we never pass this if check
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600298 if is_type(member_type, 'struct'):
299 self.struct_dict[struct_type][num]['struct'] = True
300 else:
301 self.struct_dict[struct_type][num]['struct'] = False
302 self.struct_dict[struct_type][num]['type'] = member_type
303 if '[' in member_name:
304 (member_name, array_size) = member_name.split('[', 1)
Courtney Goeltzenleuchterf579fa62015-06-10 17:39:03 -0600305 if 'char' in member_type:
306 self.struct_dict[struct_type][num]['array'] = False
307 self.struct_dict[struct_type][num]['array_size'] = 0
308 self.struct_dict[struct_type][num]['ptr'] = True
309 else:
310 self.struct_dict[struct_type][num]['array'] = True
311 self.struct_dict[struct_type][num]['array_size'] = array_size.strip(']')
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700312 elif self._is_dynamic_array(self.struct_dict[struct_type][num]['full_type'], member_name):
313 #print("Found dynamic array %s of size %s" % (member_name, self.last_struct_count_name))
314 self.struct_dict[struct_type][num]['array'] = True
315 self.struct_dict[struct_type][num]['dyn_array'] = True
316 self.struct_dict[struct_type][num]['array_size'] = self.last_struct_count_name
Tobin Ehlisb8013a22015-02-26 12:57:08 -0700317 elif not 'array' in self.struct_dict[struct_type][num]:
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600318 self.struct_dict[struct_type][num]['array'] = False
319 self.struct_dict[struct_type][num]['array_size'] = 0
320 self.struct_dict[struct_type][num]['name'] = member_name
321
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700322# check if given identifier is of specified type_to_check
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600323def is_type(identifier, type_to_check):
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600324 if identifier in types_dict and type_to_check == types_dict[identifier]:
325 return True
326 if identifier in typedef_rev_dict:
327 new_id = typedef_rev_dict[identifier]
328 if new_id in types_dict and type_to_check == types_dict[new_id]:
329 return True
330 return False
331
332# This is a validation function to verify that we can reproduce the original structs
333def recreate_structs():
334 for struct_name in struct_dict:
335 sys.stdout.write("typedef struct %s\n{\n" % struct_name)
336 for mem_num in sorted(struct_dict[struct_name]):
337 sys.stdout.write(" ")
338 if struct_dict[struct_name][mem_num]['const']:
339 sys.stdout.write("const ")
340 #if struct_dict[struct_name][mem_num]['struct']:
341 # sys.stdout.write("struct ")
342 sys.stdout.write (struct_dict[struct_name][mem_num]['type'])
343 if struct_dict[struct_name][mem_num]['ptr']:
344 sys.stdout.write("*")
345 sys.stdout.write(" ")
346 sys.stdout.write(struct_dict[struct_name][mem_num]['name'])
347 if struct_dict[struct_name][mem_num]['array']:
348 sys.stdout.write("[")
349 sys.stdout.write(struct_dict[struct_name][mem_num]['array_size'])
350 sys.stdout.write("]")
351 sys.stdout.write(";\n")
352 sys.stdout.write("} ")
353 sys.stdout.write(typedef_fwd_dict[struct_name])
354 sys.stdout.write(";\n\n")
355
Courtney Goeltzenleuchter95487bc2015-04-14 18:48:46 -0600356#
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -0600357# TODO: Fix construction of struct name
Courtney Goeltzenleuchter95487bc2015-04-14 18:48:46 -0600358def get_struct_name_from_struct_type(struct_type):
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -0600359 # Note: All struct types are now camel-case
Courtney Goeltzenleuchter95487bc2015-04-14 18:48:46 -0600360 caps_struct_name = struct_type.replace("_STRUCTURE_TYPE", "")
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -0600361 char_idx = 0
362 struct_name = ''
363 for char in caps_struct_name:
364 if (0 == char_idx) or (caps_struct_name[char_idx-1] == '_'):
365 struct_name += caps_struct_name[char_idx]
366 elif (caps_struct_name[char_idx] == '_'):
367 pass
368 else:
369 struct_name += caps_struct_name[char_idx].lower()
370 char_idx += 1
Chia-I Wu3432a0c2015-10-27 18:04:07 +0800371
372 if struct_name.endswith("AllocInfo"):
373 struct_name = struct_name[:-9] + "AllocateInfo"
374 if struct_name.endswith("RasterStateCreateInfo"):
375 struct_name = struct_name[:-21] + "RasterizationStateCreateInfo"
376
Courtney Goeltzenleuchter95487bc2015-04-14 18:48:46 -0600377 return struct_name
378
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600379# class for writing common file elements
380# Here's how this class lays out a file:
381# COPYRIGHT
382# HEADER
383# BODY
384# FOOTER
385#
386# For each of these sections, there's a "set*" function
387# The class as a whole has a generate function which will write each section in order
388class CommonFileGen:
389 def __init__(self, filename=None, copyright_txt="", header_txt="", body_txt="", footer_txt=""):
390 self.filename = filename
391 self.contents = {'copyright': copyright_txt, 'header': header_txt, 'body': body_txt, 'footer': footer_txt}
392 # TODO : Set a default copyright & footer at least
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600393
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600394 def setFilename(self, filename):
395 self.filename = filename
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600396
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600397 def setCopyright(self, c):
398 self.contents['copyright'] = c
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600399
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600400 def setHeader(self, h):
401 self.contents['header'] = h
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600402
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600403 def setBody(self, b):
404 self.contents['body'] = b
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600405
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600406 def setFooter(self, f):
407 self.contents['footer'] = f
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600408
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600409 def generate(self):
410 #print("Generate to file %s" % self.filename)
411 with open(self.filename, "w") as f:
412 f.write(self.contents['copyright'])
413 f.write(self.contents['header'])
414 f.write(self.contents['body'])
415 f.write(self.contents['footer'])
416
417# class for writing a wrapper class for structures
418# The wrapper class wraps the structs and includes utility functions for
419# setting/getting member values and displaying the struct data in various formats
420class StructWrapperGen:
421 def __init__(self, in_struct_dict, prefix, out_dir):
422 self.struct_dict = in_struct_dict
423 self.include_headers = []
Jon Ashburnea65e492015-08-06 17:27:49 -0600424 self.lineinfo = sourcelineinfo()
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600425 self.api = prefix
Courtney Goeltzenleuchterdba79982015-04-14 16:30:53 -0600426 if prefix.lower() == "vulkan":
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -0600427 self.api_prefix = "vk"
428 else:
429 self.api_prefix = prefix
430 self.header_filename = os.path.join(out_dir, self.api_prefix+"_struct_wrappers.h")
431 self.class_filename = os.path.join(out_dir, self.api_prefix+"_struct_wrappers.cpp")
432 self.string_helper_filename = os.path.join(out_dir, self.api_prefix+"_struct_string_helper.h")
433 self.string_helper_no_addr_filename = os.path.join(out_dir, self.api_prefix+"_struct_string_helper_no_addr.h")
434 self.string_helper_cpp_filename = os.path.join(out_dir, self.api_prefix+"_struct_string_helper_cpp.h")
435 self.string_helper_no_addr_cpp_filename = os.path.join(out_dir, self.api_prefix+"_struct_string_helper_no_addr_cpp.h")
436 self.validate_helper_filename = os.path.join(out_dir, self.api_prefix+"_struct_validate_helper.h")
Tobin Ehlisd49efcb2014-11-25 17:43:26 -0700437 self.no_addr = False
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600438 self.hfg = CommonFileGen(self.header_filename)
439 self.cfg = CommonFileGen(self.class_filename)
440 self.shg = CommonFileGen(self.string_helper_filename)
Tobin Ehlis99f88672015-01-10 12:42:41 -0700441 self.shcppg = CommonFileGen(self.string_helper_cpp_filename)
Tobin Ehlis14ff0852014-12-17 17:44:50 -0700442 self.vhg = CommonFileGen(self.validate_helper_filename)
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -0600443 self.size_helper_filename = os.path.join(out_dir, self.api_prefix+"_struct_size_helper.h")
444 self.size_helper_c_filename = os.path.join(out_dir, self.api_prefix+"_struct_size_helper.c")
Tobin Ehlis60354772015-03-12 14:50:40 -0600445 self.size_helper_gen = CommonFileGen(self.size_helper_filename)
Peter Lohrmann4a8d8912015-04-03 11:43:06 -0700446 self.size_helper_c_gen = CommonFileGen(self.size_helper_c_filename)
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600447 #print(self.header_filename)
448 self.header_txt = ""
449 self.definition_txt = ""
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600450
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600451 def set_include_headers(self, include_headers):
452 self.include_headers = include_headers
453
Tobin Ehlisd49efcb2014-11-25 17:43:26 -0700454 def set_no_addr(self, no_addr):
455 self.no_addr = no_addr
456 if self.no_addr:
457 self.shg = CommonFileGen(self.string_helper_no_addr_filename)
Tobin Ehlis99f88672015-01-10 12:42:41 -0700458 self.shcppg = CommonFileGen(self.string_helper_no_addr_cpp_filename)
Tobin Ehlisd49efcb2014-11-25 17:43:26 -0700459 else:
460 self.shg = CommonFileGen(self.string_helper_filename)
Tobin Ehlis99f88672015-01-10 12:42:41 -0700461 self.shcppg = CommonFileGen(self.string_helper_cpp_filename)
Tobin Ehlisd49efcb2014-11-25 17:43:26 -0700462
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600463 # Return class name for given struct name
464 def get_class_name(self, struct_name):
465 class_name = struct_name.strip('_').lower() + "_struct_wrapper"
466 return class_name
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600467
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600468 def get_file_list(self):
469 return [os.path.basename(self.header_filename), os.path.basename(self.class_filename), os.path.basename(self.string_helper_filename)]
470
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600471 # Generate class header file
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600472 def generateHeader(self):
473 self.hfg.setCopyright(self._generateCopyright())
474 self.hfg.setHeader(self._generateHeader())
475 self.hfg.setBody(self._generateClassDeclaration())
476 self.hfg.setFooter(self._generateFooter())
477 self.hfg.generate()
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600478
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600479 # Generate class definition
480 def generateBody(self):
481 self.cfg.setCopyright(self._generateCopyright())
482 self.cfg.setHeader(self._generateCppHeader())
483 self.cfg.setBody(self._generateClassDefinition())
484 self.cfg.setFooter(self._generateFooter())
485 self.cfg.generate()
486
487 # Generate c-style .h file that contains functions for printing structs
488 def generateStringHelper(self):
489 print("Generating struct string helper")
490 self.shg.setCopyright(self._generateCopyright())
491 self.shg.setHeader(self._generateStringHelperHeader())
492 self.shg.setBody(self._generateStringHelperFunctions())
493 self.shg.generate()
494
Tobin Ehlis99f88672015-01-10 12:42:41 -0700495 # Generate cpp-style .h file that contains functions for printing structs
496 def generateStringHelperCpp(self):
497 print("Generating struct string helper cpp")
498 self.shcppg.setCopyright(self._generateCopyright())
499 self.shcppg.setHeader(self._generateStringHelperHeaderCpp())
500 self.shcppg.setBody(self._generateStringHelperFunctionsCpp())
501 self.shcppg.generate()
502
Tobin Ehlis14ff0852014-12-17 17:44:50 -0700503 # Generate c-style .h file that contains functions for printing structs
504 def generateValidateHelper(self):
505 print("Generating struct validate helper")
506 self.vhg.setCopyright(self._generateCopyright())
507 self.vhg.setHeader(self._generateValidateHelperHeader())
508 self.vhg.setBody(self._generateValidateHelperFunctions())
509 self.vhg.generate()
510
Tobin Ehlis60354772015-03-12 14:50:40 -0600511 def generateSizeHelper(self):
512 print("Generating struct size helper")
513 self.size_helper_gen.setCopyright(self._generateCopyright())
514 self.size_helper_gen.setHeader(self._generateSizeHelperHeader())
515 self.size_helper_gen.setBody(self._generateSizeHelperFunctions())
516 self.size_helper_gen.generate()
517
Peter Lohrmann4a8d8912015-04-03 11:43:06 -0700518 def generateSizeHelperC(self):
519 print("Generating struct size helper c")
520 self.size_helper_c_gen.setCopyright(self._generateCopyright())
521 self.size_helper_c_gen.setHeader(self._generateSizeHelperHeaderC())
522 self.size_helper_c_gen.setBody(self._generateSizeHelperFunctionsC())
523 self.size_helper_c_gen.generate()
524
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600525 def _generateCopyright(self):
Peter Lohrmann4a8d8912015-04-03 11:43:06 -0700526 copyright = []
527 copyright.append('/* THIS FILE IS GENERATED. DO NOT EDIT. */');
528 copyright.append('');
529 copyright.append('/*');
Ian Elliott0977abc2015-04-15 11:15:13 -0600530 copyright.append(' * Vulkan');
Peter Lohrmann4a8d8912015-04-03 11:43:06 -0700531 copyright.append(' *');
532 copyright.append(' * Copyright (C) 2014 LunarG, Inc.');
533 copyright.append(' *');
534 copyright.append(' * Permission is hereby granted, free of charge, to any person obtaining a');
535 copyright.append(' * copy of this software and associated documentation files (the "Software"),');
536 copyright.append(' * to deal in the Software without restriction, including without limitation');
537 copyright.append(' * the rights to use, copy, modify, merge, publish, distribute, sublicense,');
538 copyright.append(' * and/or sell copies of the Software, and to permit persons to whom the');
539 copyright.append(' * Software is furnished to do so, subject to the following conditions:');
540 copyright.append(' *');
541 copyright.append(' * The above copyright notice and this permission notice shall be included');
542 copyright.append(' * in all copies or substantial portions of the Software.');
543 copyright.append(' *');
544 copyright.append(' * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR');
545 copyright.append(' * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,');
546 copyright.append(' * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL');
547 copyright.append(' * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER');
548 copyright.append(' * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING');
549 copyright.append(' * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER');
550 copyright.append(' * DEALINGS IN THE SOFTWARE.');
551 copyright.append(' */');
552 copyright.append('');
553 return "\n".join(copyright)
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600554
555 def _generateCppHeader(self):
556 header = []
557 header.append("//#includes, #defines, globals and such...\n")
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -0600558 header.append("#include <stdio.h>\n#include <%s>\n#include <%s_enum_string_helper.h>\n" % (os.path.basename(self.header_filename), self.api_prefix))
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600559 return "".join(header)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600560
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600561 def _generateClassDefinition(self):
562 class_def = []
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600563 if 'vk' == self.api:
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600564 class_def.append(self._generateDynamicPrintFunctions())
Peter Lohrmann49ea1842015-03-30 16:29:56 -0700565 for s in sorted(self.struct_dict):
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600566 class_def.append("\n// %s class definition" % self.get_class_name(s))
567 class_def.append(self._generateConstructorDefinitions(s))
568 class_def.append(self._generateDestructorDefinitions(s))
569 class_def.append(self._generateDisplayDefinitions(s))
570 return "\n".join(class_def)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600571
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600572 def _generateConstructorDefinitions(self, s):
573 con_defs = []
574 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)))
575 # TODO : This is a shallow copy of ptrs
576 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]))
577 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]))
578 return "\n".join(con_defs)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600579
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600580 def _generateDestructorDefinitions(self, s):
581 return "%s::~%s() {}" % (self.get_class_name(s), self.get_class_name(s))
Mark Lobodzinski28b8f022015-08-27 15:30:29 -0600582
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600583 def _generateDynamicPrintFunctions(self):
584 dp_funcs = []
Mark Lobodzinski17caf572015-01-29 08:55:56 -0600585 dp_funcs.append("\nvoid dynamic_display_full_txt(const void* pStruct, uint32_t indent)\n{\n // Cast to APP_INFO ptr initially just to pull sType off struct")
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -0600586 dp_funcs.append(" VkStructureType sType = ((VkApplicationInfo*)pStruct)->sType;\n")
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600587 dp_funcs.append(" switch (sType)\n {")
588 for e in enum_type_dict:
589 class_num = 0
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -0600590 if "StructureType" in e:
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600591 for v in sorted(enum_type_dict[e]):
Courtney Goeltzenleuchter95487bc2015-04-14 18:48:46 -0600592 struct_name = get_struct_name_from_struct_type(v)
Chia-I Wu736324e2015-10-26 20:42:12 +0800593 if struct_name not in self.struct_dict:
594 continue
595
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600596 class_name = self.get_class_name(struct_name)
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600597 instance_name = "swc%i" % class_num
598 dp_funcs.append(" case %s:\n {" % (v))
599 dp_funcs.append(" %s %s((%s*)pStruct);" % (class_name, instance_name, struct_name))
600 dp_funcs.append(" %s.set_indent(indent);" % (instance_name))
601 dp_funcs.append(" %s.display_full_txt();" % (instance_name))
602 dp_funcs.append(" }")
603 dp_funcs.append(" break;")
604 class_num += 1
605 dp_funcs.append(" }")
606 dp_funcs.append("}\n")
607 return "\n".join(dp_funcs)
608
Tobin Ehlis14ff0852014-12-17 17:44:50 -0700609 def _get_func_name(self, struct, mid_str):
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -0600610 return "%s_%s_%s" % (self.api_prefix, mid_str, struct.lower().strip("_"))
Tobin Ehlis14ff0852014-12-17 17:44:50 -0700611
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600612 def _get_sh_func_name(self, struct):
Tobin Ehlis14ff0852014-12-17 17:44:50 -0700613 return self._get_func_name(struct, 'print')
614
615 def _get_vh_func_name(self, struct):
616 return self._get_func_name(struct, 'validate')
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600617
Tobin Ehlis60354772015-03-12 14:50:40 -0600618 def _get_size_helper_func_name(self, struct):
619 return self._get_func_name(struct, 'size')
620
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600621 # Return elements to create formatted string for given struct member
622 def _get_struct_print_formatted(self, struct_member, pre_var_name="prefix", postfix = "\\n", struct_var_name="pStruct", struct_ptr=True, print_array=False):
623 struct_op = "->"
624 if not struct_ptr:
625 struct_op = "."
626 member_name = struct_member['name']
627 print_type = "p"
628 cast_type = ""
629 member_post = ""
630 array_index = ""
631 member_print_post = ""
Tobin Ehlisb0497852015-02-11 14:24:02 -0700632 print_delimiter = "%"
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700633 if struct_member['array'] and 'char' in struct_member['type'].lower(): # just print char array as string
634 if member_name.startswith('pp'): # TODO : Only printing first element of dynam array of char* for now
635 member_post = "[0]"
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600636 print_type = "s"
637 print_array = False
638 elif struct_member['array'] and not print_array:
639 # Just print base address of array when not full print_array
640 cast_type = "(void*)"
641 elif is_type(struct_member['type'], 'enum'):
642 cast_type = "string_%s" % struct_member['type']
Jon Ashburnfe6113c2015-01-09 09:11:44 -0700643 if struct_member['ptr']:
644 struct_var_name = "*" + struct_var_name
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600645 print_type = "s"
646 elif is_type(struct_member['type'], 'struct'): # print struct address for now
647 cast_type = "(void*)"
648 if not struct_member['ptr']:
649 cast_type = "(void*)&"
Courtney Goeltzenleuchtercd2a0992015-07-09 11:44:38 -0600650 elif 'bool' in struct_member['type'].lower():
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600651 print_type = "s"
652 member_post = ' ? "TRUE" : "FALSE"'
Tobin Ehlis7e65d752015-01-15 17:51:52 -0700653 elif 'float' in struct_member['type']:
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600654 print_type = "f"
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -0600655 elif 'uint64' in struct_member['type'] or 'gpusize' in struct_member['type'].lower():
656 print_type = '" PRId64 "'
Tobin Ehlis7e65d752015-01-15 17:51:52 -0700657 elif 'uint8' in struct_member['type']:
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600658 print_type = "hu"
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -0600659 elif 'size' in struct_member['type'].lower():
Tobin Ehlisb0497852015-02-11 14:24:02 -0700660 print_type = '" PRINTF_SIZE_T_SPECIFIER "'
661 print_delimiter = ""
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -0600662 elif True in [ui_str.lower() in struct_member['type'].lower() for ui_str in ['uint', 'flags', 'samplemask']]:
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600663 print_type = "u"
Tobin Ehlis7e65d752015-01-15 17:51:52 -0700664 elif 'int' in struct_member['type']:
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600665 print_type = "i"
666 elif struct_member['ptr']:
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600667 pass
668 else:
669 #print("Unhandled struct type: %s" % struct_member['type'])
670 cast_type = "(void*)"
671 if print_array and struct_member['array']:
672 member_print_post = "[%u]"
673 array_index = " i,"
674 member_post = "[i]"
Tobin Ehlisb0497852015-02-11 14:24:02 -0700675 print_out = "%%s%s%s = %s%s%s" % (member_name, member_print_post, print_delimiter, print_type, postfix) # section of print that goes inside of quotes
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600676 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
Tobin Ehlisd49efcb2014-11-25 17:43:26 -0700677 if self.no_addr and "p" == print_type:
678 print_out = "%%s%s%s = addr\\n" % (member_name, member_print_post) # section of print that goes inside of quotes
679 print_arg = ", %s" % (pre_var_name)
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600680 return (print_out, print_arg)
681
682 def _generateStringHelperFunctions(self):
683 sh_funcs = []
Tobin Ehlis5a487e52014-11-11 12:28:12 -0700684 # We do two passes, first pass just generates prototypes for all the functsions
Tobin Ehlis291cd702015-01-20 09:48:48 -0700685 for s in sorted(self.struct_dict):
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700686 sh_funcs.append('char* %s(const %s* pStruct, const char* prefix);' % (self._get_sh_func_name(s), typedef_fwd_dict[s]))
687 sh_funcs.append('')
688 sh_funcs.append('#if defined(_WIN32)')
689 sh_funcs.append('// Microsoft did not implement C99 in Visual Studio; but started adding it with')
690 sh_funcs.append('// VS2013. However, VS2013 still did not have snprintf(). The following is a')
691 sh_funcs.append('// work-around.')
692 sh_funcs.append('#define snprintf _snprintf')
693 sh_funcs.append('#endif // _WIN32\n')
Peter Lohrmann49ea1842015-03-30 16:29:56 -0700694 for s in sorted(self.struct_dict):
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600695 p_out = ""
696 p_args = ""
Tobin Ehlis5a487e52014-11-11 12:28:12 -0700697 stp_list = [] # stp == "struct to print" a list of structs for this API call that should be printed as structs
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700698 # This pre-pass flags embedded structs and pNext
Tobin Ehlis291cd702015-01-20 09:48:48 -0700699 for m in sorted(self.struct_dict[s]):
Tobin Ehlis5a487e52014-11-11 12:28:12 -0700700 if 'pNext' == self.struct_dict[s][m]['name'] or is_type(self.struct_dict[s][m]['type'], 'struct'):
701 stp_list.append(self.struct_dict[s][m])
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700702 sh_funcs.append('char* %s(const %s* pStruct, const char* prefix)\n{\n char* str;' % (self._get_sh_func_name(s), typedef_fwd_dict[s]))
703 sh_funcs.append(" size_t len;")
Tobin Ehlis5a487e52014-11-11 12:28:12 -0700704 num_stps = len(stp_list);
705 total_strlen_str = ''
706 if 0 != num_stps:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700707 sh_funcs.append(" char* tmpStr;")
708 sh_funcs.append(' char* extra_indent = (char*)malloc(strlen(prefix) + 3);')
709 sh_funcs.append(' strcpy(extra_indent, " ");')
710 sh_funcs.append(' strncat(extra_indent, prefix, strlen(prefix));')
711 sh_funcs.append(' char* stp_strs[%i];' % num_stps)
Tobin Ehlis5a487e52014-11-11 12:28:12 -0700712 for index in range(num_stps):
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700713 # If it's an array, print all of the elements
714 # If it's a ptr, print thing it's pointing to
715 # Non-ptr struct case. Print the struct using its address
716 struct_deref = '&'
717 if 1 < stp_list[index]['full_type'].count('*'):
718 struct_deref = ''
Tobin Ehlis5a487e52014-11-11 12:28:12 -0700719 if (stp_list[index]['ptr']):
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700720 sh_funcs.append(' if (pStruct->%s) {' % stp_list[index]['name'])
Tobin Ehlis5a487e52014-11-11 12:28:12 -0700721 if 'pNext' == stp_list[index]['name']:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700722 sh_funcs.append(' tmpStr = dynamic_display((void*)pStruct->pNext, prefix);')
723 sh_funcs.append(' len = 256+strlen(tmpStr);')
724 sh_funcs.append(' stp_strs[%i] = (char*)malloc(len);' % index)
Tobin Ehlisd49efcb2014-11-25 17:43:26 -0700725 if self.no_addr:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700726 sh_funcs.append(' snprintf(stp_strs[%i], len, " %%spNext (addr)\\n%%s", prefix, tmpStr);' % index)
Tobin Ehlisd49efcb2014-11-25 17:43:26 -0700727 else:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700728 sh_funcs.append(' snprintf(stp_strs[%i], len, " %%spNext (%%p)\\n%%s", prefix, (void*)pStruct->pNext, tmpStr);' % index)
729 sh_funcs.append(' free(tmpStr);')
Tobin Ehlis5a487e52014-11-11 12:28:12 -0700730 else:
Tobin Ehlisb8013a22015-02-26 12:57:08 -0700731 if stp_list[index]['name'] in ['pImageViews', 'pBufferViews']:
732 # TODO : This is a quick hack to handle these arrays of ptrs
Courtney Goeltzenleuchtereeae16b2015-04-02 22:54:15 -0600733 sh_funcs.append(' tmpStr = %s(&pStruct->%s[0], extra_indent);' % (self._get_sh_func_name(stp_list[index]['type']), stp_list[index]['name']))
Tobin Ehlisb8013a22015-02-26 12:57:08 -0700734 else:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700735 sh_funcs.append(' tmpStr = %s(pStruct->%s, extra_indent);' % (self._get_sh_func_name(stp_list[index]['type']), stp_list[index]['name']))
736 sh_funcs.append(' len = 256+strlen(tmpStr)+strlen(prefix);')
737 sh_funcs.append(' stp_strs[%i] = (char*)malloc(len);' % (index))
Tobin Ehlisd49efcb2014-11-25 17:43:26 -0700738 if self.no_addr:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700739 sh_funcs.append(' snprintf(stp_strs[%i], len, " %%s%s (addr)\\n%%s", prefix, tmpStr);' % (index, stp_list[index]['name']))
Tobin Ehlisd49efcb2014-11-25 17:43:26 -0700740 else:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700741 sh_funcs.append(' snprintf(stp_strs[%i], len, " %%s%s (%%p)\\n%%s", prefix, (void*)pStruct->%s, tmpStr);' % (index, stp_list[index]['name'], stp_list[index]['name']))
742 sh_funcs.append(' }')
743 sh_funcs.append(" else\n stp_strs[%i] = \"\";" % (index))
744 elif stp_list[index]['array']:
745 sh_funcs.append(' tmpStr = %s(&pStruct->%s[0], extra_indent);' % (self._get_sh_func_name(stp_list[index]['type']), stp_list[index]['name']))
746 sh_funcs.append(' len = 256+strlen(tmpStr);')
747 sh_funcs.append(' stp_strs[%i] = (char*)malloc(len);' % (index))
Tobin Ehlisd49efcb2014-11-25 17:43:26 -0700748 if self.no_addr:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700749 sh_funcs.append(' snprintf(stp_strs[%i], len, " %%s%s[0] (addr)\\n%%s", prefix, tmpStr);' % (index, stp_list[index]['name']))
Tobin Ehlisd49efcb2014-11-25 17:43:26 -0700750 else:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700751 sh_funcs.append(' snprintf(stp_strs[%i], len, " %%s%s[0] (%%p)\\n%%s", prefix, (void*)&pStruct->%s[0], tmpStr);' % (index, stp_list[index]['name'], stp_list[index]['name']))
Tobin Ehlis5a487e52014-11-11 12:28:12 -0700752 else:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700753 sh_funcs.append(' tmpStr = %s(&pStruct->%s, extra_indent);' % (self._get_sh_func_name(stp_list[index]['type']), stp_list[index]['name']))
754 sh_funcs.append(' len = 256+strlen(tmpStr);')
755 sh_funcs.append(' stp_strs[%i] = (char*)malloc(len);' % (index))
Tobin Ehlisd49efcb2014-11-25 17:43:26 -0700756 if self.no_addr:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700757 sh_funcs.append(' snprintf(stp_strs[%i], len, " %%s%s (addr)\\n%%s", prefix, tmpStr);' % (index, stp_list[index]['name']))
Tobin Ehlisd49efcb2014-11-25 17:43:26 -0700758 else:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700759 sh_funcs.append(' snprintf(stp_strs[%i], len, " %%s%s (%%p)\\n%%s", prefix, (void*)&pStruct->%s, tmpStr);' % (index, stp_list[index]['name'], stp_list[index]['name']))
Tobin Ehlis5a487e52014-11-11 12:28:12 -0700760 total_strlen_str += 'strlen(stp_strs[%i]) + ' % index
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700761 sh_funcs.append(' len = %ssizeof(char)*1024;' % (total_strlen_str))
762 sh_funcs.append(' str = (char*)malloc(len);')
Courtney Goeltzenleuchterbbd0a362014-12-01 09:31:17 -0700763 sh_funcs.append(' snprintf(str, len, "')
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600764 for m in sorted(self.struct_dict[s]):
765 (p_out1, p_args1) = self._get_struct_print_formatted(self.struct_dict[s][m])
766 p_out += p_out1
767 p_args += p_args1
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600768 p_out += '"'
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700769 p_args += ");"
770 sh_funcs[-1] = '%s%s%s' % (sh_funcs[-1], p_out, p_args)
Tobin Ehlis5a487e52014-11-11 12:28:12 -0700771 if 0 != num_stps:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700772 sh_funcs.append(' for (int32_t stp_index = %i; stp_index >= 0; stp_index--) {' % (num_stps-1))
773 sh_funcs.append(' if (0 < strlen(stp_strs[stp_index])) {')
774 sh_funcs.append(' strncat(str, stp_strs[stp_index], strlen(stp_strs[stp_index]));')
775 sh_funcs.append(' free(stp_strs[stp_index]);')
776 sh_funcs.append(' }')
777 sh_funcs.append(' }')
778 sh_funcs.append(' free(extra_indent);')
779 sh_funcs.append(" return str;\n}")
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600780 # Add function to dynamically print out unknown struct
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700781 sh_funcs.append("char* dynamic_display(const void* pStruct, const char* prefix)\n{")
782 sh_funcs.append(" // Cast to APP_INFO ptr initially just to pull sType off struct")
783 sh_funcs.append(" if (pStruct == NULL) {")
784 sh_funcs.append(" return NULL;")
785 sh_funcs.append(" }")
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -0600786 sh_funcs.append(" VkStructureType sType = ((VkApplicationInfo*)pStruct)->sType;")
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700787 sh_funcs.append(' char indent[100];\n strcpy(indent, " ");\n strcat(indent, prefix);')
788 sh_funcs.append(" switch (sType)\n {")
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600789 for e in enum_type_dict:
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -0600790 if "StructureType" in e:
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600791 for v in sorted(enum_type_dict[e]):
Courtney Goeltzenleuchter95487bc2015-04-14 18:48:46 -0600792 struct_name = get_struct_name_from_struct_type(v)
Chia-I Wu736324e2015-10-26 20:42:12 +0800793 if struct_name not in self.struct_dict:
794 continue
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600795 print_func_name = self._get_sh_func_name(struct_name)
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700796 sh_funcs.append(' case %s:\n {' % (v))
797 sh_funcs.append(' return %s((%s*)pStruct, indent);' % (print_func_name, struct_name))
798 sh_funcs.append(' }')
799 sh_funcs.append(' break;')
800 sh_funcs.append(" default:")
801 sh_funcs.append(" return NULL;")
802 sh_funcs.append(" }")
Tobin Ehlis6442dca2014-10-22 15:13:53 -0600803 sh_funcs.append("}")
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700804 return "\n".join(sh_funcs)
Tobin Ehlis99f88672015-01-10 12:42:41 -0700805
806 def _generateStringHelperFunctionsCpp(self):
807 # declare str & tmp str
808 # declare array of stringstreams for every struct ptr in current struct
809 # declare array of stringstreams for every non-string element in current struct
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700810 # For every struct ptr, if non-Null, then set its string, else set to NULL str
811 # For every non-string element, set its string stream
Tobin Ehlis99f88672015-01-10 12:42:41 -0700812 # create and return final string
813 sh_funcs = []
814 # First generate prototypes for every struct
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -0600815 # XXX - REMOVE this comment
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600816 lineinfo = sourcelineinfo()
817 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis291cd702015-01-20 09:48:48 -0700818 for s in sorted(self.struct_dict):
Tobin Ehlis99f88672015-01-10 12:42:41 -0700819 sh_funcs.append('string %s(const %s* pStruct, const string prefix);' % (self._get_sh_func_name(s), typedef_fwd_dict[s]))
820 sh_funcs.append('\n')
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600821 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis291cd702015-01-20 09:48:48 -0700822 for s in sorted(self.struct_dict):
Tobin Ehlisce320942015-06-11 09:37:00 -0600823 num_non_enum_elems = [(is_type(self.struct_dict[s][elem]['type'], 'enum') and not self.struct_dict[s][elem]['ptr']) for elem in self.struct_dict[s]].count(False)
Tobin Ehlis99f88672015-01-10 12:42:41 -0700824 stp_list = [] # stp == "struct to print" a list of structs for this API call that should be printed as structs
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700825 # This pre-pass flags embedded structs and pNext
Tobin Ehlis291cd702015-01-20 09:48:48 -0700826 for m in sorted(self.struct_dict[s]):
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700827 if 'pNext' == self.struct_dict[s][m]['name'] or is_type(self.struct_dict[s][m]['type'], 'struct') or self.struct_dict[s][m]['array']:
Courtney Goeltzenleuchter82e72392015-07-10 09:06:56 -0600828 # TODO: This is a tmp workaround
829 if 'ppActiveLayerNames' not in self.struct_dict[s][m]['name']:
830 stp_list.append(self.struct_dict[s][m])
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600831 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis99f88672015-01-10 12:42:41 -0700832 sh_funcs.append('string %s(const %s* pStruct, const string prefix)\n{' % (self._get_sh_func_name(s), typedef_fwd_dict[s]))
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600833 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700834 indent = ' '
Tobin Ehlise78dbd82015-04-09 09:19:36 -0600835 sh_funcs.append('%susing namespace StreamControl;' % (indent))
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700836 sh_funcs.append('%sstring final_str;' % (indent))
837 sh_funcs.append('%sstring tmp_str;' % (indent))
838 sh_funcs.append('%sstring extra_indent = " " + prefix;' % (indent))
Tobin Ehlis291cd702015-01-20 09:48:48 -0700839 if (0 != num_non_enum_elems):
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700840 sh_funcs.append('%sstringstream ss[%u];' % (indent, num_non_enum_elems))
Tobin Ehlis99f88672015-01-10 12:42:41 -0700841 num_stps = len(stp_list)
Tobin Ehlisce320942015-06-11 09:37:00 -0600842 # First generate code for any embedded structs or arrays
Tobin Ehlis99f88672015-01-10 12:42:41 -0700843 if 0 < num_stps:
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700844 sh_funcs.append('%sstring stp_strs[%u];' % (indent, num_stps))
Tobin Ehlis99f88672015-01-10 12:42:41 -0700845 idx_ss_decl = False # Make sure to only decl this once
846 for index in range(num_stps):
847 addr_char = '&'
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700848 if 1 < stp_list[index]['full_type'].count('*'):
Tobin Ehlis99f88672015-01-10 12:42:41 -0700849 addr_char = ''
Tobin Ehlisf03e8cd2015-06-30 15:28:00 -0600850 if stp_list[index]['array']:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600851 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700852 if stp_list[index]['dyn_array']:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600853 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700854 array_count = 'pStruct->%s' % (stp_list[index]['array_size'])
855 else:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600856 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700857 array_count = '%s' % (stp_list[index]['array_size'])
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600858 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700859 sh_funcs.append('%sstp_strs[%u] = "";' % (indent, index))
860 if not idx_ss_decl:
861 sh_funcs.append('%sstringstream index_ss;' % (indent))
862 idx_ss_decl = True
Mark Lobodzinski74dfa182015-08-11 09:35:02 -0600863 if (stp_list[index]['name'] == 'pQueueFamilyIndices'):
864 sh_funcs.append('%sif (pStruct->sharingMode == VK_SHARING_MODE_CONCURRENT) {' % (indent))
865 indent += ' '
Tobin Ehlis793ad302015-04-03 12:01:11 -0600866 sh_funcs.append('%sif (pStruct->%s) {' % (indent, stp_list[index]['name']))
867 indent += ' '
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700868 sh_funcs.append('%sfor (uint32_t i = 0; i < %s; i++) {' % (indent, array_count))
Tobin Ehlis793ad302015-04-03 12:01:11 -0600869 indent += ' '
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700870 sh_funcs.append('%sindex_ss.str("");' % (indent))
871 sh_funcs.append('%sindex_ss << i;' % (indent))
Tobin Ehlisce320942015-06-11 09:37:00 -0600872 if is_type(stp_list[index]['type'], 'enum'):
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600873 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700874 addr_char = ''
Tobin Ehlisce320942015-06-11 09:37:00 -0600875 #value_print = 'string_%s(%spStruct->%s)' % (self.struct_dict[s][m]['type'], deref, self.struct_dict[s][m]['name'])
876 sh_funcs.append('%sss[%u] << string_%s(pStruct->%s[i]);' % (indent, index, stp_list[index]['type'], stp_list[index]['name']))
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700877 sh_funcs.append('%sstp_strs[%u] += " " + prefix + "%s[" + index_ss.str() + "] = " + ss[%u].str() + "\\n";' % (indent, index, stp_list[index]['name'], index))
Tobin Ehlisce320942015-06-11 09:37:00 -0600878 elif is_type(stp_list[index]['type'], 'struct'):
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600879 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700880 sh_funcs.append('%sss[%u] << %spStruct->%s[i];' % (indent, index, addr_char, stp_list[index]['name']))
881 sh_funcs.append('%stmp_str = %s(%spStruct->%s[i], extra_indent);' % (indent, self._get_sh_func_name(stp_list[index]['type']), addr_char, stp_list[index]['name']))
882 if self.no_addr:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600883 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700884 sh_funcs.append('%sstp_strs[%u] += " " + prefix + "%s[" + index_ss.str() + "] (addr)\\n" + tmp_str;' % (indent, index, stp_list[index]['name']))
885 else:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600886 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700887 sh_funcs.append('%sstp_strs[%u] += " " + prefix + "%s[" + index_ss.str() + "] (" + ss[%u].str() + ")\\n" + tmp_str;' % (indent, index, stp_list[index]['name'], index))
Tobin Ehlisce320942015-06-11 09:37:00 -0600888 else:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600889 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlisce320942015-06-11 09:37:00 -0600890 addr_char = ''
Courtney Goeltzenleuchter44981552015-10-23 15:48:32 -0600891 if stp_list[index]['type'] in vulkan.core.objects:
Tobin Ehlisa30e7e52015-07-06 14:02:36 -0600892 sh_funcs.append('%sstp_strs[%u] += " " + prefix + "%s[" + index_ss.str() + "].handle = " + ss[%u].str() + "\\n";' % (indent, index, stp_list[index]['name'], index))
893 else:
894 sh_funcs.append('%sss[%u] << %spStruct->%s[i];' % (indent, index, addr_char, stp_list[index]['name']))
895 sh_funcs.append('%sstp_strs[%u] += " " + prefix + "%s[" + index_ss.str() + "] = " + ss[%u].str() + "\\n";' % (indent, index, stp_list[index]['name'], index))
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600896 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700897 sh_funcs.append('%sss[%u].str("");' % (indent, index))
Tobin Ehlis793ad302015-04-03 12:01:11 -0600898 indent = indent[4:]
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700899 sh_funcs.append('%s}' % (indent))
Tobin Ehlisc62cb892015-04-17 13:26:33 -0600900 indent = indent[4:]
901 sh_funcs.append('%s}' % (indent))
Mark Lobodzinski74dfa182015-08-11 09:35:02 -0600902 #endif
903 if (stp_list[index]['name'] == 'pQueueFamilyIndices'):
904 indent = indent[4:]
905 sh_funcs.append('%s}' % (indent))
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700906 elif (stp_list[index]['ptr']):
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600907 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlisf03e8cd2015-06-30 15:28:00 -0600908 sh_funcs.append('%sif (pStruct->%s) {' % (indent, stp_list[index]['name']))
909 indent += ' '
Tobin Ehlis99f88672015-01-10 12:42:41 -0700910 if 'pNext' == stp_list[index]['name']:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600911 sh_funcs.append('%s' % lineinfo.get())
Mark Lobodzinski17caf572015-01-29 08:55:56 -0600912 sh_funcs.append(' tmp_str = dynamic_display((void*)pStruct->pNext, prefix);')
Tobin Ehlis99f88672015-01-10 12:42:41 -0700913 else:
Tobin Ehlisb8013a22015-02-26 12:57:08 -0700914 if stp_list[index]['name'] in ['pImageViews', 'pBufferViews']:
915 # TODO : This is a quick hack to handle these arrays of ptrs
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600916 sh_funcs.append('%s' % lineinfo.get())
Courtney Goeltzenleuchtereeae16b2015-04-02 22:54:15 -0600917 sh_funcs.append(' tmp_str = %s(&pStruct->%s[0], extra_indent);' % (self._get_sh_func_name(stp_list[index]['type']), stp_list[index]['name']))
Tobin Ehlisb8013a22015-02-26 12:57:08 -0700918 else:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600919 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlisb8013a22015-02-26 12:57:08 -0700920 sh_funcs.append(' tmp_str = %s(pStruct->%s, extra_indent);' % (self._get_sh_func_name(stp_list[index]['type']), stp_list[index]['name']))
Tobin Ehlis99f88672015-01-10 12:42:41 -0700921 sh_funcs.append(' ss[%u] << %spStruct->%s;' % (index, addr_char, stp_list[index]['name']))
922 if self.no_addr:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600923 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis99f88672015-01-10 12:42:41 -0700924 sh_funcs.append(' stp_strs[%u] = " " + prefix + "%s (addr)\\n" + tmp_str;' % (index, stp_list[index]['name']))
925 else:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600926 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis99f88672015-01-10 12:42:41 -0700927 sh_funcs.append(' stp_strs[%u] = " " + prefix + "%s (" + ss[%u].str() + ")\\n" + tmp_str;' % (index, stp_list[index]['name'], index))
928 sh_funcs.append(' ss[%u].str("");' % (index))
929 sh_funcs.append(' }')
930 sh_funcs.append(' else')
931 sh_funcs.append(' stp_strs[%u] = "";' % index)
Tobin Ehlis99f88672015-01-10 12:42:41 -0700932 else:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600933 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis99f88672015-01-10 12:42:41 -0700934 sh_funcs.append(' tmp_str = %s(&pStruct->%s, extra_indent);' % (self._get_sh_func_name(stp_list[index]['type']), stp_list[index]['name']))
935 sh_funcs.append(' ss[%u] << %spStruct->%s;' % (index, addr_char, stp_list[index]['name']))
936 if self.no_addr:
937 sh_funcs.append(' stp_strs[%u] = " " + prefix + "%s (addr)\\n" + tmp_str;' % (index, stp_list[index]['name']))
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600938 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis99f88672015-01-10 12:42:41 -0700939 else:
940 sh_funcs.append(' stp_strs[%u] = " " + prefix + "%s (" + ss[%u].str() + ")\\n" + tmp_str;' % (index, stp_list[index]['name'], index))
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600941 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis99f88672015-01-10 12:42:41 -0700942 sh_funcs.append(' ss[%u].str("");' % index)
Tobin Ehlisce320942015-06-11 09:37:00 -0600943 # Now print one-line info for all data members
Tobin Ehlis99f88672015-01-10 12:42:41 -0700944 index = 0
945 final_str = ''
946 for m in sorted(self.struct_dict[s]):
947 if not is_type(self.struct_dict[s][m]['type'], 'enum'):
948 if is_type(self.struct_dict[s][m]['type'], 'struct') and not self.struct_dict[s][m]['ptr']:
949 if self.no_addr:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600950 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis99f88672015-01-10 12:42:41 -0700951 sh_funcs.append(' ss[%u].str("addr");' % (index))
952 else:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600953 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis99f88672015-01-10 12:42:41 -0700954 sh_funcs.append(' ss[%u] << &pStruct->%s;' % (index, self.struct_dict[s][m]['name']))
Jon Ashburnc669cc62015-07-09 15:02:25 -0600955 elif self.struct_dict[s][m]['array']:
956 sh_funcs.append('%s' % lineinfo.get())
957 sh_funcs.append(' ss[%u] << (void*)pStruct->%s;' % (index, self.struct_dict[s][m]['name']))
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700958 elif 'bool' in self.struct_dict[s][m]['type'].lower():
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600959 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis99f88672015-01-10 12:42:41 -0700960 sh_funcs.append(' ss[%u].str(pStruct->%s ? "TRUE" : "FALSE");' % (index, self.struct_dict[s][m]['name']))
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700961 elif 'uint8' in self.struct_dict[s][m]['type'].lower():
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600962 sh_funcs.append('%s' % lineinfo.get())
Jon Ashburnc669cc62015-07-09 15:02:25 -0600963 sh_funcs.append(' ss[%u] << pStruct->%s;' % (index, self.struct_dict[s][m]['name']))
Tobin Ehlis17f45a62015-04-28 17:27:16 -0600964 elif 'void' in self.struct_dict[s][m]['type'].lower() and self.struct_dict[s][m]['ptr']:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600965 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis17f45a62015-04-28 17:27:16 -0600966 sh_funcs.append(' if (StreamControl::writeAddress)')
967 sh_funcs.append(' ss[%u] << pStruct->%s;' % (index, self.struct_dict[s][m]['name']))
968 sh_funcs.append(' else')
969 sh_funcs.append(' ss[%u].str("address");' % (index))
Tobin Ehlis99f88672015-01-10 12:42:41 -0700970 else:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600971 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis99f88672015-01-10 12:42:41 -0700972 (po, pa) = self._get_struct_print_formatted(self.struct_dict[s][m])
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700973 if "addr" in po: # or self.struct_dict[s][m]['ptr']:
Tobin Ehlis99f88672015-01-10 12:42:41 -0700974 sh_funcs.append(' ss[%u].str("addr");' % (index))
Tobin Ehlisa30e7e52015-07-06 14:02:36 -0600975 elif not self.struct_dict[s][m]['ptr'] and self.struct_dict[s][m]['type'] in vulkan.core.objects:
Chia-I Wue2fc5522015-10-26 20:04:44 +0800976 sh_funcs.append(' ss[%u] << pStruct->%s;' % (index, self.struct_dict[s][m]['name']))
Tobin Ehlis99f88672015-01-10 12:42:41 -0700977 else:
978 sh_funcs.append(' ss[%u] << pStruct->%s;' % (index, self.struct_dict[s][m]['name']))
979 value_print = 'ss[%u].str()' % index
980 index += 1
981 else:
Tobin Ehlisce320942015-06-11 09:37:00 -0600982 # For an non-empty array of enums just print address w/ note that array will be displayed below
Tobin Ehlis7e65d752015-01-15 17:51:52 -0700983 if self.struct_dict[s][m]['ptr']:
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600984 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlisce320942015-06-11 09:37:00 -0600985 sh_funcs.append(' if (pStruct->%s)' % (self.struct_dict[s][m]['name']))
986 sh_funcs.append(' ss[%u] << pStruct->%s << " (See individual array values below)";' % (index, self.struct_dict[s][m]['name']))
987 sh_funcs.append(' else')
988 sh_funcs.append(' ss[%u].str("NULL");' % (index))
989 value_print = 'ss[%u].str()' % index
990 index += 1
991 # For single enum just print the string representation
992 else:
993 value_print = 'string_%s(pStruct->%s)' % (self.struct_dict[s][m]['type'], self.struct_dict[s][m]['name'])
Tobin Ehlis99f88672015-01-10 12:42:41 -0700994 final_str += ' + prefix + "%s = " + %s + "\\n"' % (self.struct_dict[s][m]['name'], value_print)
995 final_str = final_str[3:] # strip off the initial ' + '
Tobin Ehlis5178bd72015-03-06 10:38:25 -0700996 if 0 != num_stps: # Append data for any embedded structs
Tobin Ehlis99f88672015-01-10 12:42:41 -0700997 final_str += " + %s" % " + ".join(['stp_strs[%u]' % n for n in reversed(range(num_stps))])
Tobin Ehlis08fafd02015-06-12 12:49:01 -0600998 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis99f88672015-01-10 12:42:41 -0700999 sh_funcs.append(' final_str = %s;' % final_str)
1000 sh_funcs.append(' return final_str;\n}')
Tobin Ehlis291cd702015-01-20 09:48:48 -07001001 # Add function to return a string value for input void*
Tobin Ehlis08fafd02015-06-12 12:49:01 -06001002 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis291cd702015-01-20 09:48:48 -07001003 sh_funcs.append("string string_convert_helper(const void* toString, const string prefix)\n{")
Tobin Ehlise78dbd82015-04-09 09:19:36 -06001004 sh_funcs.append(" using namespace StreamControl;")
Tobin Ehlis291cd702015-01-20 09:48:48 -07001005 sh_funcs.append(" stringstream ss;")
1006 sh_funcs.append(' ss << toString;')
1007 sh_funcs.append(' string final_str = prefix + ss.str();')
1008 sh_funcs.append(" return final_str;")
1009 sh_funcs.append("}")
Tobin Ehlis08fafd02015-06-12 12:49:01 -06001010 sh_funcs.append('%s' % lineinfo.get())
Tony Barbourb5d2c942015-07-14 13:34:05 -06001011 # Add function to return a string value for input uint64_t
1012 sh_funcs.append("string string_convert_helper(const uint64_t toString, const string prefix)\n{")
Tobin Ehlis08541742015-04-16 15:56:11 -06001013 sh_funcs.append(" using namespace StreamControl;")
1014 sh_funcs.append(" stringstream ss;")
1015 sh_funcs.append(' ss << toString;')
1016 sh_funcs.append(' string final_str = prefix + ss.str();')
1017 sh_funcs.append(" return final_str;")
1018 sh_funcs.append("}")
Tobin Ehlis08fafd02015-06-12 12:49:01 -06001019 sh_funcs.append('%s' % lineinfo.get())
Ian Elliott2b6b68a2015-08-07 14:11:14 -06001020 #### TODO: Get the following function moved to be in "vk_enum_string_helper.h"
Ian Elliott7e40db92015-08-21 15:09:33 -06001021 # Add function to return a string value for input VkSurfaceFormatKHR*
1022 sh_funcs.append("static inline const char* string_VkColorSpaceKHR(VkColorSpaceKHR input_value)\n{")
1023 sh_funcs.append(" switch ((VkColorSpaceKHR)input_value)")
Ian Elliott2b6b68a2015-08-07 14:11:14 -06001024 sh_funcs.append(" {")
Ian Elliott7e40db92015-08-21 15:09:33 -06001025 sh_funcs.append(" case VK_COLORSPACE_SRGB_NONLINEAR_KHR:")
1026 sh_funcs.append(" return \"VK_COLORSPACE_SRGB_NONLINEAR_KHR\";")
Ian Elliott2b6b68a2015-08-07 14:11:14 -06001027 sh_funcs.append(" default:")
Ian Elliott7e40db92015-08-21 15:09:33 -06001028 sh_funcs.append(" return \"Unhandled VkColorSpaceKHR\";")
Ian Elliott2b6b68a2015-08-07 14:11:14 -06001029 sh_funcs.append(" }")
1030 sh_funcs.append("}")
1031 sh_funcs.append('%s' % lineinfo.get())
Ian Elliott7e40db92015-08-21 15:09:33 -06001032 # Add function to return a string value for input VkSurfaceFormatKHR*
1033 sh_funcs.append("string string_convert_helper(VkSurfaceFormatKHR toString, const string prefix)\n{")
1034 sh_funcs.append(' string final_str = prefix + "format = " + string_VkFormat(toString.format) + "format = " + string_VkColorSpaceKHR(toString.colorSpace);')
Ian Elliott2b6b68a2015-08-07 14:11:14 -06001035 sh_funcs.append(" return final_str;")
1036 sh_funcs.append("}")
1037 sh_funcs.append('%s' % lineinfo.get())
Tobin Ehlis99f88672015-01-10 12:42:41 -07001038 # Add function to dynamically print out unknown struct
Mark Lobodzinski17caf572015-01-29 08:55:56 -06001039 sh_funcs.append("string dynamic_display(const void* pStruct, const string prefix)\n{")
Tobin Ehlis99f88672015-01-10 12:42:41 -07001040 sh_funcs.append(" // Cast to APP_INFO ptr initially just to pull sType off struct")
Ian Elliott82800022015-02-25 17:40:38 -07001041 sh_funcs.append(" if (pStruct == NULL) {\n")
Michael Lentinefb3b23b2015-10-23 12:40:50 -07001042 sh_funcs.append(" return string();")
Ian Elliott82800022015-02-25 17:40:38 -07001043 sh_funcs.append(" }\n")
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001044 sh_funcs.append(" VkStructureType sType = ((VkApplicationInfo*)pStruct)->sType;")
Tobin Ehlis99f88672015-01-10 12:42:41 -07001045 sh_funcs.append(' string indent = " ";')
1046 sh_funcs.append(' indent += prefix;')
1047 sh_funcs.append(" switch (sType)\n {")
1048 for e in enum_type_dict:
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001049 if "StructureType" in e:
Tobin Ehlis99f88672015-01-10 12:42:41 -07001050 for v in sorted(enum_type_dict[e]):
Courtney Goeltzenleuchter95487bc2015-04-14 18:48:46 -06001051 struct_name = get_struct_name_from_struct_type(v)
Chia-I Wu736324e2015-10-26 20:42:12 +08001052 if struct_name not in self.struct_dict:
1053 continue
Tobin Ehlis99f88672015-01-10 12:42:41 -07001054 print_func_name = self._get_sh_func_name(struct_name)
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001055 #sh_funcs.append('string %s(const %s* pStruct, const string prefix);' % (self._get_sh_func_name(s), typedef_fwd_dict[s]))
Tobin Ehlis99f88672015-01-10 12:42:41 -07001056 sh_funcs.append(' case %s:\n {' % (v))
1057 sh_funcs.append(' return %s((%s*)pStruct, indent);' % (print_func_name, struct_name))
1058 sh_funcs.append(' }')
1059 sh_funcs.append(' break;')
1060 sh_funcs.append(" default:")
Michael Lentinefb3b23b2015-10-23 12:40:50 -07001061 sh_funcs.append(" return string();")
Tobin Ehlis08fafd02015-06-12 12:49:01 -06001062 sh_funcs.append('%s' % lineinfo.get())
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001063 sh_funcs.append(" }")
Tobin Ehlis99f88672015-01-10 12:42:41 -07001064 sh_funcs.append("}")
1065 return "\n".join(sh_funcs)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001066
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001067 def _genStructMemberPrint(self, member, s, array, struct_array):
1068 (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)
1069 extra_indent = ""
1070 if array:
1071 extra_indent = " "
1072 if is_type(self.struct_dict[s][member]['type'], 'struct'): # print struct address for now
1073 struct_array.insert(0, self.struct_dict[s][member])
1074 elif self.struct_dict[s][member]['ptr']:
Tobin Ehlis7e65d752015-01-15 17:51:52 -07001075 # Special case for void* named "pNext"
1076 if "void" in self.struct_dict[s][member]['type'] and "pNext" == self.struct_dict[s][member]['name']:
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001077 struct_array.insert(0, self.struct_dict[s][member])
1078 return (' %sprintf("%%*s %s", m_indent, ""%s);' % (extra_indent, p_out, p_arg), struct_array)
1079
1080 def _generateDisplayDefinitions(self, s):
1081 disp_def = []
1082 struct_array = []
1083 # Single-line struct print function
1084 disp_def.append("// Output 'structname = struct_address' on a single line")
1085 disp_def.append("void %s::display_single_txt()\n{" % self.get_class_name(s))
1086 disp_def.append(' printf(" %%*s%s = %%p", m_indent, "", (void*)m_origStructAddr);' % typedef_fwd_dict[s])
1087 disp_def.append("}\n")
1088 # Private helper function to print struct members
1089 disp_def.append("// Private helper function that displays the members of the wrapped struct")
1090 disp_def.append("void %s::display_struct_members()\n{" % self.get_class_name(s))
1091 i_declared = False
1092 for member in sorted(self.struct_dict[s]):
1093 # TODO : Need to display each member based on its type
Mark Lobodzinski17caf572015-01-29 08:55:56 -06001094 # TODO : Need to handle pNext which are structs, but of void* type
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001095 # Can grab struct type off of header of struct pointed to
1096 # TODO : Handle Arrays
1097 if self.struct_dict[s][member]['array']:
1098 # Create for loop to print each element of array
1099 if not i_declared:
1100 disp_def.append(' uint32_t i;')
1101 i_declared = True
1102 disp_def.append(' for (i = 0; i<%s; i++) {' % self.struct_dict[s][member]['array_size'])
1103 (return_str, struct_array) = self._genStructMemberPrint(member, s, True, struct_array)
1104 disp_def.append(return_str)
1105 disp_def.append(' }')
1106 else:
1107 (return_str, struct_array) = self._genStructMemberPrint(member, s, False, struct_array)
1108 disp_def.append(return_str)
1109 disp_def.append("}\n")
1110 i_declared = False
1111 # Basic print function to display struct members
1112 disp_def.append("// Output all struct elements, each on their own line")
1113 disp_def.append("void %s::display_txt()\n{" % self.get_class_name(s))
1114 disp_def.append(' printf("%%*s%s struct contents at %%p:\\n", m_indent, "", (void*)m_origStructAddr);' % typedef_fwd_dict[s])
1115 disp_def.append(' this->display_struct_members();')
1116 disp_def.append("}\n")
1117 # Advanced print function to display current struct and contents of any pointed-to structs
1118 disp_def.append("// Output all struct elements, and for any structs pointed to, print complete contents")
1119 disp_def.append("void %s::display_full_txt()\n{" % self.get_class_name(s))
1120 disp_def.append(' printf("%%*s%s struct contents at %%p:\\n", m_indent, "", (void*)m_origStructAddr);' % typedef_fwd_dict[s])
1121 disp_def.append(' this->display_struct_members();')
1122 class_num = 0
1123 # TODO : Need to handle arrays of structs here
1124 for ms in struct_array:
1125 swc_name = "class%s" % str(class_num)
1126 if ms['array']:
1127 if not i_declared:
1128 disp_def.append(' uint32_t i;')
1129 i_declared = True
1130 disp_def.append(' for (i = 0; i<%s; i++) {' % ms['array_size'])
1131 #disp_def.append(" if (m_struct.%s[i]) {" % (ms['name']))
1132 disp_def.append(" %s %s(&(m_struct.%s[i]));" % (self.get_class_name(ms['type']), swc_name, ms['name']))
1133 disp_def.append(" %s.set_indent(m_indent + 4);" % (swc_name))
1134 disp_def.append(" %s.display_full_txt();" % (swc_name))
1135 #disp_def.append(' }')
1136 disp_def.append(' }')
1137 elif 'pNext' == ms['name']:
1138 # Need some code trickery here
1139 # I'm thinking have a generated function that takes pNext ptr value
1140 # then it checks sType and in large switch statement creates appropriate
1141 # wrapper class type and then prints contents
1142 disp_def.append(" if (m_struct.%s) {" % (ms['name']))
1143 #disp_def.append(' printf("%*s This is where we would call dynamic print function\\n", m_indent, "");')
1144 disp_def.append(' dynamic_display_full_txt(m_struct.%s, m_indent);' % (ms['name']))
1145 disp_def.append(" }")
1146 else:
1147 if ms['ptr']:
1148 disp_def.append(" if (m_struct.%s) {" % (ms['name']))
1149 disp_def.append(" %s %s(m_struct.%s);" % (self.get_class_name(ms['type']), swc_name, ms['name']))
1150 else:
1151 disp_def.append(" if (&m_struct.%s) {" % (ms['name']))
1152 disp_def.append(" %s %s(&m_struct.%s);" % (self.get_class_name(ms['type']), swc_name, ms['name']))
1153 disp_def.append(" %s.set_indent(m_indent + 4);" % (swc_name))
1154 disp_def.append(" %s.display_full_txt();\n }" % (swc_name))
1155 class_num += 1
1156 disp_def.append("}\n")
1157 return "\n".join(disp_def)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001158
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001159 def _generateStringHelperHeader(self):
1160 header = []
1161 header.append("//#includes, #defines, globals and such...\n")
1162 for f in self.include_headers:
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001163 if 'vk_enum_string_helper' not in f:
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001164 header.append("#include <%s>\n" % f)
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001165 header.append('#include "vk_enum_string_helper.h"\n\n// Function Prototypes\n')
Mark Lobodzinski17caf572015-01-29 08:55:56 -06001166 header.append("char* dynamic_display(const void* pStruct, const char* prefix);\n")
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001167 return "".join(header)
Tobin Ehlis99f88672015-01-10 12:42:41 -07001168
1169 def _generateStringHelperHeaderCpp(self):
1170 header = []
1171 header.append("//#includes, #defines, globals and such...\n")
1172 for f in self.include_headers:
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001173 if 'vk_enum_string_helper' not in f:
Tobin Ehlis99f88672015-01-10 12:42:41 -07001174 header.append("#include <%s>\n" % f)
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001175 header.append('#include "vk_enum_string_helper.h"\n')
Tobin Ehlis99f88672015-01-10 12:42:41 -07001176 header.append('using namespace std;\n\n// Function Prototypes\n')
Tobin Ehlise78dbd82015-04-09 09:19:36 -06001177 header.append('\n')
1178 header.append('namespace StreamControl\n')
1179 header.append('{\n')
1180 header.append('bool writeAddress = true;\n')
1181 header.append('template <typename T>\n')
1182 header.append('std::ostream& operator<< (std::ostream &out, T const* pointer)\n')
1183 header.append('{\n')
1184 header.append(' if(writeAddress)\n')
1185 header.append(' {\n')
1186 header.append(' out.operator<<(pointer);\n')
1187 header.append(' }\n')
1188 header.append(' else\n')
1189 header.append(' {\n')
1190 header.append(' std::operator<<(out, "address");\n')
1191 header.append(' }\n')
1192 header.append(' return out;\n')
1193 header.append('}\n')
1194 header.append('std::ostream& operator<<(std::ostream &out, char const*const s)\n')
1195 header.append('{\n')
1196 header.append(' return std::operator<<(out, s);\n')
1197 header.append('}\n')
1198 header.append('}\n')
1199 header.append('\n')
Mark Lobodzinski17caf572015-01-29 08:55:56 -06001200 header.append("string dynamic_display(const void* pStruct, const string prefix);\n")
Tobin Ehlis99f88672015-01-10 12:42:41 -07001201 return "".join(header)
1202
Tobin Ehlis14ff0852014-12-17 17:44:50 -07001203 def _generateValidateHelperFunctions(self):
1204 sh_funcs = []
1205 # We do two passes, first pass just generates prototypes for all the functsions
Peter Lohrmann49ea1842015-03-30 16:29:56 -07001206 for s in sorted(self.struct_dict):
Tobin Ehlis14ff0852014-12-17 17:44:50 -07001207 sh_funcs.append('uint32_t %s(const %s* pStruct);' % (self._get_vh_func_name(s), typedef_fwd_dict[s]))
1208 sh_funcs.append('\n')
Peter Lohrmann49ea1842015-03-30 16:29:56 -07001209 for s in sorted(self.struct_dict):
Tobin Ehlis14ff0852014-12-17 17:44:50 -07001210 sh_funcs.append('uint32_t %s(const %s* pStruct)\n{' % (self._get_vh_func_name(s), typedef_fwd_dict[s]))
1211 for m in sorted(self.struct_dict[s]):
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001212 # TODO : Need to handle arrays of enums like in VkRenderPassCreateInfo struct
Tobin Ehlis7e65d752015-01-15 17:51:52 -07001213 if is_type(self.struct_dict[s][m]['type'], 'enum') and not self.struct_dict[s][m]['ptr']:
Tobin Ehlis14ff0852014-12-17 17:44:50 -07001214 sh_funcs.append(' if (!validate_%s(pStruct->%s))\n return 0;' % (self.struct_dict[s][m]['type'], self.struct_dict[s][m]['name']))
Jon Ashburn27e02a62015-01-12 15:46:51 -07001215 # TODO : Need a little refinement to this code to make sure type of struct matches expected input (ptr, const...)
Tobin Ehlisce12ad62014-12-18 09:29:58 -07001216 if is_type(self.struct_dict[s][m]['type'], 'struct'):
1217 if (self.struct_dict[s][m]['ptr']):
Tobin Ehlisf4a3ac52015-02-24 15:39:04 -07001218 sh_funcs.append(' if (pStruct->%s && !%s((const %s*)pStruct->%s))\n return 0;' % (self.struct_dict[s][m]['name'], self._get_vh_func_name(self.struct_dict[s][m]['type']), self.struct_dict[s][m]['type'], self.struct_dict[s][m]['name']))
Tobin Ehlisce12ad62014-12-18 09:29:58 -07001219 else:
1220 sh_funcs.append(' if (!%s((const %s*)&pStruct->%s))\n return 0;' % (self._get_vh_func_name(self.struct_dict[s][m]['type']), self.struct_dict[s][m]['type'], self.struct_dict[s][m]['name']))
Tobin Ehlis14ff0852014-12-17 17:44:50 -07001221 sh_funcs.append(" return 1;\n}")
1222
1223 return "\n".join(sh_funcs)
1224
1225 def _generateValidateHelperHeader(self):
1226 header = []
1227 header.append("//#includes, #defines, globals and such...\n")
1228 for f in self.include_headers:
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001229 if 'vk_enum_validate_helper' not in f:
Tobin Ehlis14ff0852014-12-17 17:44:50 -07001230 header.append("#include <%s>\n" % f)
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001231 header.append('#include "vk_enum_validate_helper.h"\n\n// Function Prototypes\n')
Mark Lobodzinski17caf572015-01-29 08:55:56 -06001232 #header.append("char* dynamic_display(const void* pStruct, const char* prefix);\n")
Tobin Ehlis14ff0852014-12-17 17:44:50 -07001233 return "".join(header)
1234
Tobin Ehlis60354772015-03-12 14:50:40 -06001235 def _generateSizeHelperFunctions(self):
1236 sh_funcs = []
Peter Lohrmann4a8d8912015-04-03 11:43:06 -07001237 # just generates prototypes for all the functions
Peter Lohrmann49ea1842015-03-30 16:29:56 -07001238 for s in sorted(self.struct_dict):
Tobin Ehlis60354772015-03-12 14:50:40 -06001239 sh_funcs.append('size_t %s(const %s* pStruct);' % (self._get_size_helper_func_name(s), typedef_fwd_dict[s]))
Peter Lohrmann4a8d8912015-04-03 11:43:06 -07001240 return "\n".join(sh_funcs)
1241
1242
1243 def _generateSizeHelperFunctionsC(self):
1244 sh_funcs = []
1245 # generate function definitions
Peter Lohrmann49ea1842015-03-30 16:29:56 -07001246 for s in sorted(self.struct_dict):
Peter Lohrmann4a8d8912015-04-03 11:43:06 -07001247 skip_list = [] # Used when struct elements need to be skipped b/c size already accounted for
Tobin Ehlis60354772015-03-12 14:50:40 -06001248 sh_funcs.append('size_t %s(const %s* pStruct)\n{' % (self._get_size_helper_func_name(s), typedef_fwd_dict[s]))
1249 indent = ' '
1250 sh_funcs.append('%ssize_t structSize = 0;' % (indent))
1251 sh_funcs.append('%sif (pStruct) {' % (indent))
1252 indent = ' '
1253 sh_funcs.append('%sstructSize = sizeof(%s);' % (indent, typedef_fwd_dict[s]))
1254 i_decl = False
1255 for m in sorted(self.struct_dict[s]):
1256 if m in skip_list:
1257 continue
1258 if self.struct_dict[s][m]['dyn_array']:
1259 if self.struct_dict[s][m]['full_type'].count('*') > 1:
1260 if not is_type(self.struct_dict[s][m]['type'], 'struct') and not 'char' in self.struct_dict[s][m]['type'].lower():
Chia-I Wu3432a0c2015-10-27 18:04:07 +08001261 if 'ppMemoryBarriers' == self.struct_dict[s][m]['name']:
Tobin Ehlis04112922015-03-16 10:44:40 -06001262 # TODO : For now be conservative and consider all memBarrier ptrs as largest possible struct
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001263 sh_funcs.append('%sstructSize += pStruct->%s*(sizeof(%s*) + sizeof(VkImageMemoryBarrier));' % (indent, self.struct_dict[s][m]['array_size'], self.struct_dict[s][m]['type']))
Tobin Ehlis04112922015-03-16 10:44:40 -06001264 else:
1265 sh_funcs.append('%sstructSize += pStruct->%s*(sizeof(%s*) + sizeof(%s));' % (indent, self.struct_dict[s][m]['array_size'], self.struct_dict[s][m]['type'], self.struct_dict[s][m]['type']))
Tobin Ehlis60354772015-03-12 14:50:40 -06001266 else: # This is an array of char* or array of struct ptrs
1267 if not i_decl:
1268 sh_funcs.append('%suint32_t i = 0;' % (indent))
1269 i_decl = True
1270 sh_funcs.append('%sfor (i = 0; i < pStruct->%s; i++) {' % (indent, self.struct_dict[s][m]['array_size']))
1271 indent = ' '
1272 if is_type(self.struct_dict[s][m]['type'], 'struct'):
1273 sh_funcs.append('%sstructSize += (sizeof(%s*) + %s(pStruct->%s[i]));' % (indent, self.struct_dict[s][m]['type'], self._get_size_helper_func_name(self.struct_dict[s][m]['type']), self.struct_dict[s][m]['name']))
1274 else:
Tobin Ehlisbd6a9162015-03-13 07:18:05 -06001275 sh_funcs.append('%sstructSize += (sizeof(char*) + (sizeof(char) * (1 + strlen(pStruct->%s[i]))));' % (indent, self.struct_dict[s][m]['name']))
Tobin Ehlis60354772015-03-12 14:50:40 -06001276 indent = ' '
1277 sh_funcs.append('%s}' % (indent))
1278 else:
1279 if is_type(self.struct_dict[s][m]['type'], 'struct'):
1280 if not i_decl:
1281 sh_funcs.append('%suint32_t i = 0;' % (indent))
1282 i_decl = True
1283 sh_funcs.append('%sfor (i = 0; i < pStruct->%s; i++) {' % (indent, self.struct_dict[s][m]['array_size']))
1284 indent = ' '
1285 sh_funcs.append('%sstructSize += %s(&pStruct->%s[i]);' % (indent, self._get_size_helper_func_name(self.struct_dict[s][m]['type']), self.struct_dict[s][m]['name']))
1286 indent = ' '
1287 sh_funcs.append('%s}' % (indent))
1288 else:
1289 sh_funcs.append('%sstructSize += pStruct->%s*sizeof(%s);' % (indent, self.struct_dict[s][m]['array_size'], self.struct_dict[s][m]['type']))
1290 elif self.struct_dict[s][m]['ptr'] and 'pNext' != self.struct_dict[s][m]['name']:
1291 if 'char' in self.struct_dict[s][m]['type'].lower():
Tobin Ehlisbd6a9162015-03-13 07:18:05 -06001292 sh_funcs.append('%sstructSize += sizeof(%s)*(1+strlen(pStruct->%s));' % (indent, self.struct_dict[s][m]['type'], self.struct_dict[s][m]['name']))
Tobin Ehlis60354772015-03-12 14:50:40 -06001293 elif is_type(self.struct_dict[s][m]['type'], 'struct'):
1294 sh_funcs.append('%sstructSize += %s(pStruct->%s);' % (indent, self._get_size_helper_func_name(self.struct_dict[s][m]['type']), self.struct_dict[s][m]['name']))
Tobin Ehlis04112922015-03-16 10:44:40 -06001295 elif 'void' not in self.struct_dict[s][m]['type'].lower():
Tobin Ehlis60354772015-03-12 14:50:40 -06001296 sh_funcs.append('%sstructSize += sizeof(%s);' % (indent, self.struct_dict[s][m]['type']))
1297 elif 'size_t' == self.struct_dict[s][m]['type'].lower():
1298 sh_funcs.append('%sstructSize += pStruct->%s;' % (indent, self.struct_dict[s][m]['name']))
1299 skip_list.append(m+1)
1300 indent = ' '
1301 sh_funcs.append('%s}' % (indent))
1302 sh_funcs.append("%sreturn structSize;\n}" % (indent))
Tobin Ehlis04112922015-03-16 10:44:40 -06001303 # Now generate generic functions to loop over entire struct chain (or just handle single generic structs)
Ian Elliott7e40db92015-08-21 15:09:33 -06001304 if 'khr' not in self.header_filename and '_debug_' not in self.header_filename:
Jon Ashburnea65e492015-08-06 17:27:49 -06001305 for follow_chain in [True, False]:
1306 sh_funcs.append('%s' % self.lineinfo.get())
1307 if follow_chain:
1308 sh_funcs.append('size_t get_struct_chain_size(const void* pStruct)\n{')
1309 else:
1310 sh_funcs.append('size_t get_dynamic_struct_size(const void* pStruct)\n{')
1311 indent = ' '
1312 sh_funcs.append('%s// Just use VkApplicationInfo as struct until actual type is resolved' % (indent))
1313 sh_funcs.append('%sVkApplicationInfo* pNext = (VkApplicationInfo*)pStruct;' % (indent))
1314 sh_funcs.append('%ssize_t structSize = 0;' % (indent))
1315 if follow_chain:
1316 sh_funcs.append('%swhile (pNext) {' % (indent))
1317 indent = ' '
1318 sh_funcs.append('%sswitch (pNext->sType) {' % (indent))
1319 indent += ' '
1320 for e in enum_type_dict:
1321 if 'StructureType' in e:
1322 for v in sorted(enum_type_dict[e]):
1323 struct_name = get_struct_name_from_struct_type(v)
Chia-I Wu736324e2015-10-26 20:42:12 +08001324 if struct_name not in self.struct_dict:
1325 continue
1326
Jon Ashburnea65e492015-08-06 17:27:49 -06001327 sh_funcs.append('%scase %s:' % (indent, v))
1328 sh_funcs.append('%s{' % (indent))
1329 indent += ' '
1330 sh_funcs.append('%sstructSize += %s((%s*)pNext);' % (indent, self._get_size_helper_func_name(struct_name), struct_name))
1331 sh_funcs.append('%sbreak;' % (indent))
1332 indent = indent[:-4]
1333 sh_funcs.append('%s}' % (indent))
1334 sh_funcs.append('%sdefault:' % (indent))
Tobin Ehlis04112922015-03-16 10:44:40 -06001335 indent += ' '
Jon Ashburnea65e492015-08-06 17:27:49 -06001336 sh_funcs.append('%sassert(0);' % (indent))
1337 sh_funcs.append('%sstructSize += 0;' % (indent))
Tobin Ehlis04112922015-03-16 10:44:40 -06001338 indent = indent[:-4]
Tobin Ehlis04112922015-03-16 10:44:40 -06001339 indent = indent[:-4]
1340 sh_funcs.append('%s}' % (indent))
Jon Ashburnea65e492015-08-06 17:27:49 -06001341 if follow_chain:
1342 sh_funcs.append('%spNext = (VkApplicationInfo*)pNext->pNext;' % (indent))
1343 indent = indent[:-4]
1344 sh_funcs.append('%s}' % (indent))
1345 sh_funcs.append('%sreturn structSize;\n}' % indent)
Tobin Ehlis60354772015-03-12 14:50:40 -06001346 return "\n".join(sh_funcs)
1347
1348 def _generateSizeHelperHeader(self):
1349 header = []
1350 header.append("//#includes, #defines, globals and such...\n")
1351 for f in self.include_headers:
1352 header.append("#include <%s>\n" % f)
1353 header.append('\n// Function Prototypes\n')
1354 header.append("size_t get_struct_chain_size(const void* pStruct);\n")
Tobin Ehlis04112922015-03-16 10:44:40 -06001355 header.append("size_t get_dynamic_struct_size(const void* pStruct);\n")
Tobin Ehlis60354772015-03-12 14:50:40 -06001356 return "".join(header)
1357
Peter Lohrmann4a8d8912015-04-03 11:43:06 -07001358 def _generateSizeHelperHeaderC(self):
1359 header = []
Courtney Goeltzenleuchterdba79982015-04-14 16:30:53 -06001360 header.append('#include "vk_struct_size_helper.h"')
Ian Elliott7e40db92015-08-21 15:09:33 -06001361 header.append('#include "vk_ext_khr_swapchain.h"')
1362 header.append('#include "vk_ext_khr_device_swapchain.h"')
Peter Lohrmann4a8d8912015-04-03 11:43:06 -07001363 header.append('#include <string.h>')
1364 header.append('#include <assert.h>')
1365 header.append('\n// Function definitions\n')
1366 return "\n".join(header)
1367
1368
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001369 def _generateHeader(self):
1370 header = []
1371 header.append("//#includes, #defines, globals and such...\n")
1372 for f in self.include_headers:
1373 header.append("#include <%s>\n" % f)
1374 return "".join(header)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001375
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001376 # Declarations
1377 def _generateConstructorDeclarations(self, s):
1378 constructors = []
1379 constructors.append(" %s();\n" % self.get_class_name(s))
1380 constructors.append(" %s(%s* pInStruct);\n" % (self.get_class_name(s), typedef_fwd_dict[s]))
1381 constructors.append(" %s(const %s* pInStruct);\n" % (self.get_class_name(s), typedef_fwd_dict[s]))
1382 return "".join(constructors)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001383
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001384 def _generateDestructorDeclarations(self, s):
1385 return " virtual ~%s();\n" % self.get_class_name(s)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001386
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001387 def _generateDisplayDeclarations(self, s):
1388 return " void display_txt();\n void display_single_txt();\n void display_full_txt();\n"
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001389
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001390 def _generateGetSetDeclarations(self, s):
1391 get_set = []
1392 get_set.append(" void set_indent(uint32_t indent) { m_indent = indent; }\n")
1393 for member in sorted(self.struct_dict[s]):
1394 # TODO : Skipping array set/get funcs for now
1395 if self.struct_dict[s][member]['array']:
1396 continue
1397 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']))
1398 if not self.struct_dict[s][member]['const']:
1399 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']))
1400 return "".join(get_set)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001401
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001402 def _generatePrivateMembers(self, s):
1403 priv = []
1404 priv.append("\nprivate:\n")
1405 priv.append(" %s m_struct;\n" % typedef_fwd_dict[s])
1406 priv.append(" const %s* m_origStructAddr;\n" % typedef_fwd_dict[s])
1407 priv.append(" uint32_t m_indent;\n")
1408 priv.append(" const char m_dummy_prefix;\n")
1409 priv.append(" void display_struct_members();\n")
1410 return "".join(priv)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001411
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001412 def _generateClassDeclaration(self):
1413 class_decl = []
Peter Lohrmann49ea1842015-03-30 16:29:56 -07001414 for s in sorted(self.struct_dict):
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001415 class_decl.append("\n//class declaration")
1416 class_decl.append("class %s\n{\npublic:" % self.get_class_name(s))
1417 class_decl.append(self._generateConstructorDeclarations(s))
1418 class_decl.append(self._generateDestructorDeclarations(s))
1419 class_decl.append(self._generateDisplayDeclarations(s))
1420 class_decl.append(self._generateGetSetDeclarations(s))
1421 class_decl.append(self._generatePrivateMembers(s))
1422 class_decl.append("};\n")
1423 return "\n".join(class_decl)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001424
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001425 def _generateFooter(self):
1426 return "\n//any footer info for class\n"
1427
1428class EnumCodeGen:
Tobin Ehlis7c47fc42014-12-17 07:20:23 -07001429 def __init__(self, enum_type_dict=None, enum_val_dict=None, typedef_fwd_dict=None, in_file=None, out_sh_file=None, out_vh_file=None):
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001430 self.et_dict = enum_type_dict
1431 self.ev_dict = enum_val_dict
1432 self.tf_dict = typedef_fwd_dict
1433 self.in_file = in_file
Tobin Ehlis7c47fc42014-12-17 07:20:23 -07001434 self.out_sh_file = out_sh_file
1435 self.eshfg = CommonFileGen(self.out_sh_file)
1436 self.out_vh_file = out_vh_file
1437 self.evhfg = CommonFileGen(self.out_vh_file)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001438
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001439 def generateStringHelper(self):
Tobin Ehlis7c47fc42014-12-17 07:20:23 -07001440 self.eshfg.setHeader(self._generateSHHeader())
1441 self.eshfg.setBody(self._generateSHBody())
1442 self.eshfg.generate()
1443
1444 def generateEnumValidate(self):
1445 self.evhfg.setHeader(self._generateSHHeader())
Tobin Ehlis14ff0852014-12-17 17:44:50 -07001446 self.evhfg.setBody(self._generateVHBody())
Tobin Ehlis7c47fc42014-12-17 07:20:23 -07001447 self.evhfg.generate()
1448
1449 def _generateVHBody(self):
1450 body = []
Peter Lohrmann49ea1842015-03-30 16:29:56 -07001451 for bet in sorted(self.et_dict):
Tobin Ehlis7c47fc42014-12-17 07:20:23 -07001452 fet = self.tf_dict[bet]
Tobin Ehlis9d8ba362015-04-15 17:04:03 -06001453 body.append("static inline uint32_t validate_%s(%s input_value)\n{" % (fet, fet))
1454 # TODO : This is not ideal, but allows for flag combinations. Need more rigorous validation of realistic flag combinations
Tobin Ehlisd3350652015-04-22 13:59:43 -06001455 if 'flagbits' in bet.lower():
Tobin Ehlis9d8ba362015-04-15 17:04:03 -06001456 body.append(' if (input_value > (%s))' % (' | '.join(self.et_dict[bet])))
1457 body.append(' return 0;')
1458 body.append(' return 1;')
1459 body.append('}\n\n')
1460 else:
1461 body.append(' switch ((%s)input_value)\n {' % (fet))
1462 for e in sorted(self.et_dict[bet]):
1463 if (self.ev_dict[e]['unique']):
1464 body.append(' case %s:' % (e))
1465 body.append(' return 1;\n default:\n return 0;\n }\n}\n\n')
Tobin Ehlis7c47fc42014-12-17 07:20:23 -07001466 return "\n".join(body)
1467
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001468 def _generateSHBody(self):
1469 body = []
1470# with open(self.out_file, "a") as hf:
1471 # bet == base_enum_type, fet == final_enum_type
Peter Lohrmann49ea1842015-03-30 16:29:56 -07001472 for bet in sorted(self.et_dict):
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001473 fet = self.tf_dict[bet]
Ian Elliottfeae4052015-02-18 12:38:04 -07001474 body.append("static inline const char* string_%s(%s input_value)\n{\n switch ((%s)input_value)\n {" % (fet, fet, fet))
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001475 for e in sorted(self.et_dict[bet]):
1476 if (self.ev_dict[e]['unique']):
Tobin Ehlis10777032015-01-16 15:13:34 -07001477 body.append(' case %s:\n return "%s";' % (e, e))
1478 body.append(' default:\n return "Unhandled %s";\n }\n}\n\n' % (fet))
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001479 return "\n".join(body)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001480
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001481 def _generateSHHeader(self):
Ian Elliott2d4ab1e2015-01-13 17:52:38 -07001482 header = []
1483 header.append('#pragma once\n')
Ian Elliottc779c7e2015-04-28 16:11:24 -06001484 header.append('#ifdef _WIN32\n')
1485 header.append('#pragma warning( disable : 4065 )\n')
1486 header.append('#endif\n')
Ian Elliottfeae4052015-02-18 12:38:04 -07001487 header.append('#include <%s>\n\n\n' % self.in_file)
Ian Elliott2d4ab1e2015-01-13 17:52:38 -07001488 return "\n".join(header)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001489
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001490
1491class CMakeGen:
1492 def __init__(self, struct_wrapper=None, out_dir=None):
1493 self.sw = struct_wrapper
Tobin Ehlis83562882014-11-27 15:43:39 -07001494 self.include_headers = []
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001495 self.add_lib_file_list = self.sw.get_file_list()
1496 self.out_dir = out_dir
1497 self.out_file = os.path.join(self.out_dir, "CMakeLists.txt")
1498 self.cmg = CommonFileGen(self.out_file)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001499
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001500 def generate(self):
1501 self.cmg.setBody(self._generateBody())
1502 self.cmg.generate()
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001503
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001504 def _generateBody(self):
1505 body = []
1506 body.append("project(%s)" % os.path.basename(self.out_dir))
1507 body.append("cmake_minimum_required(VERSION 2.8)\n")
1508 body.append("add_library(${PROJECT_NAME} %s)\n" % " ".join(self.add_lib_file_list))
1509 body.append('set(COMPILE_FLAGS "-fpermissive")')
1510 body.append('set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COMPILE_FLAGS}")\n')
1511 body.append("include_directories(${SRC_DIR}/thirdparty/${GEN_API}/inc/)\n")
1512 body.append("target_include_directories (%s PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})\n" % os.path.basename(self.out_dir))
1513 return "\n".join(body)
1514
1515class GraphVizGen:
Tobin Ehlis83562882014-11-27 15:43:39 -07001516 def __init__(self, struct_dict, prefix, out_dir):
1517 self.struct_dict = struct_dict
1518 self.api = prefix
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001519 if prefix == "vulkan":
1520 self.api_prefix = "vk"
1521 else:
1522 self.api_prefix = prefix
1523 self.out_file = os.path.join(out_dir, self.api_prefix+"_struct_graphviz_helper.h")
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001524 self.gvg = CommonFileGen(self.out_file)
Tobin Ehlis83562882014-11-27 15:43:39 -07001525
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001526 def generate(self):
Tobin Ehlis83562882014-11-27 15:43:39 -07001527 self.gvg.setCopyright("//This is the copyright\n")
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001528 self.gvg.setHeader(self._generateHeader())
1529 self.gvg.setBody(self._generateBody())
Tobin Ehlis83562882014-11-27 15:43:39 -07001530 #self.gvg.setFooter('}')
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001531 self.gvg.generate()
Tobin Ehlis83562882014-11-27 15:43:39 -07001532
1533 def set_include_headers(self, include_headers):
1534 self.include_headers = include_headers
1535
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001536 def _generateHeader(self):
Tobin Ehlis83562882014-11-27 15:43:39 -07001537 header = []
1538 header.append("//#includes, #defines, globals and such...\n")
1539 for f in self.include_headers:
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001540 if 'vk_enum_string_helper' not in f:
Tobin Ehlis83562882014-11-27 15:43:39 -07001541 header.append("#include <%s>\n" % f)
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001542 #header.append('#include "vk_enum_string_helper.h"\n\n// Function Prototypes\n')
Mark Lobodzinski17caf572015-01-29 08:55:56 -06001543 header.append("\nchar* dynamic_gv_display(const void* pStruct, const char* prefix);\n")
Tobin Ehlis83562882014-11-27 15:43:39 -07001544 return "".join(header)
1545
1546 def _get_gv_func_name(self, struct):
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001547 return "%s_gv_print_%s" % (self.api_prefix, struct.lower().strip("_"))
Tobin Ehlis83562882014-11-27 15:43:39 -07001548
1549 # Return elements to create formatted string for given struct member
1550 def _get_struct_gv_print_formatted(self, struct_member, pre_var_name="", postfix = "\\n", struct_var_name="pStruct", struct_ptr=True, print_array=False, port_label=""):
1551 struct_op = "->"
1552 pre_var_name = '"%s "' % struct_member['full_type']
1553 if not struct_ptr:
1554 struct_op = "."
1555 member_name = struct_member['name']
1556 print_type = "p"
1557 cast_type = ""
1558 member_post = ""
1559 array_index = ""
1560 member_print_post = ""
Tobin Ehlisb0497852015-02-11 14:24:02 -07001561 print_delimiter = "%"
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001562 if struct_member['array'] and 'char' in struct_member['type'].lower(): # just print char array as string
1563 print_type = "p"
Tobin Ehlis83562882014-11-27 15:43:39 -07001564 print_array = False
1565 elif struct_member['array'] and not print_array:
1566 # Just print base address of array when not full print_array
1567 cast_type = "(void*)"
1568 elif is_type(struct_member['type'], 'enum'):
Jon Ashburnfe6113c2015-01-09 09:11:44 -07001569 if struct_member['ptr']:
1570 struct_var_name = "*" + struct_var_name
Tobin Ehlis83562882014-11-27 15:43:39 -07001571 cast_type = "string_%s" % struct_member['type']
1572 print_type = "s"
1573 elif is_type(struct_member['type'], 'struct'): # print struct address for now
1574 cast_type = "(void*)"
1575 if not struct_member['ptr']:
1576 cast_type = "(void*)&"
Courtney Goeltzenleuchtercd2a0992015-07-09 11:44:38 -06001577 elif 'bool' in struct_member['type'].lower():
Tobin Ehlis83562882014-11-27 15:43:39 -07001578 print_type = "s"
1579 member_post = ' ? "TRUE" : "FALSE"'
Tobin Ehlis7e65d752015-01-15 17:51:52 -07001580 elif 'float' in struct_member['type']:
Tobin Ehlis83562882014-11-27 15:43:39 -07001581 print_type = "f"
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001582 elif 'uint64' in struct_member['type'] or 'gpusize' in struct_member['type'].lower():
1583 print_type = '" PRId64 "'
Tobin Ehlis7e65d752015-01-15 17:51:52 -07001584 elif 'uint8' in struct_member['type']:
Tobin Ehlis83562882014-11-27 15:43:39 -07001585 print_type = "hu"
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001586 elif 'size' in struct_member['type'].lower():
Tobin Ehlisb0497852015-02-11 14:24:02 -07001587 print_type = '" PRINTF_SIZE_T_SPECIFIER "'
1588 print_delimiter = ""
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001589 elif True in [ui_str.lower() in struct_member['type'].lower() for ui_str in ['uint', 'flags', 'samplemask']]:
Tobin Ehlis83562882014-11-27 15:43:39 -07001590 print_type = "u"
Tobin Ehlis7e65d752015-01-15 17:51:52 -07001591 elif 'int' in struct_member['type']:
Tobin Ehlis83562882014-11-27 15:43:39 -07001592 print_type = "i"
1593 elif struct_member['ptr']:
1594 pass
1595 else:
1596 #print("Unhandled struct type: %s" % struct_member['type'])
1597 cast_type = "(void*)"
1598 if print_array and struct_member['array']:
1599 member_print_post = "[%u]"
1600 array_index = " i,"
1601 member_post = "[i]"
Tobin Ehlisb0497852015-02-11 14:24:02 -07001602 print_out = "<TR><TD>%%s%s%s</TD><TD%s>%s%s%s</TD></TR>" % (member_name, member_print_post, port_label, print_delimiter, print_type, postfix) # section of print that goes inside of quotes
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001603 print_arg = ", %s,%s %s(%s%s%s)%s\n" % (pre_var_name, array_index, cast_type, struct_var_name, struct_op, member_name, member_post) # section of print passed to portion in quotes
Tobin Ehlis83562882014-11-27 15:43:39 -07001604 return (print_out, print_arg)
1605
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001606 def _generateBody(self):
Tobin Ehlis83562882014-11-27 15:43:39 -07001607 gv_funcs = []
1608 array_func_list = [] # structs for which we'll generate an array version of their print function
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001609 array_func_list.append('vkbufferviewattachinfo')
1610 array_func_list.append('vkimageviewattachinfo')
1611 array_func_list.append('vksamplerimageviewinfo')
1612 array_func_list.append('vkdescriptortypecount')
Tobin Ehlis83562882014-11-27 15:43:39 -07001613 # For first pass, generate prototype
Peter Lohrmann49ea1842015-03-30 16:29:56 -07001614 for s in sorted(self.struct_dict):
Tobin Ehlis83562882014-11-27 15:43:39 -07001615 gv_funcs.append('char* %s(const %s* pStruct, const char* myNodeName);\n' % (self._get_gv_func_name(s), typedef_fwd_dict[s]))
1616 if s.lower().strip("_") in array_func_list:
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001617 if s.lower().strip("_") in ['vkbufferviewattachinfo', 'vkimageviewattachinfo']:
Tobin Ehlisb8013a22015-02-26 12:57:08 -07001618 gv_funcs.append('char* %s_array(uint32_t count, const %s* const* pStruct, const char* myNodeName);\n' % (self._get_gv_func_name(s), typedef_fwd_dict[s]))
1619 else:
1620 gv_funcs.append('char* %s_array(uint32_t count, const %s* pStruct, const char* myNodeName);\n' % (self._get_gv_func_name(s), typedef_fwd_dict[s]))
Tobin Ehlis83562882014-11-27 15:43:39 -07001621 gv_funcs.append('\n')
Peter Lohrmann49ea1842015-03-30 16:29:56 -07001622 for s in sorted(self.struct_dict):
Tobin Ehlis83562882014-11-27 15:43:39 -07001623 p_out = ""
1624 p_args = ""
1625 stp_list = [] # stp == "struct to print" a list of structs for this API call that should be printed as structs
1626 # the fields below are a super-hacky way for now to get port labels into GV output, TODO : Clean this up!
1627 pl_dict = {}
1628 struct_num = 0
Tobin Ehlisb8013a22015-02-26 12:57:08 -07001629 # This isn't great but this pre-pass flags structs w/ pNext and other struct ptrs
Tobin Ehlis83562882014-11-27 15:43:39 -07001630 for m in sorted(self.struct_dict[s]):
1631 if 'pNext' == self.struct_dict[s][m]['name'] or is_type(self.struct_dict[s][m]['type'], 'struct'):
1632 stp_list.append(self.struct_dict[s][m])
1633 if 'pNext' == self.struct_dict[s][m]['name']:
1634 pl_dict[m] = ' PORT=\\"pNext\\"'
1635 else:
1636 pl_dict[m] = ' PORT=\\"struct%i\\"' % struct_num
1637 struct_num += 1
1638 gv_funcs.append('char* %s(const %s* pStruct, const char* myNodeName)\n{\n char* str;\n' % (self._get_gv_func_name(s), typedef_fwd_dict[s]))
1639 num_stps = len(stp_list);
1640 total_strlen_str = ''
1641 if 0 != num_stps:
1642 gv_funcs.append(" char* tmpStr;\n")
1643 gv_funcs.append(" char nodeName[100];\n")
Tobin Ehlis83562882014-11-27 15:43:39 -07001644 gv_funcs.append(' char* stp_strs[%i];\n' % num_stps)
1645 for index in range(num_stps):
1646 if (stp_list[index]['ptr']):
1647 if 'pDescriptorInfo' == stp_list[index]['name']:
1648 gv_funcs.append(' if (pStruct->pDescriptorInfo && (0 != pStruct->descriptorCount)) {\n')
1649 else:
1650 gv_funcs.append(' if (pStruct->%s) {\n' % stp_list[index]['name'])
1651 if 'pNext' == stp_list[index]['name']:
1652 gv_funcs.append(' sprintf(nodeName, "pNext_%p", (void*)pStruct->pNext);\n')
Mark Lobodzinski17caf572015-01-29 08:55:56 -06001653 gv_funcs.append(' tmpStr = dynamic_gv_display((void*)pStruct->pNext, nodeName);\n')
Tobin Ehlis83562882014-11-27 15:43:39 -07001654 gv_funcs.append(' stp_strs[%i] = (char*)malloc(256+strlen(tmpStr)+strlen(nodeName)+strlen(myNodeName));\n' % index)
1655 gv_funcs.append(' sprintf(stp_strs[%i], "%%s\\n\\"%%s\\":pNext -> \\"%%s\\" [];\\n", tmpStr, myNodeName, nodeName);\n' % index)
1656 gv_funcs.append(' free(tmpStr);\n')
1657 else:
1658 gv_funcs.append(' sprintf(nodeName, "%s_%%p", (void*)pStruct->%s);\n' % (stp_list[index]['name'], stp_list[index]['name']))
Tobin Ehlis793ad302015-04-03 12:01:11 -06001659 if stp_list[index]['name'] in ['pTypeCount', 'pSamplerImageViews']:
Tobin Ehlisb8013a22015-02-26 12:57:08 -07001660 gv_funcs.append(' tmpStr = %s_array(pStruct->count, pStruct->%s, nodeName);\n' % (self._get_gv_func_name(stp_list[index]['type']), stp_list[index]['name']))
Tobin Ehlis83562882014-11-27 15:43:39 -07001661 else:
1662 gv_funcs.append(' tmpStr = %s(pStruct->%s, nodeName);\n' % (self._get_gv_func_name(stp_list[index]['type']), stp_list[index]['name']))
1663 gv_funcs.append(' stp_strs[%i] = (char*)malloc(256+strlen(tmpStr)+strlen(nodeName)+strlen(myNodeName));\n' % (index))
1664 gv_funcs.append(' sprintf(stp_strs[%i], "%%s\\n\\"%%s\\":struct%i -> \\"%%s\\" [];\\n", tmpStr, myNodeName, nodeName);\n' % (index, index))
1665 gv_funcs.append(' }\n')
Chia-I Wu3bf80a62014-12-16 00:36:58 +08001666 gv_funcs.append(" else\n stp_strs[%i] = \"\";\n" % (index))
Tobin Ehlis83562882014-11-27 15:43:39 -07001667 elif stp_list[index]['array']: # TODO : For now just printing first element of array
1668 gv_funcs.append(' sprintf(nodeName, "%s_%%p", (void*)&pStruct->%s[0]);\n' % (stp_list[index]['name'], stp_list[index]['name']))
1669 gv_funcs.append(' tmpStr = %s(&pStruct->%s[0], nodeName);\n' % (self._get_gv_func_name(stp_list[index]['type']), stp_list[index]['name']))
1670 gv_funcs.append(' stp_strs[%i] = (char*)malloc(256+strlen(tmpStr)+strlen(nodeName)+strlen(myNodeName));\n' % (index))
1671 gv_funcs.append(' sprintf(stp_strs[%i], "%%s\\n\\"%%s\\":struct%i -> \\"%%s\\" [];\\n", tmpStr, myNodeName, nodeName);\n' % (index, index))
1672 else:
1673 gv_funcs.append(' sprintf(nodeName, "%s_%%p", (void*)&pStruct->%s);\n' % (stp_list[index]['name'], stp_list[index]['name']))
1674 gv_funcs.append(' tmpStr = %s(&pStruct->%s, nodeName);\n' % (self._get_gv_func_name(stp_list[index]['type']), stp_list[index]['name']))
1675 gv_funcs.append(' stp_strs[%i] = (char*)malloc(256+strlen(tmpStr)+strlen(nodeName)+strlen(myNodeName));\n' % (index))
1676 gv_funcs.append(' sprintf(stp_strs[%i], "%%s\\n\\"%%s\\":struct%i -> \\"%%s\\" [];\\n", tmpStr, myNodeName, nodeName);\n' % (index, index))
1677 total_strlen_str += 'strlen(stp_strs[%i]) + ' % index
1678 gv_funcs.append(' str = (char*)malloc(%ssizeof(char)*2048);\n' % (total_strlen_str))
1679 gv_funcs.append(' sprintf(str, "\\"%s\\" [\\nlabel = <<TABLE BORDER=\\"0\\" CELLBORDER=\\"1\\" CELLSPACING=\\"0\\"><TR><TD COLSPAN=\\"2\\">%s (%p)</TD></TR>')
1680 p_args = ", myNodeName, myNodeName, pStruct"
1681 for m in sorted(self.struct_dict[s]):
1682 plabel = ""
1683 if m in pl_dict:
1684 plabel = pl_dict[m]
1685 (p_out1, p_args1) = self._get_struct_gv_print_formatted(self.struct_dict[s][m], port_label=plabel)
1686 p_out += p_out1
1687 p_args += p_args1
1688 p_out += '</TABLE>>\\n];\\n\\n"'
1689 p_args += ");\n"
1690 gv_funcs.append(p_out)
1691 gv_funcs.append(p_args)
1692 if 0 != num_stps:
1693 gv_funcs.append(' for (int32_t stp_index = %i; stp_index >= 0; stp_index--) {\n' % (num_stps-1))
1694 gv_funcs.append(' if (0 < strlen(stp_strs[stp_index])) {\n')
1695 gv_funcs.append(' strncat(str, stp_strs[stp_index], strlen(stp_strs[stp_index]));\n')
1696 gv_funcs.append(' free(stp_strs[stp_index]);\n')
1697 gv_funcs.append(' }\n')
1698 gv_funcs.append(' }\n')
1699 gv_funcs.append(" return str;\n}\n")
1700 if s.lower().strip("_") in array_func_list:
Tobin Ehlisb8013a22015-02-26 12:57:08 -07001701 ptr_array = False
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001702 if s.lower().strip("_") in ['vkbufferviewattachinfo', 'vkimageviewattachinfo']:
Tobin Ehlisb8013a22015-02-26 12:57:08 -07001703 ptr_array = True
1704 gv_funcs.append('char* %s_array(uint32_t count, const %s* const* pStruct, const char* myNodeName)\n{\n char* str;\n char tmpStr[1024];\n' % (self._get_gv_func_name(s), typedef_fwd_dict[s]))
1705 else:
1706 gv_funcs.append('char* %s_array(uint32_t count, const %s* pStruct, const char* myNodeName)\n{\n char* str;\n char tmpStr[1024];\n' % (self._get_gv_func_name(s), typedef_fwd_dict[s]))
Tobin Ehlis83562882014-11-27 15:43:39 -07001707 gv_funcs.append(' str = (char*)malloc(sizeof(char)*1024*count);\n')
1708 gv_funcs.append(' sprintf(str, "\\"%s\\" [\\nlabel = <<TABLE BORDER=\\"0\\" CELLBORDER=\\"1\\" CELLSPACING=\\"0\\"><TR><TD COLSPAN=\\"3\\">%s (%p)</TD></TR>", myNodeName, myNodeName, pStruct);\n')
1709 gv_funcs.append(' for (uint32_t i=0; i < count; i++) {\n')
1710 gv_funcs.append(' sprintf(tmpStr, "');
1711 p_args = ""
1712 p_out = ""
1713 for m in sorted(self.struct_dict[s]):
Tobin Ehlis83562882014-11-27 15:43:39 -07001714 plabel = ""
1715 (p_out1, p_args1) = self._get_struct_gv_print_formatted(self.struct_dict[s][m], port_label=plabel)
Tobin Ehlisb8013a22015-02-26 12:57:08 -07001716 if 0 == m: # Add array index notation at end of first row
1717 p_out1 = '%s<TD ROWSPAN=\\"%i\\" PORT=\\"slot%%u\\">%%u</TD></TR>' % (p_out1[:-5], len(self.struct_dict[s]))
Tobin Ehlis83562882014-11-27 15:43:39 -07001718 p_args1 += ', i, i'
1719 p_out += p_out1
1720 p_args += p_args1
1721 p_out += '"'
1722 p_args += ");\n"
Tobin Ehlisb8013a22015-02-26 12:57:08 -07001723 if ptr_array:
1724 p_args = p_args.replace('->', '[i]->')
1725 else:
1726 p_args = p_args.replace('->', '[i].')
Tobin Ehlis83562882014-11-27 15:43:39 -07001727 gv_funcs.append(p_out);
1728 gv_funcs.append(p_args);
1729 gv_funcs.append(' strncat(str, tmpStr, strlen(tmpStr));\n')
1730 gv_funcs.append(' }\n')
1731 gv_funcs.append(' strncat(str, "</TABLE>>\\n];\\n\\n", 20);\n')
Tobin Ehlis83562882014-11-27 15:43:39 -07001732 gv_funcs.append(' return str;\n}\n')
1733 # Add function to dynamically print out unknown struct
Mark Lobodzinski17caf572015-01-29 08:55:56 -06001734 gv_funcs.append("char* dynamic_gv_display(const void* pStruct, const char* nodeName)\n{\n")
Tobin Ehlis83562882014-11-27 15:43:39 -07001735 gv_funcs.append(" // Cast to APP_INFO ptr initially just to pull sType off struct\n")
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001736 gv_funcs.append(" VkStructureType sType = ((VkApplicationInfo*)pStruct)->sType;\n")
Tobin Ehlis83562882014-11-27 15:43:39 -07001737 gv_funcs.append(" switch (sType)\n {\n")
1738 for e in enum_type_dict:
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001739 if "StructureType" in e:
Tobin Ehlis83562882014-11-27 15:43:39 -07001740 for v in sorted(enum_type_dict[e]):
Courtney Goeltzenleuchter95487bc2015-04-14 18:48:46 -06001741 struct_name = get_struct_name_from_struct_type(v)
Chia-I Wu736324e2015-10-26 20:42:12 +08001742 if struct_name not in self.struct_dict:
1743 continue
1744
Tobin Ehlis83562882014-11-27 15:43:39 -07001745 print_func_name = self._get_gv_func_name(struct_name)
1746 # TODO : Hand-coded fixes for some exceptions
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001747 #if 'VkPipelineCbStateCreateInfo' in struct_name:
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001748 # struct_name = 'VK_PIPELINE_CB_STATE'
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001749 if 'VkSemaphoreCreateInfo' in struct_name:
1750 struct_name = 'VkSemaphoreCreateInfo'
Tobin Ehlis83562882014-11-27 15:43:39 -07001751 print_func_name = self._get_gv_func_name(struct_name)
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001752 elif 'VkSemaphoreOpenInfo' in struct_name:
1753 struct_name = 'VkSemaphoreOpenInfo'
Tobin Ehlis83562882014-11-27 15:43:39 -07001754 print_func_name = self._get_gv_func_name(struct_name)
1755 gv_funcs.append(' case %s:\n' % (v))
1756 gv_funcs.append(' return %s((%s*)pStruct, nodeName);\n' % (print_func_name, struct_name))
1757 #gv_funcs.append(' }\n')
1758 #gv_funcs.append(' break;\n')
Chia-I Wubfa3fea2014-12-16 00:43:20 +08001759 gv_funcs.append(" default:\n")
1760 gv_funcs.append(" return NULL;\n")
Tobin Ehlis83562882014-11-27 15:43:39 -07001761 gv_funcs.append(" }\n")
1762 gv_funcs.append("}")
1763 return "".join(gv_funcs)
1764
1765
1766
1767
1768
1769# def _generateHeader(self):
1770# hdr = []
1771# hdr.append('digraph g {\ngraph [\nrankdir = "LR"\n];')
1772# hdr.append('node [\nfontsize = "16"\nshape = "plaintext"\n];')
1773# hdr.append('edge [\n];\n')
1774# return "\n".join(hdr)
Mark Lobodzinski28b8f022015-08-27 15:30:29 -06001775#
Tobin Ehlis83562882014-11-27 15:43:39 -07001776# def _generateBody(self):
1777# body = []
Peter Lohrmann49ea1842015-03-30 16:29:56 -07001778# for s in sorted(self.struc_dict):
Tobin Ehlis83562882014-11-27 15:43:39 -07001779# field_num = 1
1780# 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]))
1781# for m in sorted(self.struc_dict[s]):
1782# 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']))
1783# field_num += 2
1784# body.append('</TABLE>>\n];\n')
1785# return "".join(body)
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001786
1787def main(argv=None):
1788 opts = handle_args()
1789 # Parse input file and fill out global dicts
1790 hfp = HeaderFileParser(opts.input_file)
1791 hfp.parse()
1792 # TODO : Don't want these to be global, see note at top about wrapper classes
1793 global enum_val_dict
1794 global enum_type_dict
1795 global struct_dict
1796 global typedef_fwd_dict
1797 global typedef_rev_dict
1798 global types_dict
1799 enum_val_dict = hfp.get_enum_val_dict()
1800 enum_type_dict = hfp.get_enum_type_dict()
1801 struct_dict = hfp.get_struct_dict()
Tobin Ehlis5a487e52014-11-11 12:28:12 -07001802 # TODO : Would like to validate struct data here to verify that all of the bools for struct members are correct at this point
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001803 typedef_fwd_dict = hfp.get_typedef_fwd_dict()
1804 typedef_rev_dict = hfp.get_typedef_rev_dict()
1805 types_dict = hfp.get_types_dict()
1806 #print(enum_val_dict)
1807 #print(typedef_dict)
1808 #print(struct_dict)
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001809 prefix = os.path.basename(opts.input_file).strip(".h")
1810 if prefix == "vulkan":
1811 prefix = "vk"
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001812 if (opts.abs_out_dir is not None):
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001813 enum_sh_filename = os.path.join(opts.abs_out_dir, prefix+"_enum_string_helper.h")
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001814 else:
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001815 enum_sh_filename = os.path.join(os.getcwd(), opts.rel_out_dir, prefix+"_enum_string_helper.h")
Tobin Ehlis7c47fc42014-12-17 07:20:23 -07001816 enum_sh_filename = os.path.abspath(enum_sh_filename)
1817 if not os.path.exists(os.path.dirname(enum_sh_filename)):
1818 print("Creating output dir %s" % os.path.dirname(enum_sh_filename))
1819 os.mkdir(os.path.dirname(enum_sh_filename))
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001820 if opts.gen_enum_string_helper:
Tobin Ehlis7c47fc42014-12-17 07:20:23 -07001821 print("Generating enum string helper to %s" % enum_sh_filename)
Courtney Goeltzenleuchterd8e229c2015-04-08 15:36:08 -06001822 enum_vh_filename = os.path.join(os.path.dirname(enum_sh_filename), prefix+"_enum_validate_helper.h")
Tobin Ehlis7c47fc42014-12-17 07:20:23 -07001823 print("Generating enum validate helper to %s" % enum_vh_filename)
1824 eg = EnumCodeGen(enum_type_dict, enum_val_dict, typedef_fwd_dict, os.path.basename(opts.input_file), enum_sh_filename, enum_vh_filename)
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001825 eg.generateStringHelper()
Tobin Ehlis7c47fc42014-12-17 07:20:23 -07001826 eg.generateEnumValidate()
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001827 #for struct in struct_dict:
1828 #print(struct)
1829 if opts.gen_struct_wrappers:
Tobin Ehlis7c47fc42014-12-17 07:20:23 -07001830 sw = StructWrapperGen(struct_dict, os.path.basename(opts.input_file).strip(".h"), os.path.dirname(enum_sh_filename))
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001831 #print(sw.get_class_name(struct))
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001832 sw.set_include_headers([os.path.basename(opts.input_file),os.path.basename(enum_sh_filename),"stdint.h","inttypes.h", "stdio.h","stdlib.h"])
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001833 print("Generating struct wrapper header to %s" % sw.header_filename)
1834 sw.generateHeader()
1835 print("Generating struct wrapper class to %s" % sw.class_filename)
1836 sw.generateBody()
1837 sw.generateStringHelper()
Tobin Ehlis14ff0852014-12-17 17:44:50 -07001838 sw.generateValidateHelper()
Tobin Ehlisd49efcb2014-11-25 17:43:26 -07001839 # Generate a 2nd helper file that excludes addrs
1840 sw.set_no_addr(True)
1841 sw.generateStringHelper()
Tobin Ehlis99f88672015-01-10 12:42:41 -07001842 sw.set_no_addr(False)
1843 sw.set_include_headers([os.path.basename(opts.input_file),os.path.basename(enum_sh_filename),"stdint.h","stdio.h","stdlib.h","iostream","sstream","string"])
Tobin Ehlis99f88672015-01-10 12:42:41 -07001844 sw.set_no_addr(True)
1845 sw.generateStringHelperCpp()
Tobin Ehlis5178bd72015-03-06 10:38:25 -07001846 sw.set_no_addr(False)
1847 sw.generateStringHelperCpp()
Courtney Goeltzenleuchterf53c3cb2015-04-14 14:55:44 -06001848 sw.set_include_headers(["stdio.h", "stdlib.h", "vulkan.h"])
Tobin Ehlis60354772015-03-12 14:50:40 -06001849 sw.generateSizeHelper()
Peter Lohrmann4a8d8912015-04-03 11:43:06 -07001850 sw.generateSizeHelperC()
Jon Ashburnea65e492015-08-06 17:27:49 -06001851 if opts.gen_struct_sizes:
1852 st = StructWrapperGen(struct_dict, os.path.basename(opts.input_file).strip(".h"), os.path.dirname(enum_sh_filename))
1853 st.set_include_headers(["stdio.h", "stdlib.h", "vulkan.h"])
1854 st.generateSizeHelper()
1855 st.generateSizeHelperC()
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001856 if opts.gen_cmake:
Tobin Ehlis7c47fc42014-12-17 07:20:23 -07001857 cmg = CMakeGen(sw, os.path.dirname(enum_sh_filename))
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001858 cmg.generate()
1859 if opts.gen_graphviz:
Tobin Ehlis7c47fc42014-12-17 07:20:23 -07001860 gv = GraphVizGen(struct_dict, os.path.basename(opts.input_file).strip(".h"), os.path.dirname(enum_sh_filename))
Courtney Goeltzenleuchterfb4efc62015-04-10 08:34:15 -06001861 gv.set_include_headers([os.path.basename(opts.input_file),os.path.basename(enum_sh_filename),"stdint.h","stdio.h","stdlib.h", "inttypes.h"])
Tobin Ehlis6442dca2014-10-22 15:13:53 -06001862 gv.generate()
1863 print("DONE!")
1864 #print(typedef_rev_dict)
1865 #print(types_dict)
1866 #recreate_structs()
1867
1868if __name__ == "__main__":
1869 sys.exit(main())