95d5b5d5a5e8d28f2fdc76ecbfc509cf28a982c9
[WebKit-https.git] / WebCore / inspector / CodeGeneratorInspector.pm
1 # Copyright (c) 2010 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 package CodeGeneratorInspector;
6
7 use strict;
8
9 use Class::Struct;
10 use File::stat;
11
12 my %typeTransform;
13 $typeTransform{"InspectorClient"} = {
14     "forward" => "InspectorClient",
15     "header" => "InspectorClient.h",
16 };
17 $typeTransform{"Backend"} = {
18     "forward" => "InspectorBackend",
19     "header" => "InspectorBackend.h",
20     "domainAccessor" => "m_inspectorController->inspectorBackend()",
21 };
22 $typeTransform{"Controller"} = {
23     "forwardHeader" => "InspectorController.h",
24     "domainAccessor" => "m_inspectorController",
25 };
26 $typeTransform{"Debug"} = {
27     "forward" => "InspectorDebuggerAgent",
28     "header" => "InspectorDebuggerAgent.h",
29     "domainAccessor" => "m_inspectorController->debuggerAgent()",
30 };
31 $typeTransform{"Resource"} = {
32     "forward" => "InspectorResourceAgent",
33     "header" => "InspectorResourceAgent.h",
34     "domainAccessor" => "m_inspectorController->m_resourceAgent",
35 };
36 $typeTransform{"DOM"} = {
37     "forward" => "InspectorDOMAgent",
38     "header" => "InspectorDOMAgent.h",
39     "domainAccessor" => "m_inspectorController->domAgent()",
40 };
41 $typeTransform{"CSS"} = {
42     "forward" => "InspectorCSSAgent",
43     "header" => "InspectorCSSAgent.h",
44     "domainAccessor" => "m_inspectorController->cssAgent()",
45 };
46 $typeTransform{"ApplicationCache"} = {
47     "forward" => "InspectorApplicationCacheAgent",
48     "header" => "InspectorApplicationCacheAgent.h",
49     "domainAccessor" => "m_inspectorController->applicationCacheAgent()",
50 };
51 $typeTransform{"FileSystem"} = {
52     "forward" => "InspectorFileSystemAgent",
53     "header" => "InspectorFileSystemAgent.h",
54     "domainAccessor" => "m_inspectorController->fileSystemAgent()",
55 };
56 $typeTransform{"Profiler"} = {
57     "forward" => "InspectorProfilerAgent",
58     "header" => "InspectorProfilerAgent.h",
59     "domainAccessor" => "m_inspectorController->profilerAgent()",
60 };
61 $typeTransform{"Frontend"} = {
62     "forward" => "InspectorFrontend",
63     "header" => "InspectorFrontend.h",
64 };
65 $typeTransform{"PassRefPtr"} = {
66     "forwardHeader" => "wtf/PassRefPtr.h",
67 };
68 $typeTransform{"Object"} = {
69     "param" => "PassRefPtr<InspectorObject>",
70     "variable" => "RefPtr<InspectorObject>",
71     "defaultValue" => "InspectorObject::create()",
72     "forward" => "InspectorObject",
73     "header" => "InspectorValues.h",
74     "JSONType" => "Object"
75 };
76 $typeTransform{"Array"} = {
77     "param" => "PassRefPtr<InspectorArray>",
78     "variable" => "RefPtr<InspectorArray>",
79     "defaultValue" => "InspectorArray::create()",
80     "forward" => "InspectorArray",
81     "header" => "InspectorValues.h",
82     "JSONType" => "Array"
83 };
84 $typeTransform{"Value"} = {
85     "param" => "PassRefPtr<InspectorValue>",
86     "variable" => "RefPtr<InspectorValue>",
87     "defaultValue" => "InspectorValue::null()",
88     "forward" => "InspectorValue",
89     "header" => "InspectorValues.h",
90     "JSONType" => "Value"
91 };
92 $typeTransform{"String"} = {
93     "param" => "const String&",
94     "variable" => "String",
95     "return" => "String",
96     "defaultValue" => "\"\"",
97     "forwardHeader" => "wtf/Forward.h",
98     "header" => "PlatformString.h",
99     "JSONType" => "String"
100 };
101 $typeTransform{"long"} = {
102     "param" => "long",
103     "variable" => "long",
104     "defaultValue" => "0",
105     "forward" => "",
106     "header" => "",
107     "JSONType" => "Number"
108 };
109 $typeTransform{"int"} = {
110     "param" => "int",
111     "variable" => "int",
112     "defaultValue" => "0",
113     "forward" => "",
114     "header" => "",
115     "JSONType" => "Number",
116 };
117 $typeTransform{"unsigned long"} = {
118     "param" => "unsigned long",
119     "variable" => "unsigned long",
120     "defaultValue" => "0u",
121     "forward" => "",
122     "header" => "",
123     "JSONType" => "Number"
124 };
125 $typeTransform{"unsigned int"} = {
126     "param" => "unsigned int",
127     "variable" => "unsigned int",
128     "defaultValue" => "0u",
129     "forward" => "",
130     "header" => "",
131     "JSONType" => "Number"
132 };
133 $typeTransform{"double"} = {
134     "param" => "double",
135     "variable" => "double",
136     "defaultValue" => "0.0",
137     "forward" => "",
138     "header" => "",
139     "JSONType" => "Number"
140 };
141 $typeTransform{"boolean"} = {
142     "param" => "bool",
143     "variable"=> "bool",
144     "defaultValue" => "false",
145     "forward" => "",
146     "header" => "",
147     "JSONType" => "Boolean"
148 };
149 $typeTransform{"void"} = {
150     "forward" => "",
151     "header" => ""
152 };
153
154 # Default License Templates
155
156 my $licenseTemplate = << "EOF";
157 // Copyright (c) 2010 The Chromium Authors. All rights reserved.
158 // Use of this source code is governed by a BSD-style license that can be
159 // found in the LICENSE file.
160 EOF
161
162 my $codeGenerator;
163 my $outputDir;
164 my $outputHeadersDir;
165 my $writeDependencies;
166 my $verbose;
167
168 my $namespace;
169
170 my $backendClassName;
171 my $backendJSStubName;
172 my %backendTypes;
173 my %backendMethods;
174 my @backendMethodsImpl;
175 my $backendConstructor;
176 my @backendConstantDeclarations;
177 my @backendConstantDefinitions;
178 my $backendFooter;
179 my @backendStubJS;
180
181 my $frontendClassName;
182 my %frontendTypes;
183 my %frontendMethods;
184 my @frontendMethodsImpl;
185 my $frontendConstructor;
186 my @frontendConstantDeclarations;
187 my @frontendConstantDefinitions;
188 my $frontendFooter;
189
190 # Default constructor
191 sub new
192 {
193     my $object = shift;
194     my $reference = { };
195
196     $codeGenerator = shift;
197     $outputDir = shift;
198     $outputHeadersDir = shift;
199     shift; # $useLayerOnTop
200     shift; # $preprocessor
201     $writeDependencies = shift;
202     $verbose = shift;
203
204     bless($reference, $object);
205     return $reference;
206 }
207
208 # Params: 'idlDocument' struct
209 sub GenerateModule
210 {
211     my $object = shift;
212     my $dataNode = shift;
213
214     $namespace = $dataNode->module;
215     $namespace =~ s/core/WebCore/;
216 }
217
218 # Params: 'idlDocument' struct
219 sub GenerateInterface
220 {
221     my $object = shift;
222     my $interface = shift;
223     my $defines = shift;
224
225     my $className = $interface->name;
226
227     $frontendClassName = $className . "Frontend";
228     $frontendConstructor = "    ${frontendClassName}(InspectorClient* inspectorClient) : m_inspectorClient(inspectorClient) { }";
229     $frontendFooter = "    InspectorClient* m_inspectorClient;";
230     $frontendTypes{"String"} = 1;
231     $frontendTypes{"InspectorClient"} = 1;
232     $frontendTypes{"PassRefPtr"} = 1;
233
234     $backendClassName = $className . "BackendDispatcher";
235     $backendJSStubName = $className . "BackendStub";
236     my @backendHead;
237     push(@backendHead, "    ${backendClassName}(InspectorController* inspectorController) : m_inspectorController(inspectorController) { }");
238     push(@backendHead, "    void reportProtocolError(const long callId, const String& errorText) const;");
239     push(@backendHead, "    void dispatch(const String& message);");
240     push(@backendHead, "    static bool getCommandName(const String& message, String* result);");
241     $backendConstructor = join("\n", @backendHead);
242     $backendFooter = "    InspectorController* m_inspectorController;";
243     $backendTypes{"Controller"} = 1;
244     $backendTypes{"InspectorClient"} = 1;
245     $backendTypes{"PassRefPtr"} = 1;
246     $backendTypes{"Object"} = 1;
247
248     push(@backendMethodsImpl, generateBackendMessageParser());
249     generateFunctions($interface);
250
251     # Make dispatcher methods private on the backend.
252     push(@backendConstantDeclarations, "");
253     push(@backendConstantDeclarations, "private:");
254 }
255
256 sub generateFunctions
257 {
258     my $interface = shift;
259
260     foreach my $function (@{$interface->functions}) {
261         if ($function->signature->extendedAttributes->{"notify"}) {
262             generateFrontendFunction($function);
263         } else {
264             generateBackendFunction($function);
265         }
266     }
267     push(@backendMethodsImpl, generateBackendDispatcher());
268     push(@backendMethodsImpl, generateBackendReportProtocolError());
269
270     my @backendGettersDeclarations;
271     push(@backendGettersDeclarations, "");
272     push(@backendGettersDeclarations, "private:");
273     foreach my $type (keys %backendTypes) {
274         if ($typeTransform{$type}{"JSONType"}) {
275             push(@backendMethodsImpl, generateArgumentGetters($type, \@backendGettersDeclarations));
276         }
277     }
278     push(@backendConstantDeclarations, @backendGettersDeclarations);
279
280     @backendStubJS = generateBackendStubJS($interface);
281 }
282
283 sub generateFrontendFunction
284 {
285     my $function = shift;
286
287     my $functionName = $function->signature->name;
288
289     my @argsFiltered = grep($_->direction eq "out", @{$function->parameters}); # just keep only out parameters for frontend interface.
290     map($frontendTypes{$_->type} = 1, @argsFiltered); # register required types.
291     my $arguments = join(", ", map($typeTransform{$_->type}->{"param"} . " " . $_->name, @argsFiltered)); # prepare arguments for function signature.
292
293     my $signature = "    void ${functionName}(${arguments});";
294     if (!$frontendMethods{${signature}}) {
295         $frontendMethods{${signature}} = 1;
296
297         my @function;
298         push(@function, "void ${frontendClassName}::${functionName}(${arguments})");
299         push(@function, "{");
300         push(@function, "    RefPtr<InspectorObject> ${functionName}Message = InspectorObject::create();");
301         push(@function, "    ${functionName}Message->setString(\"type\", \"event\");");
302         push(@function, "    ${functionName}Message->setString(\"event\", \"$functionName\");");
303         push(@function, "    RefPtr<InspectorObject> payloadDataObject = InspectorObject::create();");
304         my @pushArguments = map("    payloadDataObject->set" . $typeTransform{$_->type}->{"JSONType"} . "(\"" . $_->name . "\", " . $_->name . ");", @argsFiltered);
305         push(@function, @pushArguments);
306         push(@function, "    ${functionName}Message->setObject(\"data\", payloadDataObject);");
307         push(@function, "    m_inspectorClient->sendMessageToFrontend(${functionName}Message->toJSONString());");
308
309         push(@function, "}");
310         push(@function, "");
311         push(@frontendMethodsImpl, @function);
312     }
313 }
314
315 sub generateBackendFunction
316 {
317     my $function = shift;
318
319     my $functionName = $function->signature->name;
320
321     push(@backendConstantDeclarations, "    static const char* ${functionName}Cmd;");
322     push(@backendConstantDefinitions, "const char* ${backendClassName}::${functionName}Cmd = \"${functionName}\";");
323
324     map($backendTypes{$_->type} = 1, @{$function->parameters}); # register required types
325     my @inArgs = grep($_->direction eq "in" && !($_->name eq "callId") , @{$function->parameters});
326     my @outArgs = grep($_->direction eq "out", @{$function->parameters});
327
328     my $signature = "    void ${functionName}(long callId, InspectorObject* requestMessageObject);";
329     !$backendMethods{${signature}} || die "Duplicate function was detected for signature '$signature'.";
330     $backendMethods{${signature}} = $functionName;
331
332     my @function;
333     my $requestMessageObject = scalar(@inArgs) ? " requestMessageObject" : "";
334     push(@function, "void ${backendClassName}::${functionName}(long callId, InspectorObject*$requestMessageObject)");
335     push(@function, "{");
336     push(@function, "    RefPtr<InspectorArray> protocolErrors = InspectorArray::create();");
337     push(@function, "");
338
339     my $domain = $function->signature->extendedAttributes->{"handler"} || "Controller";
340     my $domainAccessor = $typeTransform{$domain}->{"domainAccessor"};
341     $backendTypes{$domain} = 1;
342     push(@function, "    if (!$domainAccessor)");
343     push(@function, "        protocolErrors->pushString(\"Protocol Error: $domain handler is not available.\");");
344     push(@function, "");
345
346     # declare local variables for out arguments.
347     push(@function, map("    " . $typeTransform{$_->type}->{"variable"} . " " . $_->name . " = " . $typeTransform{$_->type}->{"defaultValue"} . ";", @outArgs));
348
349     my $indent = "";
350     if (scalar(@inArgs)) {
351         # declare variables for all 'in' args;
352         push(@function, "    if (RefPtr<InspectorObject> argumentsContainer = getObject(requestMessageObject, \"arguments\", protocolErrors.get())) {");
353
354         foreach my $parameter (@inArgs) {
355             my $name = $parameter->name;
356             my $type = $parameter->type;
357             my $typeString = $parameter->type;
358             $typeString =~ s/\b(\w)/\U$1/g;
359             $typeString =~ s/ //g;
360             push(@function, "        " . $typeTransform{$type}->{"variable"} . " $name = get$typeString(argumentsContainer.get(), \"$name\", protocolErrors.get());");
361         }
362         push(@function, "");
363         $indent = "    ";
364     }
365
366     my $args = join(", ", (map($_->name, @inArgs), map("&" . $_->name, @outArgs)));
367     push(@function, "$indent    if (!protocolErrors->length())");
368     push(@function, "$indent        $domainAccessor->$functionName($args);");
369     push(@function, scalar(@inArgs) ? "    }" : "");
370
371     push(@function, "    // use InspectorFrontend as a marker of WebInspector availability");
372     push(@function, "    if ((callId || protocolErrors->length()) && m_inspectorController->hasFrontend()) {");
373     push(@function, "        RefPtr<InspectorObject> responseMessage = InspectorObject::create();");
374     push(@function, "        responseMessage->setNumber(\"seq\", callId);");
375     push(@function, "        responseMessage->setBoolean(\"success\", !protocolErrors->length());");
376     push(@function, "");
377     push(@function, "        if (protocolErrors->length())");
378     push(@function, "            responseMessage->setArray(\"errors\", protocolErrors);");
379     if (scalar(@outArgs)) {
380         push(@function, "        else {");
381         push(@function, "            RefPtr<InspectorObject> responseData = InspectorObject::create();");
382         push(@function, map("            responseData->set" . $typeTransform{$_->type}->{"JSONType"} . "(\"" . $_->name . "\", " . $_->name . ");", @outArgs));
383         push(@function, "            responseMessage->setObject(\"data\", responseData);");
384         push(@function, "        }");
385     }
386     push(@function, "        m_inspectorController->inspectorClient()->sendMessageToFrontend(responseMessage->toJSONString());");
387     push(@function, "    }");
388
389
390     push(@function, "}");
391     push(@function, "");
392     push(@backendMethodsImpl, @function);
393 }
394
395 sub generateBackendReportProtocolError
396 {
397     my $reportProtocolError = << "EOF";
398
399 void ${backendClassName}::reportProtocolError(const long callId, const String& errorText) const
400 {
401     RefPtr<InspectorObject> message = InspectorObject::create();
402     message->setNumber("seq", callId);
403     message->setBoolean("success", false);
404     RefPtr<InspectorArray> errors = InspectorArray::create();
405     errors->pushString(errorText);
406     message->setArray("errors", errors);
407     m_inspectorController->inspectorClient()->sendMessageToFrontend(message->toJSONString());
408 }
409 EOF
410     return split("\n", $reportProtocolError);
411 }
412
413 sub generateArgumentGetters
414 {
415     my $type = shift;
416     my $declarations = shift;
417     my $json = $typeTransform{$type}{"JSONType"};
418     my $variable = $typeTransform{$type}{"variable"};
419     my $return  = $typeTransform{$type}{"return"} ? $typeTransform{$type}{"return"} : $typeTransform{$type}{"param"};
420
421     my $typeString = $type;
422     $typeString =~ s/\b(\w)/\U$1/g;
423     $typeString =~ s/ //g;
424
425     push(@{$declarations}, "    static $return get$typeString(InspectorObject* object, const String& name, InspectorArray* protocolErrors);");
426     my $getterBody = << "EOF";
427
428 $return InspectorBackendDispatcher::get$typeString(InspectorObject* object, const String& name, InspectorArray* protocolErrors)
429 {
430     ASSERT(object);
431     ASSERT(protocolErrors);
432
433     $variable value;
434     InspectorObject::const_iterator end = object->end();
435     InspectorObject::const_iterator valueIterator = object->find(name);
436
437     if (valueIterator == end)
438         protocolErrors->pushString(String::format("Protocol Error: Argument '\%s' with type '$json' was not found.", name.utf8().data()));
439     else {
440         if (!valueIterator->second->as$json(&value))
441             protocolErrors->pushString(String::format("Protocol Error: Argument '\%s' has wrong type. It should be '$json'.", name.utf8().data()));
442     }
443     return value;
444 }
445 EOF
446
447     return split("\n", $getterBody);
448 }
449
450 sub generateBackendDispatcher
451 {
452     my @body;
453     my @methods = map($backendMethods{$_}, keys %backendMethods);
454     my @mapEntries = map("        dispatchMap.add(${_}Cmd, &${backendClassName}::$_);", @methods);
455     my $mapEntries = join("\n", @mapEntries);
456
457     my $backendDispatcherBody = << "EOF";
458 void ${backendClassName}::dispatch(const String& message)
459 {
460     typedef void (${backendClassName}::*CallHandler)(long callId, InspectorObject* messageObject);
461     typedef HashMap<String, CallHandler> DispatchMap;
462     DEFINE_STATIC_LOCAL(DispatchMap, dispatchMap, );
463     long callId = 0;
464
465     if (dispatchMap.isEmpty()) {
466 $mapEntries
467     }
468
469     RefPtr<InspectorValue> parsedMessage = InspectorValue::parseJSON(message);
470     if (!parsedMessage) {
471         reportProtocolError(callId, "Protocol Error: Invalid message format. Message should be in JSON format.");
472         return;
473     }
474
475     RefPtr<InspectorObject> messageObject = parsedMessage->asObject();
476     if (!messageObject) {
477         reportProtocolError(callId, "Protocol Error: Invalid message format. The message should be a JSONified object.");
478         return;
479     }
480
481     RefPtr<InspectorValue> commandValue = messageObject->get("command");
482     if (!commandValue) {
483         reportProtocolError(callId, "Protocol Error: Invalid message format. 'command' property wasn't found.");
484         return;
485     }
486
487     String command;
488     if (!commandValue->asString(&command)) {
489         reportProtocolError(callId, "Protocol Error: Invalid message format. The type of 'command' property should be string.");
490         return;
491     }
492
493     RefPtr<InspectorValue> callIdValue = messageObject->get("seq");
494     if (!callIdValue) {
495         reportProtocolError(callId, "Protocol Error: Invalid message format. 'seq' property was not found in the request.");
496         return;
497     }
498
499     if (!callIdValue->asNumber(&callId)) {
500         reportProtocolError(callId, "Protocol Error: Invalid message format. The type of 'seq' property should be number.");
501         return;
502     }
503
504     HashMap<String, CallHandler>::iterator it = dispatchMap.find(command);
505     if (it == dispatchMap.end()) {
506         reportProtocolError(callId, makeString("Protocol Error: Invalid command was received. '", command, "' wasn't found."));
507         return;
508     }
509
510     ((*this).*it->second)(callId, messageObject.get());
511 }
512 EOF
513     return split("\n", $backendDispatcherBody);
514 }
515
516 sub generateBackendMessageParser
517 {
518     my $messageParserBody = << "EOF";
519 bool ${backendClassName}::getCommandName(const String& message, String* result)
520 {
521     RefPtr<InspectorValue> value = InspectorValue::parseJSON(message);
522     if (!value)
523         return false;
524
525     RefPtr<InspectorObject> object = value->asObject();
526     if (!object)
527         return false;
528
529     RefPtr<InspectorValue> commandValue = object->get("command");
530     if (!commandValue)
531         return false;
532
533     return commandValue->asString(result);
534 }
535
536 EOF
537     return split("\n", $messageParserBody);
538 }
539
540 sub generateBackendStubJS
541 {
542     my $interface = shift;
543     my @backendFunctions = grep(!$_->signature->extendedAttributes->{"notify"}, @{$interface->functions});
544     my @JSStubs;
545
546     foreach my $function (@backendFunctions) {
547         my $name = $function->signature->name;
548         my $domain = $function->signature->extendedAttributes->{"handler"};
549         my $argumentNames = join(",", map("\"" . $_->name . "\": \"" . lc($typeTransform{$_->type}->{"JSONType"}) . "\"", grep($_->direction eq "in", @{$function->parameters})));
550         push(@JSStubs, "    this._registerDelegate('{" .
551             "\"seq\": 0, " .
552             "\"domain\": \"$domain\", " .
553             "\"command\": \"$name\", " .
554             "\"arguments\": {$argumentNames}" .
555         "}');");
556     }
557
558     my $JSStubs = join("\n", @JSStubs);
559     my $inspectorBackendStubJS = << "EOF";
560 $licenseTemplate
561
562 WebInspector.InspectorBackendStub = function()
563 {
564 $JSStubs
565 }
566
567 WebInspector.InspectorBackendStub.prototype = {
568     _registerDelegate: function(commandInfo)
569     {
570         var commandObject = JSON.parse(commandInfo);
571         this[commandObject.command] = this.sendMessageToBackend.bind(this, commandInfo);
572     },
573
574     sendMessageToBackend: function()
575     {
576         var args = Array.prototype.slice.call(arguments);
577         var request = JSON.parse(args.shift());
578
579         for (var key in request.arguments) {
580             if (args.length === 0) {
581                 console.error("Protocol Error: Invalid number of arguments for 'InspectorBackend.%s' call. It should have the next arguments '%s'.", request.command, JSON.stringify(request.arguments));
582                 return;
583             }
584             var value = args.shift();
585             if (typeof value !== request.arguments[key]) {
586                 console.error("Protocol Error: Invalid type of argument '%s' for 'InspectorBackend.%s' call. It should be '%s' but it is '%s'.", key, request.command, request.arguments[key], typeof value);
587                 return;
588             }
589             request.arguments[key] = value;
590         }
591
592         if (args.length === 1) {
593             if (typeof args[0] !== "function" && typeof args[0] !== "undefined") {
594                 console.error("Protocol Error: Optional callback argument for 'InspectorBackend.%s' call should be a function but its type is '%s'.", request.command, typeof args[0]);
595                 return;
596             }
597             request.seq = WebInspector.Callback.wrap(args[0]);
598         }
599
600         var message = JSON.stringify(request);
601         InspectorFrontendHost.sendMessageToBackend(message);
602     }
603 }
604
605 InspectorBackend = new WebInspector.InspectorBackendStub();
606
607 EOF
608     return split("\n", $inspectorBackendStubJS);
609 }
610
611 sub generateHeader
612 {
613     my $className = shift;
614     my $types = shift;
615     my $constructor = shift;
616     my $constants = shift;
617     my $methods = shift;
618     my $footer = shift;
619
620     my $forwardHeaders = join("\n", sort(map("#include <" . $typeTransform{$_}->{"forwardHeader"} . ">", grep($typeTransform{$_}->{"forwardHeader"}, keys %{$types}))));
621     my $forwardDeclarations = join("\n", sort(map("class " . $typeTransform{$_}->{"forward"} . ";", grep($typeTransform{$_}->{"forward"}, keys %{$types}))));
622     my $constantDeclarations = join("\n", @{$constants});
623     my $methodsDeclarations = join("\n", keys %{$methods});
624
625     my $headerBody = << "EOF";
626 // Copyright (c) 2010 The Chromium Authors. All rights reserved.
627 // Use of this source code is governed by a BSD-style license that can be
628 // found in the LICENSE file.
629 #ifndef ${className}_h
630 #define ${className}_h
631
632 ${forwardHeaders}
633
634 namespace $namespace {
635
636 $forwardDeclarations
637
638 class $className {
639 public:
640 $constructor
641
642 $constantDeclarations
643 $methodsDeclarations
644
645 private:
646 $footer
647 };
648
649 } // namespace $namespace
650 #endif // !defined(${className}_h)
651
652 EOF
653     return $headerBody;
654 }
655
656 sub generateSource
657 {
658     my $className = shift;
659     my $types = shift;
660     my $constants = shift;
661     my $methods = shift;
662
663     my @sourceContent = split("\r", $licenseTemplate);
664     push(@sourceContent, "\n#include \"config.h\"");
665     push(@sourceContent, "#include \"$className.h\"");
666     push(@sourceContent, "#include <wtf/text/StringConcatenate.h>");
667     push(@sourceContent, "");
668     push(@sourceContent, "#if ENABLE(INSPECTOR)");
669     push(@sourceContent, "");
670
671     my %headers;
672     foreach my $type (keys %{$types}) {
673         $headers{"#include \"" . $typeTransform{$type}->{"header"} . "\""} = 1 if !$typeTransform{$type}->{"header"} eq  "";
674     }
675     push(@sourceContent, sort keys %headers);
676     push(@sourceContent, "");
677     push(@sourceContent, "namespace $namespace {");
678     push(@sourceContent, "");
679     push(@sourceContent, join("\n", @{$constants}));
680     push(@sourceContent, "");
681     push(@sourceContent, @{$methods});
682     push(@sourceContent, "");
683     push(@sourceContent, "} // namespace $namespace");
684     push(@sourceContent, "");
685     push(@sourceContent, "#endif // ENABLE(INSPECTOR)");
686     push(@sourceContent, "");
687     return @sourceContent;
688 }
689
690 sub finish
691 {
692     my $object = shift;
693
694     open(my $SOURCE, ">$outputDir/$frontendClassName.cpp") || die "Couldn't open file $outputDir/$frontendClassName.cpp";
695     print $SOURCE join("\n", generateSource($frontendClassName, \%frontendTypes, \@frontendConstantDefinitions, \@frontendMethodsImpl));
696     close($SOURCE);
697     undef($SOURCE);
698
699     open(my $HEADER, ">$outputHeadersDir/$frontendClassName.h") || die "Couldn't open file $outputHeadersDir/$frontendClassName.h";
700     print $HEADER generateHeader($frontendClassName, \%frontendTypes, $frontendConstructor, \@frontendConstantDeclarations, \%frontendMethods, $frontendFooter);
701     close($HEADER);
702     undef($HEADER);
703
704     open($SOURCE, ">$outputDir/$backendClassName.cpp") || die "Couldn't open file $outputDir/$backendClassName.cpp";
705     print $SOURCE join("\n", generateSource($backendClassName, \%backendTypes, \@backendConstantDefinitions, \@backendMethodsImpl));
706     close($SOURCE);
707     undef($SOURCE);
708
709     open($HEADER, ">$outputHeadersDir/$backendClassName.h") || die "Couldn't open file $outputHeadersDir/$backendClassName.h";
710     print $HEADER join("\n", generateHeader($backendClassName, \%backendTypes, $backendConstructor, \@backendConstantDeclarations, \%backendMethods, $backendFooter));
711     close($HEADER);
712     undef($HEADER);
713
714     open(my $JS_STUB, ">$outputDir/$backendJSStubName.js") || die "Couldn't open file $outputDir/$backendJSStubName.js";
715     print $JS_STUB join("\n", @backendStubJS);
716     close($JS_STUB);
717     undef($JS_STUB);
718 }
719
720 1;