Skip to content

Commit c0fa1ef

Browse files
authored
python: Use type annotations compatible with python 3.8 (KhronosGroup#6119)
1 parent 3935361 commit c0fa1ef

File tree

4 files changed

+43
-40
lines changed

4 files changed

+43
-40
lines changed

utils/Table/Context.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
#from typing import *
1717
from enum import IntEnum
18+
from typing import Dict, List
1819
from . IndexRange import *
1920
from . StringList import *
2021

@@ -55,7 +56,7 @@ class Context():
5556
5657
It is a two-level mapping of Python type:
5758
58-
dict[str,dict[StringList,IndexRange]]
59+
Dict[str,dict[StringList,IndexRange]]
5960
6061
where
6162
@@ -76,14 +77,14 @@ class Context():
7677
"""
7778
def __init__(self) -> None:
7879
self.string_total_len: int = 0 # Sum of lengths of all strings in string_buffer
79-
self.string_buffer: list[str] = []
80-
self.strings: dict[str, IndexRange] = {}
81-
self.ir_to_string: dict[IndexRange, str] = {} # Inverse of self.strings
80+
self.string_buffer: List[str] = []
81+
self.strings: Dict[str, IndexRange] = {}
82+
self.ir_to_string: Dict[IndexRange, str] = {} # Inverse of self.strings
8283

83-
self.range_buffer: dict[str,list[IndexRange]] = {}
84+
self.range_buffer: Dict[str,List[IndexRange]] = {}
8485
# We need StringList here because it's hashable, and so it
8586
# can be used as the key for a dict.
86-
self.ranges: dict[str,dict[StringList,IndexRange]] = {}
87+
self.ranges: Dict[str,Dict[StringList,IndexRange]] = {}
8788

8889
def GetString(self, ir: IndexRange) -> str:
8990
if ir in self.ir_to_string:
@@ -106,7 +107,7 @@ def AddString(self, s: str) -> IndexRange:
106107
self.string_buffer.append(s)
107108
return ir
108109

109-
def AddStringList(self, kind: str, words: list[str]) -> IndexRange:
110+
def AddStringList(self, kind: str, words: List[str]) -> IndexRange:
110111
"""
111112
Ensures a list of strings is recorded in range_buffer[kind], and
112113
returns its location in the range_buffer[kind].
@@ -115,7 +116,7 @@ def AddStringList(self, kind: str, words: list[str]) -> IndexRange:
115116
"""
116117
l = StringList(words)
117118

118-
entry: dict[StringList, IndexRange] = self.ranges.get(kind, {})
119+
entry: Dict[StringList, IndexRange] = self.ranges.get(kind, {})
119120
if kind not in self.ranges:
120121
self.ranges[kind] = entry
121122
self.range_buffer[kind] = []

utils/Table/Operand.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
1515

16-
from typing import Any
16+
from typing import List
1717

1818
class Operand():
1919
def __init__(self, json: dict) -> None:
@@ -42,25 +42,25 @@ def value(self) -> int:
4242
raise Exception("operand needs a value integer or string")
4343

4444
@property
45-
def capabilities(self) -> list[str]:
45+
def capabilities(self) -> List[str]:
4646
return self._obj.get('capabilities',[])
4747

4848
@property
49-
def extensions(self) -> list[str]:
49+
def extensions(self) -> List[str]:
5050
return self._obj.get('extensions',[])
5151

5252
@property
53-
def aliases(self) -> list[str]:
53+
def aliases(self) -> List[str]:
5454
return self._obj.get('aliases',[])
5555

5656
@property
57-
def parameters(self) -> list[dict]:
57+
def parameters(self) -> List[dict]:
5858
return self._obj.get('parameters',[])
5959

6060
@property
61-
def version(self) -> str | None:
61+
def version(self): # -> str | None # Invald in Python 3.8
6262
return self._obj.get('version',None)
6363

6464
@property
65-
def lastVersion(self) -> str | None:
65+
def lastVersion(self): # -> str | None # Invalid in Python 3.8
6666
return self._obj.get('lastVersion',None)

utils/Table/StringList.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,14 @@
1414
# limitations under the License.
1515

1616
import functools
17+
from typing import List
1718

1819
class StringList(list):
1920
"""
2021
A hashable ordered list of strings.
2122
This can be used as the key for a dictionary.
2223
"""
23-
def __init__(self, strs: list[str]) -> None:
24+
def __init__(self, strs: List[str]) -> None:
2425
super().__init__(strs)
2526

2627
def __hash__(self) -> int: # type: ignore[override]

utils/ggt.py

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import os.path
2222
import re
2323
import sys
24+
from typing import Dict, List, Tuple
2425

2526
# Find modules relative to the directory containing this script.
2627
# This is needed for hermetic Bazel builds, where the Table files are bundled
@@ -45,7 +46,7 @@
4546

4647
MODE='new'
4748

48-
def convert_min_required_version(version: str | None) -> str:
49+
def convert_min_required_version(version): # (version: str | None) -> str
4950
"""Converts the minimal required SPIR-V version encoded in the grammar to
5051
the symbol in SPIRV-Tools."""
5152
if version is None:
@@ -55,7 +56,7 @@ def convert_min_required_version(version: str | None) -> str:
5556
return 'SPV_SPIRV_VERSION_WORD({})'.format(version.replace('.', ','))
5657

5758

58-
def convert_max_required_version(version: str | None) -> str:
59+
def convert_max_required_version(version): # (version: str | None) -> str
5960
"""Converts the maximum required SPIR-V version encoded in the grammar to
6061
the symbol in SPIRV-Tools."""
6162
if version is None:
@@ -130,7 +131,7 @@ def ctype(kind: str, quantifier: str) -> str:
130131
re.sub(r'([a-z])([A-Z])', r'\1_\2', kind).upper())
131132

132133

133-
def convert_operand_kind(obj: dict[str, str]) -> str:
134+
def convert_operand_kind(obj: Dict[str, str]) -> str:
134135
"""Returns the corresponding operand type used in spirv-tools for the given
135136
operand kind and quantifier used in the JSON grammar.
136137
@@ -155,12 +156,12 @@ class Grammar():
155156
and enum tables.
156157
Assumes an index range is emitted by printing an IndexRange object.
157158
"""
158-
def __init__(self, extensions: list[str], operand_kinds:list[dict]) -> None:
159+
def __init__(self, extensions: List[str], operand_kinds:List[dict]) -> None:
159160
self.context = Context()
160161
self.extensions = extensions
161162
self.operand_kinds = sorted(operand_kinds, key = lambda ok: convert_operand_kind(ok))
162-
self.header_decls: list[str] = [self.IndexRangeDecls()]
163-
self.body_decls: list[str] = []
163+
self.header_decls: List[str] = [self.IndexRangeDecls()]
164+
self.body_decls: List[str] = []
164165

165166
if len(self.operand_kinds) == 0:
166167
raise Exception("operand_kinds should be a non-empty list")
@@ -272,21 +273,21 @@ def ComputeOperandTables(self) -> None:
272273
};
273274
""")
274275

275-
def ShouldEmit(operand_kind_json: dict[str,any]):
276+
def ShouldEmit(operand_kind_json: Dict[str,any]):
276277
""" Returns true if we should emit a table for the given
277278
operand kind.
278279
"""
279280
category = operand_kind_json.get('category')
280281
return category in ['ValueEnum', 'BitEnum']
281282

282283
# Populate kOperandNames
283-
operand_names: list[tuple[IndexRange,int]] = []
284-
name_range_for_kind: dict[str,IndexRange] = {}
284+
operand_names: List[Tuple[IndexRange,int]] = []
285+
name_range_for_kind: Dict[str,IndexRange] = {}
285286
for operand_kind_json in self.operand_kinds:
286287
kind_key: str = convert_operand_kind(operand_kind_json)
287288
if ShouldEmit(operand_kind_json):
288289
operands = [Operand(o) for o in operand_kind_json['enumerants']]
289-
tuples: list[tuple[str,int,str]] = []
290+
tuples: List[Tuple[str,int,str]] = []
290291
for o in operands:
291292
tuples.append((o.enumerant, o.value, kind_key))
292293
for a in o.aliases:
@@ -297,13 +298,13 @@ def ShouldEmit(operand_kind_json: dict[str,any]):
297298
operand_names.extend(ir_tuples)
298299
else:
299300
pass
300-
operand_name_strings: list[str] = []
301+
operand_name_strings: List[str] = []
301302
for i in range(0, len(operand_names)):
302303
ir, value, kind_key = operand_names[i]
303304
operand_name_strings.append('{{{}, {}}}, // {} {} in {}'.format(
304305
str(ir),value,i,self.context.GetString(ir),kind_key))
305306

306-
parts: list[str] = []
307+
parts: List[str] = []
307308
parts.append("""// Operand names and values, ordered by (operand kind, name)
308309
// The fields in order are:
309310
// name, either the primary name or an alias, indexing into kStrings
@@ -332,13 +333,13 @@ def ShouldEmit(operand_kind_json: dict[str,any]):
332333
self.body_decls.extend(parts)
333334

334335
# Populate kOperandsByValue
335-
operands_by_value: list[str] = []
336-
operands_by_value_by_kind: dict[str,IndexRange] = {}
336+
operands_by_value: List[str] = []
337+
operands_by_value_by_kind: Dict[str,IndexRange] = {}
337338
for operand_kind_json in self.operand_kinds:
338339
kind_key: str = convert_operand_kind(operand_kind_json)
339340
if ShouldEmit(operand_kind_json):
340341
operands = [Operand(o) for o in operand_kind_json['enumerants']]
341-
operand_descs: list[str] = []
342+
operand_descs: List[str] = []
342343
for o in sorted(operands, key = lambda o: o.value):
343344
suboperands = [convert_operand_kind(p) for p in o.parameters]
344345
desc = [
@@ -433,19 +434,19 @@ def ComputeInstructionTables(self, insts) -> None:
433434
""")
434435

435436
# Create the sorted list of opcode strings, without the 'Op' prefix.
436-
opcode_name_entries: list[str] = []
437-
name_value_pairs: list[tuple[str,int]] = []
437+
opcode_name_entries: List[str] = []
438+
name_value_pairs: List[Tuple[str,int]] = []
438439
for i in insts:
439440
name_value_pairs.append((i['opname'][2:], i['opcode']))
440441
for a in i.get('aliases',[]):
441442
name_value_pairs.append((a[2:], i['opcode']))
442443
name_value_pairs = sorted(name_value_pairs)
443-
inst_name_strings: list[str] = []
444+
inst_name_strings: List[str] = []
444445
for i in range(0, len(name_value_pairs)):
445446
name, value = name_value_pairs[i]
446447
ir = self.context.AddString(name)
447448
inst_name_strings.append('{{{}, {}}}, // {} {}'.format(str(ir),value,i,name))
448-
parts: list[str] = []
449+
parts: List[str] = []
449450
parts.append("""// Opcode strings (without the 'Op' prefix) and opcode values, ordered by name.
450451
// The fields in order are:
451452
// name, either the primary name or an alias, indexing into kStrings
@@ -456,9 +457,9 @@ def ComputeInstructionTables(self, insts) -> None:
456457
self.body_decls.extend(parts)
457458

458459
# Create the array of InstructionDesc
459-
lines: list[str] = []
460+
lines: List[str] = []
460461
for inst in insts:
461-
parts: list[str] = []
462+
parts: List[str] = []
462463

463464
opname: str = inst['opname']
464465

@@ -530,15 +531,15 @@ def c_str(s: str):
530531
"""
531532
return '"{}\\0"'.format(json.dumps(s).strip('"'))
532533

533-
parts: list[str] = []
534+
parts: List[str] = []
534535
parts.append("// Array of characters, referenced by IndexRanges elsewhere.")
535536
parts.append("// Each IndexRange denotes a string.")
536537
parts.append('static const char kStrings[] =');
537538
parts.extend([' {} // {}'.format(c_str(s), str(self.context.strings[s])) for s in self.context.string_buffer])
538539
parts.append(';\n');
539540
self.body_decls.extend(parts);
540541

541-
parts: list[str] = []
542+
parts: List[str] = []
542543
parts.append("""// Array of IndexRanges, where each represents a string by referencing
543544
// the kStrings table.
544545
// This array contains all sequences of alias strings used in the grammar.
@@ -588,7 +589,7 @@ def c_str(s: str):
588589
parts.append('};\n');
589590
self.body_decls.extend(parts);
590591

591-
parts: list[str] = []
592+
parts: List[str] = []
592593
parts.append("// Returns the name of an extension, as an index into kStrings")
593594
parts.append("IndexRange ExtensionToIndexRange(Extension extension) {\n switch(extension) {")
594595
for e in self.extensions:

0 commit comments

Comments
 (0)