Web Inspector: Keep Web Inspector window alive across process swaps (PSON) (Local...
[WebKit-https.git] / Source / WebKit / Scripts / webkit / messages.py
1 # Copyright (C) 2010-2018 Apple Inc. All rights reserved.
2 #
3 # Redistribution and use in source and binary forms, with or without
4 # modification, are permitted provided that the following conditions
5 # are met:
6 # 1.  Redistributions of source code must retain the above copyright
7 #     notice, this list of conditions and the following disclaimer.
8 # 2.  Redistributions in binary form must reproduce the above copyright
9 #     notice, this list of conditions and the following disclaimer in the
10 #     documentation and/or other materials provided with the distribution.
11 #
12 # THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
13 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
14 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
15 # DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
16 # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
17 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
18 # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
19 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
20 # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
21 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
22
23 import collections
24 import re
25 import sys
26
27 from webkit import parser
28
29 WANTS_CONNECTION_ATTRIBUTE = 'WantsConnection'
30 LEGACY_RECEIVER_ATTRIBUTE = 'LegacyReceiver'
31 DELAYED_ATTRIBUTE = 'Delayed'
32 ASYNC_ATTRIBUTE = 'Async'
33 LEGACY_SYNC_ATTRIBUTE = 'LegacySync'
34
35 _license_header = """/*
36  * Copyright (C) 2010-2018 Apple Inc. All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1.  Redistributions of source code must retain the above copyright
42  *     notice, this list of conditions and the following disclaimer.
43  * 2.  Redistributions in binary form must reproduce the above copyright
44  *     notice, this list of conditions and the following disclaimer in the
45  *     documentation and/or other materials provided with the distribution.
46  *
47  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
48  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
49  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
50  * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
51  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
52  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
53  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
54  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
55  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
56  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
57  */
58
59 """
60
61
62 def messages_header_filename(receiver):
63     return '%sMessages.h' % receiver.name
64
65
66 def surround_in_condition(string, condition):
67     if not condition:
68         return string
69     return '#if %s\n%s#endif\n' % (condition, string)
70
71
72 def function_parameter_type(type, kind):
73     # Don't use references for built-in types.
74     builtin_types = frozenset([
75         'bool',
76         'float',
77         'double',
78         'uint8_t',
79         'uint16_t',
80         'uint32_t',
81         'uint64_t',
82         'int8_t',
83         'int16_t',
84         'int32_t',
85         'int64_t',
86     ])
87
88     if type in builtin_types:
89         return type
90
91     if kind.startswith('enum:'):
92         return type
93
94     return 'const %s&' % type
95
96
97 def reply_parameter_type(type):
98     return '%s&' % type
99
100
101 def move_type(type):
102     return '%s&&' % type
103
104
105 def arguments_type(message):
106     return 'std::tuple<%s>' % ', '.join(function_parameter_type(parameter.type, parameter.kind) for parameter in message.parameters)
107
108
109 def reply_type(message):
110     return 'std::tuple<%s>' % (', '.join(reply_parameter_type(parameter.type) for parameter in message.reply_parameters))
111
112
113 def message_to_struct_declaration(message):
114     result = []
115     function_parameters = [(function_parameter_type(x.type, x.kind), x.name) for x in message.parameters]
116     result.append('class %s {\n' % message.name)
117     result.append('public:\n')
118     result.append('    typedef %s Arguments;\n' % arguments_type(message))
119     result.append('\n')
120     result.append('    static IPC::StringReference receiverName() { return messageReceiverName(); }\n')
121     result.append('    static IPC::StringReference name() { return IPC::StringReference("%s"); }\n' % message.name)
122     result.append('    static const bool isSync = %s;\n' % ('false', 'true')[message.reply_parameters != None and not message.has_attribute(ASYNC_ATTRIBUTE)])
123     result.append('\n')
124     if message.reply_parameters != None:
125         send_parameters = [(function_parameter_type(x.type, x.kind), x.name) for x in message.reply_parameters]
126         completion_handler_parameters = '%s' % ', '.join([' '.join(x) for x in send_parameters])
127         if message.has_attribute(ASYNC_ATTRIBUTE):
128             move_parameters = ', '.join([move_type(x.type) for x in message.reply_parameters])
129             result.append('    static void callReply(IPC::Decoder&, CompletionHandler<void(%s)>&&);\n' % move_parameters)
130             result.append('    static void cancelReply(CompletionHandler<void(%s)>&&);\n' % move_parameters)
131             result.append('    static IPC::StringReference asyncMessageReplyName() { return { "%sReply" }; }\n' % message.name)
132             result.append('    using AsyncReply')
133         elif message.has_attribute(DELAYED_ATTRIBUTE):
134             result.append('    using DelayedReply')
135         if message.has_attribute(DELAYED_ATTRIBUTE) or message.has_attribute(ASYNC_ATTRIBUTE):
136             result.append(' = CompletionHandler<void(%s)>;\n' % completion_handler_parameters)
137             result.append('    static void send(std::unique_ptr<IPC::Encoder>&&, IPC::Connection&')
138             if len(send_parameters):
139                 result.append(', %s' % completion_handler_parameters)
140             result.append(');\n')
141         result.append('    typedef %s Reply;\n' % reply_type(message))
142
143     if len(function_parameters):
144         result.append('    %s%s(%s)' % (len(function_parameters) == 1 and 'explicit ' or '', message.name, ', '.join([' '.join(x) for x in function_parameters])))
145         result.append('\n        : m_arguments(%s)\n' % ', '.join([x[1] for x in function_parameters]))
146         result.append('    {\n')
147         result.append('    }\n\n')
148     result.append('    const Arguments& arguments() const\n')
149     result.append('    {\n')
150     result.append('        return m_arguments;\n')
151     result.append('    }\n')
152     result.append('\n')
153     result.append('private:\n')
154     result.append('    Arguments m_arguments;\n')
155     result.append('};\n')
156     return surround_in_condition(''.join(result), message.condition)
157
158
159 def forward_declaration(namespace, kind_and_type):
160     kind, type = kind_and_type
161
162     qualified_name = '%s::%s' % (namespace, type)
163     if kind == 'struct':
164         return 'struct %s' % type
165     elif kind.startswith('enum:'):
166         return 'enum class %s : %s' % (type, kind[5:])
167     else:
168         return 'class %s' % type
169
170
171 def forward_declarations_for_namespace(namespace, kind_and_types):
172     result = []
173     result.append('namespace %s {\n' % namespace)
174     result += ['%s;\n' % forward_declaration(namespace, x) for x in kind_and_types]
175     result.append('}\n')
176     return ''.join(result)
177
178
179 def forward_declarations_and_headers(receiver):
180     types_by_namespace = collections.defaultdict(set)
181
182     headers = set([
183         '"ArgumentCoders.h"',
184         '<wtf/Forward.h>',
185     ])
186
187     non_template_wtf_types = frozenset([
188         'MachSendRight',
189         'String',
190     ])
191
192     for message in receiver.messages:
193         if message.reply_parameters != None and message.has_attribute(DELAYED_ATTRIBUTE):
194             headers.add('<wtf/ThreadSafeRefCounted.h>')
195             types_by_namespace['IPC'].update([('class', 'Connection')])
196
197     no_forward_declaration_types = frozenset([
198         'MachSendRight',
199         'String',
200         'WebCore::DocumentIdentifier',
201         'WebCore::FetchIdentifier',
202         'WebCore::ServiceWorkerIdentifier',
203         'WebCore::ServiceWorkerJobIdentifier',
204         'WebCore::ServiceWorkerOrClientData',
205         'WebCore::ServiceWorkerOrClientIdentifier',
206         'WebCore::ServiceWorkerRegistrationIdentifier',
207         'WebCore::SWServerConnectionIdentifier',
208         'WebKit::ActivityStateChangeID',
209         'WebKit::UserContentControllerIdentifier',
210     ])
211
212     for parameter in receiver.iterparameters():
213         kind = parameter.kind
214         type = parameter.type
215
216         if type.find('<') != -1 or type in no_forward_declaration_types:
217             # Don't forward declare class templates.
218             headers.update(headers_for_type(type))
219             continue
220
221         split = type.split('::')
222
223         # Handle WTF types even if the WTF:: prefix is not given
224         if split[0] in non_template_wtf_types:
225             split.insert(0, 'WTF')
226
227         if len(split) == 2:
228             namespace = split[0]
229             inner_type = split[1]
230             types_by_namespace[namespace].add((kind, inner_type))
231         elif len(split) > 2:
232             # We probably have a nested struct, which means we can't forward declare it.
233             # Include its header instead.
234             headers.update(headers_for_type(type))
235
236     forward_declarations = '\n'.join([forward_declarations_for_namespace(namespace, types) for (namespace, types) in sorted(types_by_namespace.items())])
237     headers = ['#include %s\n' % header for header in sorted(headers)]
238
239     return (forward_declarations, headers)
240
241
242 def generate_messages_header(file):
243     receiver = parser.parse(file)
244
245     result = []
246
247     result.append(_license_header)
248
249     result.append('#pragma once\n')
250     result.append('\n')
251
252     if receiver.condition:
253         result.append('#if %s\n\n' % receiver.condition)
254
255     forward_declarations, headers = forward_declarations_and_headers(receiver)
256
257     result += headers
258     result.append('\n')
259
260     result.append(forward_declarations)
261     result.append('\n')
262
263     result.append('namespace Messages {\nnamespace %s {\n' % receiver.name)
264     result.append('\n')
265     result.append('static inline IPC::StringReference messageReceiverName()\n')
266     result.append('{\n')
267     result.append('    return IPC::StringReference("%s");\n' % receiver.name)
268     result.append('}\n')
269     result.append('\n')
270     result.append('\n'.join([message_to_struct_declaration(x) for x in receiver.messages]))
271     result.append('\n')
272     result.append('} // namespace %s\n} // namespace Messages\n' % receiver.name)
273
274     if receiver.condition:
275         result.append('\n#endif // %s\n' % receiver.condition)
276
277     return ''.join(result)
278
279
280 def handler_function(receiver, message):
281     if message.name.find('URL') == 0:
282         return '%s::%s' % (receiver.name, 'url' + message.name[3:])
283     return '%s::%s' % (receiver.name, message.name[0].lower() + message.name[1:])
284
285
286 def async_message_statement(receiver, message):
287     dispatch_function_args = ['decoder', 'this', '&%s' % handler_function(receiver, message)]
288
289     dispatch_function = 'handleMessage'
290     if message.has_attribute(ASYNC_ATTRIBUTE):
291         dispatch_function += 'Async'
292         dispatch_function_args.insert(0, 'connection')
293
294     if message.has_attribute(WANTS_CONNECTION_ATTRIBUTE):
295         dispatch_function_args.insert(0, 'connection')
296
297     result = []
298     result.append('    if (decoder.messageName() == Messages::%s::%s::name()) {\n' % (receiver.name, message.name))
299     result.append('        IPC::%s<Messages::%s::%s>(%s);\n' % (dispatch_function, receiver.name, message.name, ', '.join(dispatch_function_args)))
300     result.append('        return;\n')
301     result.append('    }\n')
302     return surround_in_condition(''.join(result), message.condition)
303
304
305 def sync_message_statement(receiver, message):
306     dispatch_function = 'handleMessage'
307     if message.has_attribute(DELAYED_ATTRIBUTE):
308         dispatch_function += 'Delayed'
309     if message.has_attribute(ASYNC_ATTRIBUTE):
310         dispatch_function += 'Async'
311     if message.has_attribute(LEGACY_SYNC_ATTRIBUTE):
312         dispatch_function += 'LegacySync'
313
314     wants_connection = message.has_attribute(DELAYED_ATTRIBUTE) or message.has_attribute(WANTS_CONNECTION_ATTRIBUTE)
315
316     result = []
317     result.append('    if (decoder.messageName() == Messages::%s::%s::name()) {\n' % (receiver.name, message.name))
318     result.append('        IPC::%s<Messages::%s::%s>(%sdecoder, %sreplyEncoder, this, &%s);\n' % (dispatch_function, receiver.name, message.name, 'connection, ' if wants_connection else '', '' if message.has_attribute(DELAYED_ATTRIBUTE) or message.has_attribute(ASYNC_ATTRIBUTE) else '*', handler_function(receiver, message)))
319     result.append('        return;\n')
320     result.append('    }\n')
321     return surround_in_condition(''.join(result), message.condition)
322
323
324 def class_template_headers(template_string):
325     template_string = template_string.strip()
326
327     class_template_types = {
328         'WebCore::RectEdges': {'headers': ['<WebCore/RectEdges.h>'], 'argument_coder_headers': ['"ArgumentCoders.h"']},
329         'HashMap': {'headers': ['<wtf/HashMap.h>'], 'argument_coder_headers': ['"ArgumentCoders.h"']},
330         'HashSet': {'headers': ['<wtf/HashSet.h>'], 'argument_coder_headers': ['"ArgumentCoders.h"']},
331         'std::optional': {'headers': ['<wtf/Optional.h>'], 'argument_coder_headers': ['"ArgumentCoders.h"']},
332         'OptionSet': {'headers': ['<wtf/OptionSet.h>'], 'argument_coder_headers': ['"ArgumentCoders.h"']},
333         'Vector': {'headers': ['<wtf/Vector.h>'], 'argument_coder_headers': ['"ArgumentCoders.h"']},
334         'std::pair': {'headers': ['<utility>'], 'argument_coder_headers': ['"ArgumentCoders.h"']},
335     }
336
337     match = re.match('(?P<template_name>.+?)<(?P<parameter_string>.+)>', template_string)
338     if not match:
339         return {'header_infos': [], 'types': [template_string]}
340
341     template_name = match.groupdict()['template_name']
342     if template_name not in class_template_types:
343         sys.stderr.write("Error: no class template type is defined for '%s'\n" % (template_string))
344         sys.exit(1)
345
346     header_infos = [class_template_types[template_name]]
347     types = []
348
349     for parameter in parser.split_parameters_string(match.groupdict()['parameter_string']):
350         parameter_header_infos_and_types = class_template_headers(parameter)
351
352         header_infos += parameter_header_infos_and_types['header_infos']
353         types += parameter_header_infos_and_types['types']
354
355     return {'header_infos': header_infos, 'types': types}
356
357
358 def argument_coder_headers_for_type(type):
359     header_infos_and_types = class_template_headers(type)
360
361     special_cases = {
362         'String': '"ArgumentCoders.h"',
363         'WebKit::ScriptMessageHandlerHandle': '"WebScriptMessageHandler.h"',
364     }
365
366     headers = []
367     for header_info in header_infos_and_types['header_infos']:
368         headers += header_info['argument_coder_headers']
369
370     for type in header_infos_and_types['types']:
371         if type in special_cases:
372             headers.append(special_cases[type])
373             continue
374
375         split = type.split('::')
376         if len(split) < 2:
377             continue
378         if split[0] == 'WebCore':
379             headers.append('"WebCoreArgumentCoders.h"')
380
381     return headers
382
383
384 def headers_for_type(type):
385     header_infos_and_types = class_template_headers(type)
386
387     special_cases = {
388         'IPC::SharedBufferDataReference': ['"SharedBufferDataReference.h"', '"DataReference.h"'],
389         'MachSendRight': ['<wtf/MachSendRight.h>'],
390         'JSC::MessageLevel': ['<JavaScriptCore/ConsoleTypes.h>'],
391         'JSC::MessageSource': ['<JavaScriptCore/ConsoleTypes.h>'],
392         'Inspector::InspectorTargetType': ['<JavaScriptCore/InspectorTarget.h>'],
393         'Inspector::FrontendChannel::ConnectionType': ['<JavaScriptCore/InspectorFrontendChannel.h>'],
394         'MonotonicTime': ['<wtf/MonotonicTime.h>'],
395         'Seconds': ['<wtf/Seconds.h>'],
396         'WallTime': ['<wtf/WallTime.h>'],
397         'String': ['<wtf/text/WTFString.h>'],
398         'PAL::SessionID': ['<pal/SessionID.h>'],
399         'WebCore::AutoplayEventFlags': ['<WebCore/AutoplayEvent.h>'],
400         'WebCore::ExceptionDetails': ['<WebCore/JSDOMExceptionHandling.h>'],
401         'WebCore::FileChooserSettings': ['<WebCore/FileChooser.h>'],
402         'WebCore::ShareDataWithParsedURL': ['<WebCore/ShareData.h>'],
403         'WebCore::FontChanges': ['<WebCore/FontAttributeChanges.h>'],
404         'WebCore::FrameLoadType': ['<WebCore/FrameLoaderTypes.h>'],
405         'WebCore::GrammarDetail': ['<WebCore/TextCheckerClient.h>'],
406         'WebCore::HasInsecureContent': ['<WebCore/FrameLoaderTypes.h>'],
407         'WebCore::Highlight': ['<WebCore/InspectorOverlay.h>'],
408         'WebCore::IncludeSecureCookies': ['<WebCore/CookiesStrategy.h>'],
409         'WebCore::KeyframeValueList': ['<WebCore/GraphicsLayer.h>'],
410         'WebCore::KeypressCommand': ['<WebCore/KeyboardEvent.h>'],
411         'WebCore::LockBackForwardList': ['<WebCore/FrameLoaderTypes.h>'],
412         'WebCore::NetworkTransactionInformation': ['<WebCore/NetworkLoadInformation.h>'],
413         'WebCore::PasteboardCustomData': ['<WebCore/Pasteboard.h>'],
414         'WebCore::PasteboardImage': ['<WebCore/Pasteboard.h>'],
415         'WebCore::PasteboardURL': ['<WebCore/Pasteboard.h>'],
416         'WebCore::PasteboardWebContent': ['<WebCore/Pasteboard.h>'],
417         'WebCore::PaymentAuthorizationResult': ['<WebCore/ApplePaySessionPaymentRequest.h>'],
418         'WebCore::PaymentMethodUpdate': ['<WebCore/ApplePaySessionPaymentRequest.h>'],
419         'WebCore::PluginInfo': ['<WebCore/PluginData.h>'],
420         'WebCore::PolicyAction': ['<WebCore/FrameLoaderTypes.h>'],
421         'WebCore::RecentSearch': ['<WebCore/SearchPopupMenu.h>'],
422         'WebCore::RouteSharingPolicy': ['<WebCore/AudioSession.h>'],
423         'WebCore::SWServerConnectionIdentifier': ['<WebCore/ServiceWorkerTypes.h>'],
424         'WebCore::ServiceWorkerJobIdentifier': ['<WebCore/ServiceWorkerTypes.h>'],
425         'WebCore::ServiceWorkerOrClientData': ['<WebCore/ServiceWorkerTypes.h>', '<WebCore/ServiceWorkerClientData.h>', '<WebCore/ServiceWorkerData.h>'],
426         'WebCore::ServiceWorkerOrClientIdentifier': ['<WebCore/ServiceWorkerTypes.h>', '<WebCore/ServiceWorkerClientIdentifier.h>'],
427         'WebCore::ServiceWorkerRegistrationIdentifier': ['<WebCore/ServiceWorkerTypes.h>'],
428         'WebCore::ServiceWorkerRegistrationState': ['<WebCore/ServiceWorkerTypes.h>'],
429         'WebCore::ServiceWorkerState': ['<WebCore/ServiceWorkerTypes.h>'],
430         'WebCore::ShippingContactUpdate': ['<WebCore/ApplePaySessionPaymentRequest.h>'],
431         'WebCore::ShippingMethodUpdate': ['<WebCore/ApplePaySessionPaymentRequest.h>'],
432         'WebCore::ShouldNotifyWhenResolved': ['<WebCore/ServiceWorkerTypes.h>'],
433         'WebCore::ShouldSample': ['<WebCore/DiagnosticLoggingClient.h>'],
434         'WebCore::SupportedPluginIdentifier': ['<WebCore/PluginData.h>'],
435         'WebCore::TextCheckingRequestData': ['<WebCore/TextChecking.h>'],
436         'WebCore::TextCheckingResult': ['<WebCore/TextCheckerClient.h>'],
437         'WebCore::TextCheckingType': ['<WebCore/TextChecking.h>'],
438         'WebCore::TextIndicatorData': ['<WebCore/TextIndicator.h>'],
439         'WebCore::ViewportAttributes': ['<WebCore/ViewportArguments.h>'],
440         'WebCore::SelectionRect': ['"EditorState.h"'],
441         'WebKit::ActivityStateChangeID': ['"DrawingAreaInfo.h"'],
442         'WebKit::BackForwardListItemState': ['"SessionState.h"'],
443         'WebKit::DeviceAccessState': ['"UserMediaPermissionRequestManager.h"'],
444         'WebKit::LayerHostingMode': ['"LayerTreeContext.h"'],
445         'WebKit::PageState': ['"SessionState.h"'],
446         'WebKit::WebGestureEvent': ['"WebEvent.h"'],
447         'WebKit::WebKeyboardEvent': ['"WebEvent.h"'],
448         'WebKit::WebMouseEvent': ['"WebEvent.h"'],
449         'WebKit::WebTouchEvent': ['"WebEvent.h"'],
450         'WebKit::WebWheelEvent': ['"WebEvent.h"'],
451         'struct WebKit::WebUserScriptData': ['"WebUserContentControllerDataTypes.h"'],
452         'struct WebKit::WebUserStyleSheetData': ['"WebUserContentControllerDataTypes.h"'],
453         'struct WebKit::WebScriptMessageHandlerData': ['"WebUserContentControllerDataTypes.h"'],
454     }
455
456     headers = []
457     for header_info in header_infos_and_types['header_infos']:
458         headers += header_info['headers']
459
460     for type in header_infos_and_types['types']:
461         if type in special_cases:
462             headers += special_cases[type]
463             continue
464
465         # We assume that we must include a header for a type iff it has a scope
466         # resolution operator (::).
467         split = type.split('::')
468         if len(split) < 2:
469             continue
470
471         if split[0] == 'WebKit' or split[0] == 'IPC':
472             headers.append('"%s.h"' % split[1])
473         else:
474             headers.append('<%s/%s.h>' % tuple(split[0:2]))
475
476     return headers
477
478
479 def generate_message_handler(file):
480     receiver = parser.parse(file)
481     header_conditions = {
482         '"%s"' % messages_header_filename(receiver): [None],
483         '"HandleMessage.h"': [None],
484         '"Decoder.h"': [None],
485     }
486
487     type_conditions = {}
488     for parameter in receiver.iterparameters():
489         if not parameter.type in type_conditions:
490             type_conditions[parameter.type] = []
491
492         if not parameter.condition in type_conditions[parameter.type]:
493             type_conditions[parameter.type].append(parameter.condition)
494
495     for parameter in receiver.iterparameters():
496         type = parameter.type
497         conditions = type_conditions[type]
498
499         argument_encoder_headers = argument_coder_headers_for_type(type)
500         if argument_encoder_headers:
501             for header in argument_encoder_headers:
502                 if header not in header_conditions:
503                     header_conditions[header] = []
504                 header_conditions[header].extend(conditions)
505
506         type_headers = headers_for_type(type)
507         for header in type_headers:
508             if header not in header_conditions:
509                 header_conditions[header] = []
510             header_conditions[header].extend(conditions)
511
512     for message in receiver.messages:
513         if message.reply_parameters is not None:
514             for reply_parameter in message.reply_parameters:
515                 type = reply_parameter.type
516                 argument_encoder_headers = argument_coder_headers_for_type(type)
517                 if argument_encoder_headers:
518                     for header in argument_encoder_headers:
519                         if header not in header_conditions:
520                             header_conditions[header] = []
521                         header_conditions[header].append(message.condition)
522
523                 type_headers = headers_for_type(type)
524                 for header in type_headers:
525                     if header not in header_conditions:
526                         header_conditions[header] = []
527                     header_conditions[header].append(message.condition)
528
529     result = []
530
531     result.append(_license_header)
532     result.append('#include "config.h"\n')
533     result.append('\n')
534
535     if receiver.condition:
536         result.append('#if %s\n\n' % receiver.condition)
537
538     result.append('#include "%s.h"\n\n' % receiver.name)
539     for header in sorted(header_conditions):
540         if header_conditions[header] and not None in header_conditions[header]:
541             result.append('#if %s\n' % ' || '.join(set(header_conditions[header])))
542             result += ['#include %s\n' % header]
543             result.append('#endif\n')
544         else:
545             result += ['#include %s\n' % header]
546     result.append('\n')
547
548     delayed_or_async_messages = []
549     for message in receiver.messages:
550         if message.reply_parameters != None and (message.has_attribute(DELAYED_ATTRIBUTE) or message.has_attribute(ASYNC_ATTRIBUTE)):
551             delayed_or_async_messages.append(message)
552
553     if delayed_or_async_messages:
554         result.append('namespace Messages {\n\nnamespace %s {\n\n' % receiver.name)
555
556         for message in delayed_or_async_messages:
557             send_parameters = [(function_parameter_type(x.type, x.kind), x.name) for x in message.reply_parameters]
558
559             if message.condition:
560                 result.append('#if %s\n\n' % message.condition)
561
562             if message.has_attribute(ASYNC_ATTRIBUTE):
563                 move_parameters = message.name, ', '.join([move_type(x.type) for x in message.reply_parameters])
564                 result.append('void %s::callReply(IPC::Decoder& decoder, CompletionHandler<void(%s)>&& completionHandler)\n{\n' % move_parameters)
565                 for x in message.reply_parameters:
566                     result.append('    std::optional<%s> %s;\n' % (x.type, x.name))
567                     result.append('    decoder >> %s;\n' % x.name)
568                     result.append('    if (!%s) {\n        ASSERT_NOT_REACHED();\n        return;\n    }\n' % x.name)
569                 result.append('    completionHandler(WTFMove(*%s));\n}\n\n' % (', *'.join(x.name for x in message.reply_parameters)))
570                 result.append('void %s::cancelReply(CompletionHandler<void(%s)>&& completionHandler)\n{\n    completionHandler(' % move_parameters)
571                 result.append(', '.join(['{ }' for x in message.reply_parameters]))
572                 result.append(');\n}\n\n')
573
574             result.append('void %s::send(std::unique_ptr<IPC::Encoder>&& encoder, IPC::Connection& connection' % (message.name))
575             if len(send_parameters):
576                 result.append(', %s' % ', '.join([' '.join(x) for x in send_parameters]))
577             result.append(')\n{\n')
578             result += ['    *encoder << %s;\n' % x.name for x in message.reply_parameters]
579             result.append('    connection.sendSyncReply(WTFMove(encoder));\n')
580             result.append('}\n')
581             result.append('\n')
582
583             if message.condition:
584                 result.append('#endif\n\n')
585
586         result.append('} // namespace %s\n\n} // namespace Messages\n\n' % receiver.name)
587
588     result.append('namespace WebKit {\n\n')
589
590     async_messages = []
591     sync_messages = []
592     for message in receiver.messages:
593         if message.reply_parameters is not None and not message.has_attribute(ASYNC_ATTRIBUTE):
594             sync_messages.append(message)
595         else:
596             async_messages.append(message)
597
598     if async_messages:
599         result.append('void %s::didReceive%sMessage(IPC::Connection& connection, IPC::Decoder& decoder)\n' % (receiver.name, receiver.name if receiver.has_attribute(LEGACY_RECEIVER_ATTRIBUTE) else ''))
600         result.append('{\n')
601         result += [async_message_statement(receiver, message) for message in async_messages]
602         if (receiver.superclass):
603             result.append('    %s::didReceiveMessage(connection, decoder);\n' % (receiver.superclass))
604         else:
605             result.append('    UNUSED_PARAM(connection);\n')
606             result.append('    UNUSED_PARAM(decoder);\n')
607             result.append('    ASSERT_NOT_REACHED();\n')
608         result.append('}\n')
609
610     if sync_messages:
611         result.append('\n')
612         result.append('void %s::didReceiveSync%sMessage(IPC::Connection& connection, IPC::Decoder& decoder, std::unique_ptr<IPC::Encoder>& replyEncoder)\n' % (receiver.name, receiver.name if receiver.has_attribute(LEGACY_RECEIVER_ATTRIBUTE) else ''))
613         result.append('{\n')
614         result += [sync_message_statement(receiver, message) for message in sync_messages]
615         result.append('    UNUSED_PARAM(connection);\n')
616         result.append('    UNUSED_PARAM(decoder);\n')
617         result.append('    UNUSED_PARAM(replyEncoder);\n')
618         result.append('    ASSERT_NOT_REACHED();\n')
619         result.append('}\n')
620
621     result.append('\n} // namespace WebKit\n\n')
622
623     if receiver.condition:
624         result.append('\n#endif // %s\n' % receiver.condition)
625
626     return ''.join(result)