Debian Codegraph @

js/src/frontend/GenerateReservedWords.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 import re
6 import sys
7
8
9 def read_reserved_word_list(
10 filename, enable_decorators, enable_explicit_resource_management
11 ):
12 macro_pat = re.compile(r"MACRO\(([^,]+), *[^,]+, *[^\)]+\)\s*\\?")
13
14 reserved_word_list = []
15 index = 0
16 with open(filename) as f:
17 for line in f:
18 m = macro_pat.search(line)
19 if m:
20 reserved_word = m.group(1)
21 if reserved_word == "accessor" and not enable_decorators:
22 continue
23 if reserved_word == "using" and not enable_explicit_resource_management:
24 continue
25 reserved_word_list.append((index, reserved_word))
26 index += 1
27
28 assert len(reserved_word_list) != 0
29
30 return reserved_word_list
31
32
33 def line(opt, s):
34 opt["output"].write("{}{}\n".format(" " * opt["indent_level"], s))
35
36
37 def indent(opt):
38 opt["indent_level"] += 1
39
40
41 def dedent(opt):
42 opt["indent_level"] -= 1
43
44
45 def span_and_count_at(reserved_word_list, column):
46 assert len(reserved_word_list) != 0
47
48 chars_dict = {}
49 for index, word in reserved_word_list:
50 chars_dict[ord(word[column])] = True
51
52 chars = sorted(chars_dict.keys())
53 return chars[-1] - chars[0] + 1, len(chars)
54
55
56 def optimal_switch_column(opt, reserved_word_list, columns, unprocessed_columns):
57 assert len(reserved_word_list) != 0
58 assert unprocessed_columns != 0
59
60 min_count = 0
61 min_span = 0
62 min_count_index = 0
63 min_span_index = 0
64
65 for index in range(0, unprocessed_columns):
66 span, count = span_and_count_at(reserved_word_list, columns[index])
67 assert span != 0
68
69 if span == 1:
70 assert count == 1
71 return 1, True
72
73 assert count != 1
74 if index == 0 or min_span > span:
75 min_span = span
76 min_span_index = index
77
78 if index == 0 or min_count > count:
79 min_count = count
80 min_count_index = index
81
82 if min_count <= opt["use_if_threshold"]:
83 return min_count_index, True
84
85 return min_span_index, False
86
87
88 def split_list_per_column(reserved_word_list, column):
89 assert len(reserved_word_list) != 0
90
91 column_dict = {}
92 for item in reserved_word_list:
93 index, word = item
94 per_column = column_dict.setdefault(word[column], [])
95 per_column.append(item)
96
97 return sorted(column_dict.items())
98
99
100 def generate_letter_switch(opt, unprocessed_columns, reserved_word_list, columns=None):
101 assert len(reserved_word_list) != 0
102
103 if not columns:
104 columns = range(0, unprocessed_columns)
105
106 if len(reserved_word_list) == 1:
107 index, word = reserved_word_list[0]
108
109 if unprocessed_columns == 0:
110 line(opt, f"JSRW_GOT_MATCH({index}) /* {word} */")
111 return
112
113 if unprocessed_columns > opt["char_tail_test_threshold"]:
114 line(opt, f"JSRW_TEST_GUESS({index}) /* {word} */")
115 return
116
117 conds = []
118 for column in columns[0:unprocessed_columns]:
119 quoted = repr(word[column])
120 conds.append(f"JSRW_AT({column})=={quoted}")
121
122 line(opt, "if ({}) {{".format(" && ".join(conds)))
123
124 indent(opt)
125 line(opt, f"JSRW_GOT_MATCH({index}) /* {word} */")
126 dedent(opt)
127
128 line(opt, "}")
129 line(opt, "JSRW_NO_MATCH()")
130 return
131
132 assert unprocessed_columns != 0
133
134 optimal_column_index, use_if = optimal_switch_column(
135 opt, reserved_word_list, columns, unprocessed_columns
136 )
137 optimal_column = columns[optimal_column_index]
138
139 # Make a copy to avoid breaking passed list.
140 columns = list(columns)
141 columns[optimal_column_index] = columns[unprocessed_columns - 1]
142
143 list_per_column = split_list_per_column(reserved_word_list, optimal_column)
144
145 if not use_if:
146 line(opt, f"switch (JSRW_AT({optimal_column})) {{")
147
148 for char, reserved_word_list_per_column in list_per_column:
149 quoted = repr(char)
150 if use_if:
151 line(opt, f"if (JSRW_AT({optimal_column}) == {quoted}) {{")
152 else:
153 line(opt, f" case {quoted}:")
154
155 indent(opt)
156 generate_letter_switch(
157 opt, unprocessed_columns - 1, reserved_word_list_per_column, columns
158 )
159 dedent(opt)
160
161 if use_if:
162 line(opt, "}")
163
164 if not use_if:
165 line(opt, "}")
166
167 line(opt, "JSRW_NO_MATCH()")
168
169
170 def split_list_per_length(reserved_word_list):
171 assert len(reserved_word_list) != 0
172
173 length_dict = {}
174 for item in reserved_word_list:
175 index, word = item
176 per_length = length_dict.setdefault(len(word), [])
177 per_length.append(item)
178
179 return sorted(length_dict.items())
180
181
182 def generate_switch(opt, reserved_word_list):
183 assert len(reserved_word_list) != 0
184
185 line(opt, "/*")
186 line(
187 opt,
188 f" * Generating switch for the list of {len(reserved_word_list)} entries:",
189 )
190 for index, word in reserved_word_list:
191 line(opt, f" * {word}")
192 line(opt, " */")
193
194 list_per_length = split_list_per_length(reserved_word_list)
195
196 use_if = False
197 if len(list_per_length) < opt["use_if_threshold"]:
198 use_if = True
199
200 if not use_if:
201 line(opt, "switch (JSRW_LENGTH()) {")
202
203 for length, reserved_word_list_per_length in list_per_length:
204 if use_if:
205 line(opt, f"if (JSRW_LENGTH() == {length}) {{")
206 else:
207 line(opt, f" case {length}:")
208
209 indent(opt)
210 generate_letter_switch(opt, length, reserved_word_list_per_length)
211 dedent(opt)
212
213 if use_if:
214 line(opt, "}")
215
216 if not use_if:
217 line(opt, "}")
218 line(opt, "JSRW_NO_MATCH()")
219
220
221 def main(output, reserved_words_h, *args):
222 enable_decorators = False
223 enable_explicit_resource_management = False
224 for arg in args:
225 if arg == "--enable-decorators":
226 enable_decorators = True
227 elif arg == "--enable-explicit-resource-management":
228 enable_explicit_resource_management = True
229 else:
230 raise ValueError("Unknown argument: " + arg)
231
232 reserved_word_list = read_reserved_word_list(
233 reserved_words_h, enable_decorators, enable_explicit_resource_management
234 )
235
236 opt = {
237 "indent_level": 1,
238 "use_if_threshold": 3,
239 "char_tail_test_threshold": 4,
240 "output": output,
241 }
242 generate_switch(opt, reserved_word_list)
243
244
245 if __name__ == "__main__":
246 main(sys.stdout, *sys.argv[1:])