tools/spec: rename classes in CamelCase for PEP8 conformance

This commit is contained in:
Danny Robson 2019-01-05 12:14:15 +11:00
parent 1710d6c8ce
commit 09c9ff741a

View File

@ -13,13 +13,13 @@ def rename(name: str):
############################################################################### ###############################################################################
class registry: class Registry:
def __init__(self): def __init__(self):
self.types = {} self.types = {}
self.extensions = {} self.extensions = {}
self.features = {} self.features = {}
self.types['API Constants'] = unscoped('API Constants') self.types['API Constants'] = Unscoped('API Constants')
self.applied = set() self.applied = set()
@ -61,7 +61,7 @@ class registry:
############################################################################### ###############################################################################
class type(object): class Type(object):
""" """
The base class for all object defined in the Vulkan API. The base class for all object defined in the Vulkan API.
@ -89,7 +89,7 @@ class type(object):
############################################################################### ###############################################################################
class aliastype(type): class AliasType(Type):
""" """
A type that is an alias for another type. A type that is an alias for another type.
@ -106,7 +106,7 @@ class aliastype(type):
##----------------------------------------------------------------------------- ##-----------------------------------------------------------------------------
class aliasvalue(type): class AliasValue(Type):
""" """
A value that is an alias for another value. A value that is an alias for another value.
@ -125,14 +125,14 @@ class aliasvalue(type):
##----------------------------------------------------------------------------- ##-----------------------------------------------------------------------------
class placeholder(type): class Placeholder(Type):
def __init__(self, name: str): def __init__(self, name: str):
super().__init__(name) super().__init__(name)
##----------------------------------------------------------------------------- ##-----------------------------------------------------------------------------
class unscoped(type): class Unscoped(Type):
def __init__(self, name: str): def __init__(self, name: str):
super().__init__(name) super().__init__(name)
self.values = [] self.values = []
@ -146,7 +146,7 @@ class unscoped(type):
############################################################################### ###############################################################################
class include(type): class Include(Type):
def __init__(self, node): def __init__(self, node):
assert node.tag == 'type' assert node.tag == 'type'
assert node.attrib['category'] == 'include' assert node.attrib['category'] == 'include'
@ -159,7 +159,7 @@ class include(type):
return self.directive or "#include <%s>" % self.name return self.directive or "#include <%s>" % self.name
class define(type): class Define(Type):
def __init__(self, node): def __init__(self, node):
assert node.tag == 'type' assert node.tag == 'type'
assert node.attrib['category'] == 'define' assert node.attrib['category'] == 'define'
@ -173,7 +173,7 @@ class define(type):
return self.directive return self.directive
class bitmask(type): class Bitmask(Type):
def __init__(self, node): def __init__(self, node):
assert node.tag == 'type' assert node.tag == 'type'
assert node.attrib['category'] == 'bitmask' assert node.attrib['category'] == 'bitmask'
@ -194,7 +194,7 @@ class bitmask(type):
"type": self.type "type": self.type
} }
def define(self, reg: registry): def define(self, reg: Registry):
return self.declare() return self.declare()
if not self.requires: if not self.requires:
@ -217,7 +217,7 @@ class bitmask(type):
} }
class handle(type): class Handle(Type):
parents: List[str] parents: List[str]
type: str type: str
@ -242,7 +242,7 @@ class handle(type):
"type": self.type "type": self.type
} }
def has_parent(self, name: str, reg: registry) -> bool: def has_parent(self, name: str, reg: Registry) -> bool:
""" """
Recursively check if this type is derived from a given parent type. Recursively check if this type is derived from a given parent type.
""" """
@ -263,7 +263,7 @@ class handle(type):
return False return False
class enum(type): class Enum(Type):
def __init__(self, node): def __init__(self, node):
assert node.tag == 'type' assert node.tag == 'type'
assert node.attrib['category'] == 'enum' assert node.attrib['category'] == 'enum'
@ -274,7 +274,7 @@ class enum(type):
self.values = {} self.values = {}
def __setitem__(self, key: str, value): def __setitem__(self, key: str, value):
assert isinstance(value, constant) or isinstance(value, aliasvalue) assert isinstance(value, Constant) or isinstance(value, AliasValue)
self.values[key] = value self.values[key] = value
def declare(self): def declare(self):
@ -283,7 +283,7 @@ class enum(type):
"name": self.name "name": self.name
} }
def define(self, reg: registry): def define(self, reg: Registry):
values = ("%(name)s = %(value)s" % { "name": k, "value": v.value } for (k,v) in self.values.items()) values = ("%(name)s = %(value)s" % { "name": k, "value": v.value } for (k,v) in self.values.items())
return "enum %(name)s : int32_t { %(values)s };" % { return "enum %(name)s : int32_t { %(values)s };" % {
@ -292,7 +292,7 @@ class enum(type):
} }
class basetype(aliastype): class BaseType(AliasType):
""" """
Represents fundamental types that aliases of system provided types and used Represents fundamental types that aliases of system provided types and used
extensively by the base API. eg, VkBool32 extensively by the base API. eg, VkBool32
@ -308,7 +308,7 @@ class basetype(aliastype):
) )
class funcpointer(type): class FuncPointer(Type):
def __init__(self, node): def __init__(self, node):
assert node.tag == 'type' assert node.tag == 'type'
assert node.attrib['category'] == 'funcpointer' assert node.attrib['category'] == 'funcpointer'
@ -324,7 +324,7 @@ class funcpointer(type):
return self.text return self.text
class pod(type): class POD(Type):
def __init__(self, node): def __init__(self, node):
assert node.tag == 'type' assert node.tag == 'type'
assert node.attrib['category'] in ['struct', 'union'] assert node.attrib['category'] in ['struct', 'union']
@ -362,7 +362,7 @@ class pod(type):
'name': rename(self.name) 'name': rename(self.name)
} }
def define(self, reg: registry): def define(self, reg: Registry):
return "%(category)s %(name)s {\n%(members)s\n};" % { return "%(category)s %(name)s {\n%(members)s\n};" % {
'category': self._category, 'category': self._category,
'name': rename(self.name), 'name': rename(self.name),
@ -370,17 +370,17 @@ class pod(type):
} }
class struct(pod): class Struct(POD):
def __init__(self, node): def __init__(self, node):
super().__init__(node) super().__init__(node)
class union(pod): class Union(POD):
def __init__(self, node): def __init__(self, node):
super().__init__(node) super().__init__(node)
class constant(type): class Constant(Type):
def __init__(self, node, **kwargs): def __init__(self, node, **kwargs):
assert node.tag == 'enum' assert node.tag == 'enum'
@ -410,8 +410,8 @@ class constant(type):
} }
class command(type): class Command(Type):
class param(type): class Param(Type):
def __init__(self, node, **kwargs): def __init__(self, node, **kwargs):
assert node.tag == 'param' assert node.tag == 'param'
@ -437,7 +437,7 @@ class command(type):
super().__init__(name) super().__init__(name)
self.result = proto.find('type').text self.result = proto.find('type').text
self.params = [self.param(p) for p in node.findall('./param')] self.params = [self.Param(p) for p in node.findall('./param')]
self.depends += [self.result] self.depends += [self.result]
for p in self.params: for p in self.params:
self.depends += p.depends self.depends += p.depends
@ -449,7 +449,7 @@ class command(type):
'params': ", ".join(p.param for p in self.params) 'params': ", ".join(p.param for p in self.params)
} }
def is_instance(self, reg: registry): def is_instance(self, reg: Registry):
assert reg assert reg
if not self.params: if not self.params:
@ -463,7 +463,7 @@ class command(type):
# If the first type isn't a handle of any description then it should # If the first type isn't a handle of any description then it should
# be an instance function. # be an instance function.
if not isinstance(first_obj, handle): if not isinstance(first_obj, Handle):
return True return True
# Both VkInstance and VkPhysicalDevice are listed as possible instance # Both VkInstance and VkPhysicalDevice are listed as possible instance
@ -480,11 +480,11 @@ class command(type):
return False return False
return True return True
def is_device(self, reg:registry): def is_device(self, reg:Registry):
return not self.is_instance(reg) return not self.is_instance(reg)
class require(object): class Require(object):
def __init__(self, root): def __init__(self, root):
self.values = [] self.values = []
self.depends = [] self.depends = []
@ -499,7 +499,7 @@ class require(object):
else: else:
raise "Unknown requires node" raise "Unknown requires node"
def apply(self, reg: registry, extnumber=None): def apply(self, reg: Registry, extnumber=None):
required = [] required = []
required += self.depends required += self.depends
@ -512,7 +512,7 @@ class require(object):
continue continue
if not 'extends' in value.attrib: if not 'extends' in value.attrib:
obj = constant(value) obj = Constant(value)
owner = reg.types['API Constants'] owner = reg.types['API Constants']
owner.values.append(obj) owner.values.append(obj)
continue continue
@ -520,10 +520,10 @@ class require(object):
owner = reg.types[value.attrib['extends']] owner = reg.types[value.attrib['extends']]
if 'alias' in value.attrib: if 'alias' in value.attrib:
owner[name] = aliasvalue(name, value.attrib['alias']) owner[name] = AliasValue(name, value.attrib['alias'])
required.append(owner.name) required.append(owner.name)
elif value.tag == 'enum': elif value.tag == 'enum':
owner[name] = constant(value,extnumber=extnumber or int(value.attrib.get('extnumber', '0'))) owner[name] = Constant(value, extnumber=extnumber or int(value.attrib.get('extnumber', '0')))
required.append(owner.name) required.append(owner.name)
elif value.tag == 'command': elif value.tag == 'command':
required.append(name) required.append(name)
@ -533,7 +533,7 @@ class require(object):
return required return required
class feature(type): class Feature(Type):
def __init__(self, root): def __init__(self, root):
assert root.tag == 'feature' assert root.tag == 'feature'
@ -543,14 +543,14 @@ class feature(type):
self.requires = [] self.requires = []
for node in root: for node in root:
if 'require' == node.tag: if 'require' == node.tag:
self.requires.append(require(node)) self.requires.append(Require(node))
else: else:
raise "Unhandled feature node" raise "Unhandled feature node"
def define(self, reg: registry): def define(self, reg: Registry):
return "#define %s" % self.name return "#define %s" % self.name
def apply(self, reg: registry): def apply(self, reg: Registry):
logging.info("Applying feature:", self.name, file=sys.stderr) logging.info("Applying feature:", self.name, file=sys.stderr)
result = [] result = []
@ -560,7 +560,7 @@ class feature(type):
return result return result
class extension(type): class Extension(Type):
def __init__(self, root): def __init__(self, root):
assert root.tag == 'extension' assert root.tag == 'extension'
@ -577,11 +577,11 @@ class extension(type):
for node in root: for node in root:
if node.tag == 'require': if node.tag == 'require':
self.requires.append(require(node)) self.requires.append(Require(node))
else: else:
raise "Unknown extension node" raise "Unknown extension node"
def apply(self, reg: registry, platform: Set[str]): def apply(self, reg: Registry, platform: Set[str]):
if self.name in reg.applied: if self.name in reg.applied:
return [] return []
reg.applied.add(self.name) reg.applied.add(self.name)
@ -602,7 +602,7 @@ class extension(type):
############################################################################### ###############################################################################
def ignore_node(types:Dict[str,type], root): def ignore_node(types:Dict[str, Type], root):
pass pass
parse_comment = ignore_node parse_comment = ignore_node
@ -611,7 +611,7 @@ parse_platforms = ignore_node
parse_tags = ignore_node parse_tags = ignore_node
def parse_types(reg: registry, root): def parse_types(reg: Registry, root):
assert root.tag == 'types' assert root.tag == 'types'
for t in root.findall('type'): for t in root.findall('type'):
@ -622,7 +622,7 @@ def parse_types(reg: registry, root):
name = t.attrib['name'] name = t.attrib['name']
target = t.attrib['alias'] target = t.attrib['alias']
reg.types[name] = aliastype(name, target) reg.types[name] = AliasType(name, target)
continue continue
category = t.attrib.get ('category') category = t.attrib.get ('category')
@ -632,26 +632,26 @@ def parse_types(reg: registry, root):
# #
# eg, 'Display' depends on 'X11/Xlib.h' # eg, 'Display' depends on 'X11/Xlib.h'
if not category: if not category:
reg.types[name] = placeholder (name) reg.types[name] = Placeholder (name)
else: else:
# Whitelist the known types so we don't accidentally instantiate # Whitelist the known types so we don't accidentally instantiate
# something whacky # something whacky
supported_categories = [ supported_categories = {
'include', 'include': Include,
'define', 'define': Define,
'bitmask', 'bitmask': Bitmask,
'basetype', 'basetype': BaseType,
'handle', 'handle': Handle,
'enum', 'enum': Enum,
'funcpointer', 'funcpointer': FuncPointer,
'struct', 'struct': Struct,
'union' 'union': Union,
] }
if category in supported_categories: concrete = supported_categories.get(category, None)
obj = globals()[category](t) if concrete:
reg.types[name] = obj reg.types[name] = concrete(t)
else: else:
raise 'unhandled type' raise 'unhandled type'
@ -660,7 +660,7 @@ def parse_types(reg: registry, root):
##----------------------------------------------------------------------------- ##-----------------------------------------------------------------------------
def parse_enums(reg: registry, root): def parse_enums(reg: Registry, root):
assert root.tag == 'enums' assert root.tag == 'enums'
ownername = root.attrib['name'] ownername = root.attrib['name']
owner = reg.types[ownername] if ownername != 'API Constants' else reg.types owner = reg.types[ownername] if ownername != 'API Constants' else reg.types
@ -671,13 +671,13 @@ def parse_enums(reg: registry, root):
assert 'requires' not in node.attrib assert 'requires' not in node.attrib
if 'alias' in node.attrib: if 'alias' in node.attrib:
owner[valuename] = aliasvalue(valuename,node.attrib['alias']) owner[valuename] = AliasValue(valuename, node.attrib['alias'])
else: else:
owner[valuename] = constant(node) owner[valuename] = Constant(node)
##----------------------------------------------------------------------------- ##-----------------------------------------------------------------------------
def parse_commands(reg: registry, root): def parse_commands(reg: Registry, root):
assert root.tag == 'commands' assert root.tag == 'commands'
for node in root.findall('./command'): for node in root.findall('./command'):
@ -685,36 +685,36 @@ def parse_commands(reg: registry, root):
assert name not in reg.types assert name not in reg.types
if 'alias' in node.attrib: if 'alias' in node.attrib:
reg.types[name] = aliasvalue(name, node.attrib['alias']) reg.types[name] = AliasValue(name, node.attrib['alias'])
continue continue
reg.types[name] = command(node) reg.types[name] = Command(node)
##----------------------------------------------------------------------------- ##-----------------------------------------------------------------------------
def parse_feature(reg: registry, root): def parse_feature(reg: Registry, root):
assert root.tag == 'feature' assert root.tag == 'feature'
name = node.attrib['name'] name = node.attrib['name']
assert name not in reg.features assert name not in reg.features
reg.features[name] = feature(root) reg.features[name] = Feature(root)
reg.types[name] = reg.features[name] reg.types[name] = reg.features[name]
##----------------------------------------------------------------------------- ##-----------------------------------------------------------------------------
def parse_extensions(reg: registry, root): def parse_extensions(reg: Registry, root):
assert root.tag == 'extensions' assert root.tag == 'extensions'
for node in root.findall('./extension'): for node in root.findall('./extension'):
name = node.attrib['name'] name = node.attrib['name']
assert name not in reg.extensions assert name not in reg.extensions
reg.extensions[name] = extension(node) reg.extensions[name] = Extension(node)
############################################################################### ###############################################################################
def write_header(path: str, q: List[type]): def write_header(path: str, q: List[Type]):
with open(path, 'w') as dst: with open(path, 'w') as dst:
dst.write("#pragma once\n") dst.write("#pragma once\n")
@ -753,7 +753,7 @@ def write_header(path: str, q: List[type]):
# Specialise traits for device and instance types. # Specialise traits for device and instance types.
for obj in q: for obj in q:
if not isinstance(obj,handle): if not isinstance(obj, Handle):
continue continue
device_value = "true_type" if obj.has_parent("VkDevice", reg) else "false_type" device_value = "true_type" if obj.has_parent("VkDevice", reg) else "false_type"
@ -766,9 +766,9 @@ def write_header(path: str, q: List[type]):
##----------------------------------------------------------------------------- ##-----------------------------------------------------------------------------
def write_icd(path: str, q: List[type]): def write_icd(path: str, q: List[Type]):
with open(path, 'w') as icd: with open(path, 'w') as icd:
commands = [i for i in q if isinstance(i, command)] commands = [i for i in q if isinstance(i, Command)]
instance_commands = [i for i in commands if i.is_instance(reg)] instance_commands = [i for i in commands if i.is_instance(reg)]
device_commands = [i for i in commands if i.is_device(reg)] device_commands = [i for i in commands if i.is_device(reg)]
@ -813,7 +813,7 @@ def write_icd(path: str, q: List[type]):
##----------------------------------------------------------------------------- ##-----------------------------------------------------------------------------
def write_dispatch(path: str, q: List[type]): def write_dispatch(path: str, q: List[Type]):
with open(path, 'w') as dispatch: with open(path, 'w') as dispatch:
dispatch.write(""" dispatch.write("""
#include "../vk.hpp" #include "../vk.hpp"
@ -840,10 +840,10 @@ def write_dispatch(path: str, q: List[type]):
""") """)
for obj in (i for i in q if isinstance(i, command)): for obj in (i for i in q if isinstance(i, Command)):
first_arg = reg.types[obj.params[0].type] first_arg = reg.types[obj.params[0].type]
if not isinstance(first_arg, handle): if not isinstance(first_arg, Handle):
dispatch.write(f""" dispatch.write(f"""
extern "C" {obj.result} {rename(obj.name)} ({", ".join(p.param for p in obj.params)}) noexcept {{ extern "C" {obj.result} {rename(obj.name)} ({", ".join(p.param for p in obj.params)}) noexcept {{
unimplemented (); unimplemented ();
@ -907,7 +907,7 @@ if __name__ == '__main__':
root = tree.getroot() root = tree.getroot()
# Find a parser for each of the nodes in the XML # Find a parser for each of the nodes in the XML
reg = registry() reg = Registry()
for node in root: for node in root:
target = "parse_%s" % node.tag target = "parse_%s" % node.tag
globals()[target](reg, node) globals()[target](reg, node)
@ -916,15 +916,15 @@ if __name__ == '__main__':
# our environment. eg, use appropriate C++ types, or cruft library # our environment. eg, use appropriate C++ types, or cruft library
# wrappers. # wrappers.
reg.types['windows.h'].name = 'cruft/util/win32/windows.hpp' reg.types['windows.h'].name = 'cruft/util/win32/windows.hpp'
reg.types['void*'] = placeholder('void*') reg.types['void*'] = Placeholder('void*')
reg.types['nullptr'] = placeholder('nullptr') reg.types['nullptr'] = Placeholder('nullptr')
reg.types['VkEnum'] = aliastype('VkEnum', 'int32_t') reg.types['VkEnum'] = AliasType('VkEnum', 'int32_t')
reg.types['VK_DEFINE_NON_DISPATCHABLE_HANDLE'] = aliastype("VK_DEFINE_NON_DISPATCHABLE_HANDLE", "uint64_t") reg.types['VK_DEFINE_NON_DISPATCHABLE_HANDLE'] = AliasType("VK_DEFINE_NON_DISPATCHABLE_HANDLE", "uint64_t")
reg.types['VK_DEFINE_HANDLE'] = aliastype("VK_DEFINE_HANDLE", "void*") reg.types['VK_DEFINE_HANDLE'] = AliasType("VK_DEFINE_HANDLE", "void*")
reg.types['VK_NULL_HANDLE'] = aliasvalue("VK_NULL_HANDLE", "nullptr"); reg.types['VK_NULL_HANDLE'] = AliasValue("VK_NULL_HANDLE", "nullptr");
# Request serialisation of all features # Request serialisation of all features
features = [feature(n) for n in root.findall('./feature')] features = [Feature(n) for n in root.findall('./feature')]
features = dict((f.name,f) for f in features) features = dict((f.name,f) for f in features)
#reg.extensions['VK_KHR_surface'].apply(reg, platform='xcb') #reg.extensions['VK_KHR_surface'].apply(reg, platform='xcb')