Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(450)

Side by Side Diff: third_party/WebKit/Source/platform/instrumentation/InstrumentingProbesCodeGenerator.py

Issue 2772613002: [instrumentation] Rename InspectorInstrumentation into CoreProbes (Closed)
Patch Set: fix typo Created 3 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 # Copyright 2017 The Chromium Authors. All rights reserved.
2 # Use of this source code is governed by a BSD-style license that can be
3 # found in the LICENSE file.
4
5 import optparse
6 import os.path
7 import re
8 import sys
9
10 # Path handling for libraries and templates
11 # Paths have to be normalized because Jinja uses the exact template path to
12 # determine the hash used in the cache filename, and we need a pre-caching step
13 # to be concurrency-safe. Use absolute path because __file__ is absolute if
14 # module is imported, and relative if executed directly.
15 # If paths differ between pre-caching and individual file compilation, the cache
16 # is regenerated, which causes a race condition and breaks concurrent build,
17 # since some compile processes will try to read the partially written cache.
18 module_path, module_filename = os.path.split(os.path.realpath(__file__))
19 templates_dir = module_path
20 third_party_dir = os.path.normpath(os.path.join(
21 module_path, os.pardir, os.pardir, os.pardir, os.pardir))
22 # jinja2 is in chromium's third_party directory.
23 # Insert at 1 so at front to override system libraries, and
24 # after path[0] == invoking script dir
25 sys.path.insert(1, third_party_dir)
26 import jinja2
27
28
29 def to_lower_case(name):
30 return name[:1].lower() + name[1:]
31
32
33 def agent_name_to_class(agent_name):
34 if agent_name == "Performance":
35 return "PerformanceMonitor"
36 elif agent_name == "TraceEvents":
37 return "InspectorTraceEvents"
38 elif agent_name == "PlatformTraceEvents":
39 return "PlatformTraceEventsAgent"
40 else:
41 return "Inspector%sAgent" % agent_name
42
43
44 def initialize_jinja_env(cache_dir):
45 jinja_env = jinja2.Environment(
46 loader=jinja2.FileSystemLoader(templates_dir),
47 # Bytecode cache is not concurrency-safe unless pre-cached:
48 # if pre-cached this is read-only, but writing creates a race condition.
49 bytecode_cache=jinja2.FileSystemBytecodeCache(cache_dir),
50 keep_trailing_newline=True, # newline-terminate generated files
51 lstrip_blocks=True, # so can indent control flow tags
52 trim_blocks=True)
53 jinja_env.filters.update({
54 "to_lower_case": to_lower_case,
55 "agent_name_to_class": agent_name_to_class})
56 jinja_env.add_extension('jinja2.ext.loopcontrols')
57 return jinja_env
58
59
60 def match_and_consume(pattern, source):
61 match = re.match(pattern, source)
62 if match:
63 return match, source[len(match.group(0)):].strip()
64 return None, source
65
66
67 def load_model_from_idl(source):
68 source = re.sub(r"//.*", "", source) # Remove line comments
69 source = re.sub(r"/\*(.|\n)*?\*/", "", source, re.MULTILINE) # Remove block comments
70 source = re.sub(r"\]\s*?\n\s*", "] ", source) # Merge the method annotation with the next line
71 source = source.strip()
72 model = []
73 while len(source):
74 match, source = match_and_consume(r"interface\s(\w*)\s?\{([^\{]*)\}", so urce)
75 if not match:
76 sys.stderr.write("Cannot parse %s\n" % source[:100])
77 sys.exit(1)
78 model.append(File(match.group(1), match.group(2)))
79 return model
80
81
82 class File(object):
83 def __init__(self, name, source):
84 self.name = name
85 self.header_name = self.name + "Inl"
86 self.includes = [include_inspector_header(base_name)]
87 self.forward_declarations = []
88 self.declarations = []
89 self.defines = []
90 for line in map(str.strip, source.split("\n")):
91 line = re.sub(r"\s{2,}", " ", line).strip() # Collapse whitespace
92 if len(line) == 0:
93 continue
94 if line.startswith("#define"):
95 self.defines.append(line)
96 elif line.startswith("#include"):
97 self.includes.append(line)
98 elif line.startswith("class ") or line.startswith("struct "):
99 self.forward_declarations.append(line)
100 else:
101 self.declarations.append(Method(line))
102 self.includes.sort()
103 self.forward_declarations.sort()
104
105
106 def include_header(name):
107 return "#include \"%s.h\"" % name
108
109
110 def include_inspector_header(name):
111 if name == "PerformanceMonitor":
112 return include_header("core/frame/" + name)
113 if name == "PlatformInstrumentation":
114 return include_header("platform/instrumentation/" + name)
115 return include_header("core/inspector/" + name)
116
117
118 class Method(object):
119 def __init__(self, source):
120 match = re.match(r"(\[[\w|,|=|\s]*\])?\s?(\w*\*?) (\w*)\((.*)\)\s?;", so urce)
121 if not match:
122 sys.stderr.write("Cannot parse %s\n" % source)
123 sys.exit(1)
124
125 self.options = []
126 if match.group(1):
127 options_str = re.sub(r"\s", "", match.group(1)[1:-1])
128 if len(options_str) != 0:
129 self.options = options_str.split(",")
130
131 self.return_type = match.group(2)
132 self.name = match.group(3)
133 self.is_scoped = self.return_type == ""
134
135 # Splitting parameters by a comma, assuming that attribute lists contain no more than one attribute.
136 self.params = map(Parameter, map(str.strip, match.group(4).split(",")))
137
138 self.returns_value = self.return_type != "" and self.return_type != "voi d"
139 if self.return_type == "bool":
140 self.default_return_value = "false"
141 elif self.returns_value:
142 sys.stderr.write("Can only return bool: %s\n" % self.name)
143 sys.exit(1)
144
145 self.agents = [option for option in self.options if "=" not in option]
146
147 if self.returns_value and len(self.agents) > 1:
148 sys.stderr.write("Can only return value from a single agent: %s\n" % self.name)
149 sys.exit(1)
150
151
152 class Parameter(object):
153 def __init__(self, source):
154 self.options = []
155 match, source = match_and_consume(r"\[(\w*)\]", source)
156 if match:
157 self.options.append(match.group(1))
158
159 parts = map(str.strip, source.split("="))
160 self.default_value = parts[1] if len(parts) != 1 else None
161
162 param_decl = parts[0]
163 min_type_tokens = 2 if re.match("(const|unsigned long) ", param_decl) el se 1
164
165 if len(param_decl.split(" ")) > min_type_tokens:
166 parts = param_decl.split(" ")
167 self.type = " ".join(parts[:-1])
168 self.name = parts[-1]
169 else:
170 self.type = param_decl
171 self.name = build_param_name(self.type)
172
173 self.value = self.name
174 self.is_prp = re.match(r"PassRefPtr<", param_decl) is not None
175 if self.is_prp:
176 self.name = "prp" + self.name[0].upper() + self.name[1:]
177 self.inner_type = re.match(r"PassRefPtr<(.+)>", param_decl).group(1)
178
179 if self.type[-1] == "*" and "char" not in self.type:
180 self.member_type = "Member<%s>" % self.type[:-1]
181 else:
182 self.member_type = self.type
183
184
185 def build_param_name(param_type):
186 base_name = re.match(r"(const |PassRefPtr<)?(\w*)", param_type).group(2)
187 return "param" + base_name
188
189
190 cmdline_parser = optparse.OptionParser()
191 cmdline_parser.add_option("--output_dir")
192 cmdline_parser.add_option("--template_dir")
193
194 try:
195 arg_options, arg_values = cmdline_parser.parse_args()
196 if len(arg_values) != 1:
197 raise Exception("Exactly one plain argument expected (found %s)" % len(a rg_values))
198 input_path = arg_values[0]
199 output_dirpath = arg_options.output_dir
200 if not output_dirpath:
201 raise Exception("Output directory must be specified")
202 except Exception:
203 # Work with python 2 and 3 http://docs.python.org/py3k/howto/pyporting.html
204 exc = sys.exc_info()[1]
205 sys.stderr.write("Failed to parse command-line arguments: %s\n\n" % exc)
206 sys.stderr.write("Usage: <script> --output_dir <output_dir> InstrumentingPro bes.idl\n")
207 exit(1)
208
209 jinja_env = initialize_jinja_env(output_dirpath)
210 all_agents = set()
211 all_defines = []
212 base_name = os.path.splitext(os.path.basename(input_path))[0]
213
214 fin = open(input_path, "r")
215 files = load_model_from_idl(fin.read())
216 fin.close()
217
218 for f in files:
219 for declaration in f.declarations:
220 for agent in declaration.agents:
221 all_agents.add(agent)
222 all_defines += f.defines
223
224 template_context = {
225 "files": files,
226 "agents": all_agents,
227 "defines": all_defines,
228 "name": base_name,
229 "input_file": os.path.basename(input_path)
230 }
231 cpp_template = jinja_env.get_template("/InstrumentingProbesImpl_cpp.template")
232 cpp_file = open(output_dirpath + "/" + base_name + "Impl.cpp", "w")
233 cpp_file.write(cpp_template.render(template_context))
234 cpp_file.close()
235
236 agents_h_template = jinja_env.get_template("/InstrumentingAgents_h.template")
237 agents_h_file = open(output_dirpath + "/" + base_name + "Agents.h", "w")
238 agents_h_file.write(agents_h_template.render(template_context))
239 agents_h_file.close()
240
241 for f in files:
242 template_context["file"] = f
243 h_template = jinja_env.get_template("/InstrumentingProbesImpl_h.template")
244 h_file = open(output_dirpath + "/" + f.header_name + ".h", "w")
245 h_file.write(h_template.render(template_context))
246 h_file.close()
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698