• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4# Copyright (c) 2024 Huawei Device Co., Ltd.
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17from __future__ import absolute_import
18import system_util
19from io import BytesIO
20import os
21import re
22import shutil
23import string
24import sys
25import textwrap
26import time
27
28# pylint:disable=dangerous-default-value
29# pylint:disable=huawei-redefined-outer-name
30
31def notify(msg):
32  """ Display a message. """
33  sys.stdout.write('  NOTE: ' + msg + '\n')
34
35
36def wrap_text(text, indent='', maxchars=120):
37  """ Wrap the text to the specified number of characters. If
38    necessary a line will be broken and wrapped after a word.
39    """
40  result = ''
41  lines = textwrap.wrap(text, maxchars - len(indent))
42  for line in lines:
43    result += indent + line + '\n'
44  return result
45
46
47def is_base_class(clsname):
48  """ Returns true if |clsname| is a known base (root) class in the object
49        hierarchy.
50    """
51  return clsname == 'ArkWebBaseRefCounted' or clsname == 'ArkWebBaseScoped'
52
53
54def get_capi_file_name(cppname):
55  """ Convert a C++ header file name to a C API header file name. """
56  return cppname[:-2] + '_capi.h'
57
58
59def get_capi_name(cppname, isclassname, prefix=None):
60  """ Convert a C++ CamelCaps name to a C API underscore name. """
61  result = ''
62  lastchr = ''
63  for chr in cppname:
64    # add an underscore if the current character is an upper case letter
65    # and the last character was a lower case letter
66    if len(result) > 0 and not chr.isdigit() \
67        and chr.upper() == chr \
68        and not lastchr.upper() == lastchr:
69      result += '_'
70    result += chr.lower()
71    lastchr = chr
72
73  if isclassname:
74    result += '_t'
75
76  if not prefix is None:
77    if prefix[0:3] == 'cef':
78      # if the prefix name is duplicated in the function name
79      # remove that portion of the function name
80      subprefix = prefix[3:]
81      pos = result.find(subprefix)
82      if pos >= 0:
83        result = result[0:pos] + result[pos + len(subprefix):]
84    result = prefix + '_' + result
85
86  return result
87
88
89def get_wrapper_type_enum(cppname):
90  """ Returns the wrapper type enumeration value for the specified C++ class
91        name. """
92  return get_capi_name(cppname, False).upper()
93
94
95def get_prev_line(body, pos):
96  """ Retrieve the start and end positions and value for the line immediately
97    before the line containing the specified position.
98    """
99  end = body.rfind('\n', 0, pos)
100  start = body.rfind('\n', 0, end) + 1
101  line = body[start:end]
102  return {'start': start, 'end': end, 'line': line}
103
104
105def get_comment(body, name):
106  """ Retrieve the comment for a class or function. """
107  result = []
108
109  pos = body.find(name)
110  in_block_comment = False
111  while pos > 0:
112    data = get_prev_line(body, pos)
113    line = data['line'].strip()
114    pos = data['start']
115    if len(line) == 0:
116      break
117    # single line /*--cef()--*/
118    elif line[0:2] == '/*' and line[-2:] == '*/':
119      continue
120    # start of multi line /*--cef()--*/
121    elif in_block_comment and line[0:2] == '/*':
122      in_block_comment = False
123      continue
124    # end of multi line /*--cef()--*/
125    elif not in_block_comment and line[-2:] == '*/':
126      in_block_comment = True
127      continue
128    elif in_block_comment:
129      continue
130    elif line[0:3] == '///':
131      # keep the comment line including any leading spaces
132      result.append(line[3:])
133    else:
134      break
135
136  result.reverse()
137  return result
138
139
140def validate_comment(file, name, comment):
141  """ Validate the comment array returned by get_comment(). """
142
143def format_translation_changes(old, new):
144  """ Return a comment stating what is different between the old and new
145    function prototype parts.
146    """
147  changed = False
148  result = ''
149
150  # normalize C API attributes
151  oldargs = [x.replace('struct _', '') for x in old['args']]
152  oldretval = old['retval'].replace('struct _', '')
153  newargs = [x.replace('struct _', '') for x in new['args']]
154  newretval = new['retval'].replace('struct _', '')
155
156  # check if the prototype has changed
157  oldset = set(oldargs)
158  newset = set(newargs)
159  if len(oldset.symmetric_difference(newset)) > 0:
160    changed = True
161    result += '\n  // WARNING - CHANGED ATTRIBUTES'
162
163    # in the implementation set only
164    oldonly = oldset.difference(newset)
165    for arg in oldonly:
166      result += '\n  //   REMOVED: ' + arg
167
168    # in the current set only
169    newonly = newset.difference(oldset)
170    for arg in newonly:
171      result += '\n  //   ADDED:   ' + arg
172
173  # check if the return value has changed
174  if oldretval != newretval:
175    changed = True
176    result += '\n  // WARNING - CHANGED RETURN VALUE'+ \
177              '\n  //   WAS: '+old['retval']+ \
178              '\n  //   NOW: '+new['retval']
179
180  if changed:
181    result += '\n  #pragma message("Warning: " __FILE__ ": '+new['name']+ \
182              ' prototype has changed")\n'
183
184  return result
185
186
187def format_translation_includes(header, dir_name, body):
188  """ Return the necessary list of includes based on the contents of the
189    body.
190    """
191  result = ''
192
193  # <algorithm> required for VS2013.
194  if body.find('std::min') > 0 or body.find('std::max') > 0:
195    result += '#include <algorithm>\n'
196
197  if body.find('cef_api_hash(') > 0:
198    result += '#include "include/cef_api_hash.h"\n'
199
200  if body.find('template_util::has_valid_size(') > 0:
201    result += '#include "libcef_dll/template_util.h"\n'
202
203  # identify what CppToC classes are being used
204  p = re.compile('([A-Za-z0-9_]{1,})CppToC')
205  list = sorted(set(p.findall(body)))
206  for item in list:
207    directory = ''
208    if not is_base_class(item):
209      cls = header.get_class(item)
210      dir = cls.get_file_directory()
211      if not dir is None:
212        directory = dir + '/'
213    result += '#include "'+dir_name+'/cpptoc/'+directory+ \
214              get_capi_name(item, False)+'_cpptoc.h"\n'
215
216  # identify what CToCpp classes are being used
217  p = re.compile('([A-Za-z0-9_]{1,})CToCpp')
218  list = sorted(set(p.findall(body)))
219  for item in list:
220    directory = ''
221    if not is_base_class(item):
222      cls = header.get_class(item)
223      dir = cls.get_file_directory()
224      if not dir is None:
225        directory = dir + '/'
226    result += '#include "'+dir_name+'/ctocpp/'+directory+ \
227              get_capi_name(item, False)+'_ctocpp.h"\n'
228
229  if body.find('shutdown_checker') > 0:
230    result += '#include "libcef_dll/shutdown_checker.h"\n'
231
232  if body.find('transfer_') > 0:
233    result += '#include "libcef_dll/transfer_util.h"\n'
234
235  return result
236
237
238def str_to_dict(str):
239  """ Convert a string to a dictionary. If the same key has multiple values
240        the values will be stored in a list. """
241  dict = {}
242  parts = str.split(',')
243  for part in parts:
244    part = part.strip()
245    if len(part) == 0:
246      continue
247    sparts = part.split('=')
248    if len(sparts) > 2:
249      raise Exception('Invalid dictionary pair format: ' + part)
250    name = sparts[0].strip()
251    if len(sparts) == 2:
252      val = sparts[1].strip()
253    else:
254      val = True
255    if name in dict:
256      # a value with this name already exists
257      curval = dict[name]
258      if not isinstance(curval, list):
259        # convert the string value to a list
260        dict[name] = [curval]
261      dict[name].append(val)
262    else:
263      dict[name] = val
264  return dict
265
266
267def dict_to_str(dict):
268  """ Convert a dictionary to a string. """
269  str = []
270  for name in dict.keys():
271    if not isinstance(dict[name], list):
272      if dict[name] is True:
273        # currently a bool value
274        str.append(name)
275      else:
276        # currently a string value
277        str.append(name + '=' + dict[name])
278    else:
279      # currently a list value
280      for val in dict[name]:
281        str.append(name + '=' + val)
282  return ','.join(str)
283
284
285# regex for matching comment-formatted attributes
286_cre_attrib = '/\*--ark web\(([A-Za-z0-9_ ,=:\n]{0,})\)--\*/'
287# regex for matching class and function names
288_cre_cfname = '([A-Za-z0-9_]{1,})'
289# regex for matching class and function names including path separators
290_cre_cfnameorpath = '([A-Za-z0-9_\/]{2,})'
291# regex for matching typedef value and name combination
292_cre_typedef = '([A-Za-z0-9_<>:,\*\&\s]{1,})'
293# regex for matching function return value and name combination
294_cre_func = '([A-Za-z][A-Za-z0-9_<>:,\*\&\s]{1,})'
295# regex for matching virtual function modifiers + arbitrary whitespace
296_cre_vfmod = '([\sA-Za-z0-9_]{0,})'
297# regex for matching arbitrary whitespace
298_cre_space = '[\s]{1,}'
299# regex for matching optional virtual keyword
300_cre_virtual = '(?:[\s]{1,}virtual){0,1}'
301
302# Simple translation types. Format is:
303#   'cpp_type' : ['capi_type', 'capi_default_value']
304_simpletypes = {
305    'void': ['void', ''],
306    'void*': ['void*', 'NULL'],
307    'char*': ['char*', 'NULL'],
308    'int': ['int', '0'],
309    'OnVsyncCallback': ['OnVsyncCallback', 'NULL'],
310    'ArkWebRunInitedCallback*': ['ArkWebRunInitedCallback*', 'NULL'],
311    'ArkAudioAdapterDeviceDesc': ['ArkAudioAdapterDeviceDesc', '{0}'],
312    'ArkAudioAdapterDeviceDescVector': ['ArkAudioAdapterDeviceDescVector', '{0}'],
313    'ArkAudioAdapterInterrupt': ['ArkAudioAdapterInterrupt', '{0}'],
314    'ArkAudioAdapterRendererOptions': ['ArkAudioAdapterRendererOptions', '{0}'],
315    'WebRunInitedCallback*': ['WebRunInitedCallback*', 'NULL'],
316    'ArkWriteResultCallback': ['ArkWriteResultCallback', 'NULL'],
317    'ArkPasteCustomData': ['ArkPasteCustomData', '{0}'],
318    'ArkClipBoardImageData': ['ArkClipBoardImageData', '{0}'],
319    'ArkPasteRecordVector': ['ArkPasteRecordVector', '{0}'],
320    'ArkAudioDeviceDescAdapterVector': ['ArkAudioDeviceDescAdapterVector', '{0}'],
321    'ArkPrintAttributesAdapter': ['ArkPrintAttributesAdapter', '{0}'],
322    'ArkTimeZoneEventCallback': ['ArkTimeZoneEventCallback', 'NULL'],
323    'ArkIConsumerSurfaceAdapter*': ['ArkIConsumerSurfaceAdapter*', 'NULL'],
324    'ArkOhosAdapterHelper*': ['ark_ohos_adapter_helper_t*', 'NULL'],
325    'ArkOhosAdapterHelper': ['ark_ohos_adapter_helper_t', 'ArkOhosAdapterHelper()'],
326    'ArkDatashareAdapter*': ['ark_datashare_adapter_t*', 'NULL'],
327    'ArkFormatAdapterVector': ['ArkFormatAdapterVector', '{0}'],
328    'ArkFrameRateSettingAdapterVector': [
329        'ArkFrameRateSettingAdapterVector', 'ark_frame_rate_setting_adapter_vector_default'
330    ],
331    'ArkVideoDeviceDescriptorAdapterVector': ['ArkVideoDeviceDescriptorAdapterVector', '{0}'],
332    'uint8_t': ['uint8_t', '0'],
333    'uint8_t*': ['uint8_t*', 'NULL'],
334    'time_t': ['time_t', '0'],
335    'pid_t': ['pid_t', '0'],
336    'int16_t': ['int16_t', '0'],
337    'uint16_t': ['uint16_t', '0'],
338    'int32_t': ['int32_t', '0'],
339    'uint32_t': ['uint32_t', '0'],
340    'uint32_t*': ['uint32_t*', 'NULL'],
341    'int64_t': ['int64_t', '0'],
342    'uint64_t': ['uint64_t', '0'],
343    'uint64_t*': ['uint64_t*', 'NULL'],
344    'double_t': ['double_t', '0'],
345    'double': ['double', '0'],
346    'float': ['float', '0'],
347    'long': ['long', '0'],
348    'unsigned int':['unsigned int', '0'],
349    'unsigned long': ['unsigned long', '0'],
350    'long long': ['long long', '0'],
351    'size_t': ['size_t', '0'],
352    'bool': ['bool', 'false'],
353    'char': ['char', '0'],
354    'Type':['Type', 'NONE'],
355    'unsigned char':['unsigned char', '0'],
356    'ArkWebDateTime':['ArkWebDateTime', 'ark_web_date_time_default'],
357    'AccessMode':['AccessMode', 'NEVER_ALLOW'],
358    'TextDirection':['TextDirection', 'SP_UNKNOWN'],
359    'CacheModeFlag':['CacheModeFlag', 'USE_NO_CACHE'],
360    'ImageColorType':['ImageColorType', 'COLOR_TYPE_UNKNOWN'],
361    'ImageAlphaType':['ImageAlphaType', 'ALPHA_TYPE_UNKNOWN'],
362    'TouchHandleType':['TouchHandleType', 'INVALID_HANDLE'],
363    'FileSelectorMode':['FileSelectorMode', 'FILE_OPEN_MODE'],
364    'ContextMenuMediaType':['ContextMenuMediaType', 'CM_MT_NONE'],
365    'NWebResponseDataType':['NWebResponseDataType', 'NWEB_STRING_TYPE'],
366    'ContextMenuSourceType':['ContextMenuSourceType', 'CM_ST_NONE'],
367    'SelectPopupMenuItemType':['SelectPopupMenuItemType', 'SP_OPTION'],
368    'ContextMenuInputFieldType':['ContextMenuInputFieldType', 'CM_IT_NONE'],
369    'MenuEventFlags':['MenuEventFlags', 'EF_NONE'],
370    'NWebConsoleLogLevel':['NWebConsoleLogLevel', 'ERROR'],
371    'ArkWebCursorInfo':['ArkWebCursorInfo', 'ark_web_cursor_info_default'],
372    'AccessibilityIdGenerateFunc':['AccessibilityIdGenerateFunc', 'NULL'],
373    'NativeArkWebOnValidCallback':['NativeArkWebOnValidCallback', 'NULL'],
374    'NativeArkWebOnDestroyCallback':['NativeArkWebOnDestroyCallback', 'NULL'],
375    'NativeArkWebOnJavaScriptProxyCallback':['NativeArkWebOnJavaScriptProxyCallback', 'NULL'],
376    'ArkWebCharVector':['ArkWebCharVector', 'ark_web_char_vector_default'],
377    'ArkWebUint8Vector':['ArkWebUint8Vector', 'ark_web_uint8_vector_default'],
378    'ArkWebUint16Vector':['ArkWebUint16Vector', 'ark_web_uint16_vector_default'],
379    'ArkWebInt32Vector':['ArkWebInt32Vector', 'ark_web_int32_vector_default'],
380    'ArkWebInt64Vector':['ArkWebInt64Vector', 'ark_web_int64_vector_default'],
381    'ArkWebUint32Vector':['ArkWebUint32Vector', 'ark_web_uint32_vector_default'],
382    'ArkWebDoubleVector':['ArkWebDoubleVector', 'ark_web_double_vector_default'],
383    'ArkWebBooleanVector':['ArkWebBooleanVector', 'ark_web_boolean_vector_default'],
384    'ArkWebInt32List':['ArkWebInt32List', 'ark_web_int32_list_default'],
385    'ArkWebValue':['ArkWebValue', 'ark_web_value_default'],
386    'ArkWebHapValueMap':['ArkWebHapValueMap', 'ark_web_hap_value_map_default'],
387    'ArkWebHapValueVector':['ArkWebHapValueVector', 'ark_web_hap_value_vector_default'],
388    'ArkWebRomValueMap':['ArkWebRomValueMap', 'ark_web_rom_value_map_default'],
389    'ArkWebRomValueVector':['ArkWebRomValueVector', 'ark_web_rom_value_vector_default'],
390    'ArkWebMessage':['ArkWebMessage', 'ark_web_message_default'],
391    'ArkWebString':['ArkWebString', 'ark_web_string_default'],
392    'ArkWebU16String':['ArkWebU16String', 'ark_web_u16string_default'],
393    'ArkWebStringList':['ArkWebStringList', 'ark_web_string_list_default'],
394    'ArkWebStringMap':['ArkWebStringMap', 'ark_web_string_map_default'],
395    'ArkWebStringVector':['ArkWebStringVector', 'ark_web_string_vector_default'],
396    'ArkWebStringVectorMap':['ArkWebStringVectorMap', 'ark_web_string_vector_map_default'],
397    'ArkWebUInt8VectorMap': ['ArkWebUInt8VectorMap', 'ark_web_uint8_vector_map_default'],
398    'ArkWebValueVector':['ArkWebValueVector', 'ark_web_value_vector_default'],
399    'ArkWebTouchPointInfoVector':['ArkWebTouchPointInfoVector', 'ak_web_touch_point_info_vector_default'],
400    'ArkWebMediaSourceInfoVector':['ArkWebMediaSourceInfoVector', 'ark_web_media_source_info_vector_default'],
401    'ArkWebJsProxyCallbackVector':['ArkWebJsProxyCallbackVector', 'ark_web_js_proxy_callback_vector_default'],
402    'ArkWebWebStorageOriginVector':['ArkWebWebStorageOriginVector', 'ark_web_web_storage_origin_vector_default'],
403    'ArkWebDateTimeSuggestionVector':['ArkWebDateTimeSuggestionVector', 'ark_web_date_time_suggestion_vector_default'],
404    'ArkWebSelectPopupMenuItemVector':[
405        'ArkWebSelectPopupMenuItemVector', 'ark_web_select_popup_menu_item_vector_default'
406    ],
407    'char* const': ['char* const', 'NULL'],
408    'cef_color_t': ['cef_color_t', '0'],
409    'cef_json_parser_error_t': ['cef_json_parser_error_t', 'JSON_NO_ERROR'],
410    'CefAudioParameters': ['cef_audio_parameters_t', 'CefAudioParameters()'],
411    'CefBaseTime': ['cef_basetime_t', 'CefBaseTime()'],
412    'CefBoxLayoutSettings': [
413        'cef_box_layout_settings_t', 'CefBoxLayoutSettings()'
414    ],
415    'CefCompositionUnderline': [
416        'cef_composition_underline_t', 'CefCompositionUnderline()'
417    ],
418    'CefCursorHandle': ['cef_cursor_handle_t', 'kNullCursorHandle'],
419    'CefCursorInfo': ['cef_cursor_info_t', 'CefCursorInfo()'],
420    'CefDraggableRegion': ['cef_draggable_region_t', 'CefDraggableRegion()'],
421    'CefEventHandle': ['cef_event_handle_t', 'kNullEventHandle'],
422    'CefInsets': ['cef_insets_t', 'CefInsets()'],
423    'CefKeyEvent': ['cef_key_event_t', 'CefKeyEvent()'],
424    'CefMainArgs': ['cef_main_args_t', 'CefMainArgs()'],
425    'CefMouseEvent': ['cef_mouse_event_t', 'CefMouseEvent()'],
426    'CefPoint': ['cef_point_t', 'CefPoint()'],
427    'CefPopupFeatures': ['cef_popup_features_t', 'CefPopupFeatures()'],
428    'CefRange': ['cef_range_t', 'CefRange()'],
429    'CefRect': ['cef_rect_t', 'CefRect()'],
430    'CefScreenInfo': ['cef_screen_info_t', 'CefScreenInfo()'],
431    'CefSize': ['cef_size_t', 'CefSize()'],
432    'CefTouchEvent': ['cef_touch_event_t', 'CefTouchEvent()'],
433    'CefTouchHandleState': [
434        'cef_touch_handle_state_t', 'CefTouchHandleState()'
435    ],
436    'CefThreadId': ['cef_thread_id_t', 'TID_UI'],
437    'CefTime': ['cef_time_t', 'CefTime()'],
438    'CefWindowHandle': ['cef_window_handle_t', 'kNullWindowHandle'],
439    'WebSnapshotCallback':['WebSnapshotCallback', 'NULL'],
440    'ArkDisplayAdapterVector': ['ArkDisplayAdapterVector', '{0}'],
441}
442
443
444def get_function_impls(content, ident, has_impl=True):
445  """ Retrieve the function parts from the specified contents as a set of
446    return value, name, arguments and body. Ident must occur somewhere in
447    the value.
448    """
449  # Remove prefix from methods in CToCpp files.
450  content = content.replace('ARK_WEB_NO_SANITIZE("cfi-icall") ', '')
451  content = content.replace('ARK_WEB_NO_SANITIZE("cfi-icall")\n', '')
452
453  # extract the functions
454  find_regex = '\n' + _cre_func + '\((.*?)\)([A-Za-z0-9_\s]{0,})'
455  if has_impl:
456    find_regex += '\{(.*?)\n\}'
457  else:
458    find_regex += '(;)'
459  p = re.compile(find_regex, re.MULTILINE | re.DOTALL)
460  list = p.findall(content)
461
462  # build the function map with the function name as the key
463  result = []
464  for retval, argval, vfmod, body in list:
465    if retval.find(ident) < 0:
466      # the identifier was not found
467      continue
468
469    # remove the identifier
470    retval = retval.replace(ident, '')
471    retval = retval.strip()
472
473    # Normalize the delimiter.
474    retval = retval.replace('\n', ' ')
475
476    # retrieve the function name
477    parts = retval.split(' ')
478    name = parts[-1]
479    del parts[-1]
480    retval = ' '.join(parts)
481
482    # parse the arguments
483    args = []
484    if argval != 'void':
485      for v in argval.split(','):
486        v = v.strip()
487        if len(v) > 0:
488          args.append(v)
489
490    result.append({
491        'retval': retval.strip(),
492        'name': name,
493        'args': args,
494        'vfmod': vfmod.strip(),
495        'body': body if has_impl else '',
496    })
497
498  return result
499
500
501def get_next_function_impl(existing, name):
502  result = None
503  for item in existing:
504    if item['name'] == name:
505      result = item
506      existing.remove(item)
507      break
508  return result
509
510def check_arg_type_is_struct(arg_type):
511  if arg_type == 'ArkWebString' or arg_type == 'ArkWebUint8Vector' or arg_type == 'ArkWebInt64Vector' or \
512      arg_type == 'ArkWebDoubleVector' or arg_type == 'ArkWebBooleanVector' or arg_type == 'ArkWebStringMap' or \
513      arg_type == 'ArkWebStringVector':
514    return True
515  else:
516    return False
517
518
519def check_func_name_is_key_work(func_name):
520  if func_name == 'continue':
521    return True
522  else:
523    return False
524
525
526class obj_header:
527  """ Class representing a C++ header file. """
528
529  def __init__(self):
530    self.filenames = []
531    self.typedefs = []
532    self.funcs = []
533    self.classes = []
534    self.root_directory = None
535
536  def set_root_directory(self, root_directory):
537    """ Set the root directory. """
538    self.root_directory = root_directory
539
540  def get_root_directory(self):
541    """ Get the root directory. """
542    return self.root_directory
543
544  def add_directory(self, directory, excluded_files=[]):
545    """ Add all header files from the specified directory. """
546    files = system_util.get_files(os.path.join(directory, '*.h'))
547    for file in files:
548      if len(excluded_files) == 0 or not os.path.split(file)[1] in excluded_files:
549        self.add_file(file)
550
551  def add_file(self, filepath):
552    """ Add a header file. """
553
554    if self.root_directory is None:
555      filename = os.path.split(filepath)[1]
556    else:
557      filename = os.path.relpath(filepath, self.root_directory)
558      filename = filename.replace('\\', '/')
559
560    try:
561      # read the input file into memory
562      self.add_data(filename, system_util.read_file(filepath))
563    except Exception:
564      print('Exception while parsing %s' % filepath)
565      raise
566
567  def add_data(self, filename, data):
568    """ Add header file contents. """
569
570    added = False
571
572    # remove space from between template definition end brackets
573    data = data.replace("> >", ">>")
574
575    # extract global typedefs
576    p = re.compile('\ntypedef' + _cre_space + _cre_typedef + ';',
577                   re.MULTILINE | re.DOTALL)
578    list = p.findall(data)
579    if len(list) > 0:
580      # build the global typedef objects
581      for value in list:
582        pos = value.rfind(' ')
583        if pos < 0:
584          raise Exception('Invalid typedef: ' + value)
585        alias = value[pos + 1:].strip()
586        value = value[:pos].strip()
587        self.typedefs.append(obj_typedef(self, filename, value, alias))
588
589    # extract global functions
590    p = re.compile('\n' + _cre_attrib + '\n' + _cre_func + '\((.*?)\)',
591                   re.MULTILINE | re.DOTALL)
592    list = p.findall(data)
593    if len(list) > 0:
594      added = True
595
596      # build the global function objects
597      for attrib, retval, argval in list:
598        comment = get_comment(data, retval + '(' + argval + ');')
599        validate_comment(filename, retval, comment)
600        self.funcs.append(
601            obj_function(self, filename, attrib, retval, argval, comment))
602
603    # extract includes
604    p = re.compile('\n#include \"' + _cre_cfnameorpath + '.h')
605    includes = p.findall(data)
606
607    # extract forward declarations
608    p = re.compile('\nclass' + _cre_space + _cre_cfname + ';')
609    forward_declares = p.findall(data)
610
611    # extract empty classes
612    p = re.compile('\n' + _cre_attrib + '\nclass' + _cre_space + _cre_cfname +
613                   _cre_space + ':' + _cre_space + 'public' + _cre_virtual +
614                   _cre_space + _cre_cfname + _cre_space + '{};',
615                   re.MULTILINE | re.DOTALL)
616    list = p.findall(data)
617    if len(list) > 0:
618      added = True
619
620      # build the class objects
621      for attrib, name, parent_name in list:
622        # Style may place the ':' on the next line.
623        comment = get_comment(data, name + ' :')
624        if len(comment) == 0:
625          comment = get_comment(data, name + "\n")
626        validate_comment(filename, name, comment)
627        self.classes.append(
628            obj_class(self, filename, attrib, name, parent_name, "", comment,
629                      includes, forward_declares))
630
631      # Remove empty classes from |data| so we don't mess up the non-empty
632      # class search that follows.
633      data = p.sub('', data)
634
635    # extract classes
636    p = re.compile('\n' + _cre_attrib + '\nclass' + _cre_space + _cre_cfname +
637                   _cre_space + ':' + _cre_space + 'public' + _cre_virtual +
638                   _cre_space + _cre_cfname + _cre_space + '{(.*?)\n};',
639                   re.MULTILINE | re.DOTALL)
640    list = p.findall(data)
641    if len(list) > 0:
642      added = True
643
644      # build the class objects
645      for attrib, name, parent_name, body in list:
646        # Style may place the ':' on the next line.
647        comment = get_comment(data, name + ' :')
648        if len(comment) == 0:
649          comment = get_comment(data, name + "\n")
650        validate_comment(filename, name, comment)
651        self.classes.append(
652            obj_class(self, filename, attrib, name, parent_name, body, comment,
653                      includes, forward_declares))
654
655    if added:
656      # a global function or class was read from the header file
657      self.filenames.append(filename)
658
659  def __repr__(self):
660    result = ''
661
662    if len(self.typedefs) > 0:
663      strlist = []
664      for cls in self.typedefs:
665        strlist.append(str(cls))
666      result += "\n".join(strlist) + "\n\n"
667
668    if len(self.funcs) > 0:
669      strlist = []
670      for cls in self.funcs:
671        strlist.append(str(cls))
672      result += "\n".join(strlist) + "\n\n"
673
674    if len(self.classes) > 0:
675      strlist = []
676      for cls in self.classes:
677        strlist.append(str(cls))
678      result += "\n".join(strlist)
679
680    return result
681
682  def get_file_names(self):
683    """ Return the array of header file names. """
684    return self.filenames
685
686  def get_typedefs(self):
687    """ Return the array of typedef objects. """
688    return self.typedefs
689
690  def get_funcs(self, filename=None):
691    """ Return the array of function objects. """
692    if filename is None:
693      return self.funcs
694    else:
695      # only return the functions in the specified file
696      res = []
697      for func in self.funcs:
698        if func.get_file_name() == filename:
699          res.append(func)
700      return res
701
702  def get_classes(self, filename=None):
703    """ Return the array of class objects. """
704    if filename is None:
705      return self.classes
706    else:
707      # only return the classes in the specified file
708      res = []
709      for cls in self.classes:
710        if cls.get_file_name() == filename:
711          res.append(cls)
712      return res
713
714  def get_class(self, classname, defined_structs=None):
715    """ Return the specified class or None if not found. """
716    for cls in self.classes:
717      if cls.get_name() == classname:
718        return cls
719      elif not defined_structs is None:
720        defined_structs.append(cls.get_capi_name())
721    return None
722
723  def get_class_names(self):
724    """ Returns the names of all classes in this object. """
725    result = []
726    for cls in self.classes:
727      result.append(cls.get_name())
728    return result
729
730  def get_base_class_name(self, classname):
731    """ Returns the base (root) class name for |classname|. """
732    cur_cls = self.get_class(classname)
733    while True:
734      parent_name = cur_cls.get_parent_name()
735      if is_base_class(parent_name):
736        return parent_name
737      else:
738        parent_cls = self.get_class(parent_name)
739        if parent_cls is None:
740          break
741      cur_cls = self.get_class(parent_name)
742    return None
743
744  def get_types(self, list):
745    """ Return a dictionary mapping data types to analyzed values. """
746    for cls in self.typedefs:
747      cls.get_types(list)
748
749    for cls in self.classes:
750      cls.get_types(list)
751
752  def get_alias_translation(self, alias):
753    """ Return a translation of alias to value based on typedef
754            statements. """
755    for cls in self.typedefs:
756      if cls.alias == alias:
757        return cls.value
758    return None
759
760  def get_analysis(self, value, named=True):
761    """ Return an analysis of the value based the header file context. """
762    return obj_analysis([self], value, named)
763
764  def get_defined_structs(self):
765    """ Return a list of already defined structure names. """
766    return [
767        'cef_print_info_t', 'cef_window_info_t', 'cef_base_ref_counted_t',
768        'cef_base_scoped_t'
769    ]
770
771  def get_capi_translations(self):
772    """ Return a dictionary that maps C++ terminology to C API terminology.
773        """
774    # strings that will be changed in C++ comments
775    map = {
776        'class': 'structure',
777        'Class': 'Structure',
778        'interface': 'structure',
779        'Interface': 'Structure',
780        'true': 'true (1)',
781        'false': 'false (0)',
782        'empty': 'NULL',
783        'method': 'function'
784    }
785
786    # add mappings for all classes and functions
787    funcs = self.get_funcs()
788    for func in funcs:
789      map[func.get_name() + '()'] = func.get_capi_name() + '()'
790
791    classes = self.get_classes()
792    for cls in classes:
793      map[cls.get_name()] = cls.get_capi_name()
794
795      funcs = cls.get_virtual_funcs()
796      for func in funcs:
797        map[func.get_name() + '()'] = func.get_capi_name() + '()'
798
799      funcs = cls.get_static_funcs()
800      for func in funcs:
801        map[func.get_name() + '()'] = func.get_capi_name() + '()'
802
803    return map
804
805
806class obj_class:
807  """ Class representing a C++ class. """
808
809  def __init__(self, parent, filename, attrib, name, parent_name, body, comment,
810               includes, forward_declares):
811    if not isinstance(parent, obj_header):
812      raise Exception('Invalid parent object type')
813
814    self.parent = parent
815    self.filename = filename
816    self.attribs = str_to_dict(attrib)
817    self.name = name
818    self.parent_name = parent_name
819    self.comment = comment
820    self.includes = includes
821    self.forward_declares = forward_declares
822
823    # extract typedefs
824    p = re.compile(
825        '\n' + _cre_space + 'typedef' + _cre_space + _cre_typedef + ';',
826        re.MULTILINE | re.DOTALL)
827    list = p.findall(body)
828
829    # build the typedef objects
830    self.typedefs = []
831    for value in list:
832      pos = value.rfind(' ')
833      if pos < 0:
834        raise Exception('Invalid typedef: ' + value)
835      alias = value[pos + 1:].strip()
836      value = value[:pos].strip()
837      self.typedefs.append(obj_typedef(self, filename, value, alias))
838
839    # extract static functions
840    p = re.compile('\n' + _cre_space + _cre_attrib + '\n' + _cre_space +
841                   'static' + _cre_space + _cre_func + '\((.*?)\)',
842                   re.MULTILINE | re.DOTALL)
843    list = p.findall(body)
844
845    # build the static function objects
846    self.staticfuncs = []
847    for attrib, retval, argval in list:
848      comment = get_comment(body, retval + '(' + argval + ')')
849      validate_comment(filename, retval, comment)
850      self.staticfuncs.append(
851          obj_function_static(self, attrib, retval, argval, comment))
852
853    # extract virtual functions
854    p = re.compile(
855        '\n' + _cre_space + _cre_attrib + '\n' + _cre_space + 'virtual' +
856        _cre_space + _cre_func + '\((.*?)\)' + _cre_vfmod,
857        re.MULTILINE | re.DOTALL)
858    list = p.findall(body)
859
860    # build the virtual function objects
861    self.virtualfuncs = []
862    for attrib, retval, argval, vfmod in list:
863      comment = get_comment(body, retval + '(' + argval + ')')
864      validate_comment(filename, retval, comment)
865      self.virtualfuncs.append(
866          obj_function_virtual(self, attrib, retval, argval, comment,
867                               vfmod.strip()))
868
869  def __repr__(self):
870    result = '/* ' + dict_to_str(
871        self.attribs) + ' */ class ' + self.name + "\n{"
872
873    if len(self.typedefs) > 0:
874      result += "\n\t"
875      strlist = []
876      for cls in self.typedefs:
877        strlist.append(str(cls))
878      result += "\n\t".join(strlist)
879
880    if len(self.staticfuncs) > 0:
881      result += "\n\t"
882      strlist = []
883      for cls in self.staticfuncs:
884        strlist.append(str(cls))
885      result += "\n\t".join(strlist)
886
887    if len(self.virtualfuncs) > 0:
888      result += "\n\t"
889      strlist = []
890      for cls in self.virtualfuncs:
891        strlist.append(str(cls))
892      result += "\n\t".join(strlist)
893
894    result += "\n};\n"
895    return result
896
897  def get_file_name(self):
898    """ Return the C++ header file name. Includes the directory component,
899            if any. """
900    return self.filename
901
902  def get_capi_file_name(self):
903    """ Return the CAPI header file name. Includes the directory component,
904            if any. """
905    return get_capi_file_name(self.filename)
906
907  def get_file_directory(self):
908    """ Return the file directory component, if any. """
909    pos = self.filename.rfind('/')
910    if pos >= 0:
911      return self.filename[:pos]
912    return None
913
914  def get_name(self):
915    """ Return the class name. """
916    return self.name
917
918  def get_capi_name(self):
919    """ Return the CAPI structure name for this class. """
920    return get_capi_name(self.name, True)
921
922  def get_parent_name(self):
923    """ Return the parent class name. """
924    return self.parent_name
925
926  def get_parent_capi_name(self):
927    """ Return the CAPI structure name for the parent class. """
928    return get_capi_name(self.parent_name, True)
929
930  def has_parent(self, parent_name):
931    """ Returns true if this class has the specified class anywhere in its
932            inheritance hierarchy. """
933    # Every class has a known base class as the top-most parent.
934    if is_base_class(parent_name) or parent_name == self.parent_name:
935      return True
936    if is_base_class(self.parent_name):
937      return False
938
939    cur_cls = self.parent.get_class(self.parent_name)
940    while True:
941      cur_parent_name = cur_cls.get_parent_name()
942      if is_base_class(cur_parent_name):
943        break
944      elif cur_parent_name == parent_name:
945        return True
946      cur_cls = self.parent.get_class(cur_parent_name)
947
948    return False
949
950  def get_comment(self):
951    """ Return the class comment as an array of lines. """
952    return self.comment
953
954  def get_includes(self):
955    """ Return the list of classes that are included from this class'
956            header file. """
957    return self.includes
958
959  def get_forward_declares(self):
960    """ Return the list of classes that are forward declared for this
961            class. """
962    return self.forward_declares
963
964  def get_attribs(self):
965    """ Return all attributes as a dictionary. """
966    return self.attribs
967
968  def has_attrib(self, name):
969    """ Return true if the specified attribute exists. """
970    return name in self.attribs
971
972  def get_attrib(self, name):
973    """ Return the first or only value for specified attribute. """
974    if name in self.attribs:
975      if isinstance(self.attribs[name], list):
976        # the value is a list
977        return self.attribs[name][0]
978      else:
979        # the value is a string
980        return self.attribs[name]
981    return None
982
983  def get_attrib_list(self, name):
984    """ Return all values for specified attribute as a list. """
985    if name in self.attribs:
986      if isinstance(self.attribs[name], list):
987        # the value is already a list
988        return self.attribs[name]
989      else:
990        # convert the value to a list
991        return [self.attribs[name]]
992    return None
993
994  def get_typedefs(self):
995    """ Return the array of typedef objects. """
996    return self.typedefs
997
998  def has_typedef_alias(self, alias):
999    """ Returns true if the specified typedef alias is defined in the scope
1000            of this class declaration. """
1001    for typedef in self.typedefs:
1002      if typedef.get_alias() == alias:
1003        return True
1004    return False
1005
1006  def get_static_funcs(self):
1007    """ Return the array of static function objects. """
1008    return self.staticfuncs
1009
1010  def get_virtual_funcs(self):
1011    """ Return the array of virtual function objects. """
1012    return self.virtualfuncs
1013
1014  def get_types(self, list):
1015    """ Return a dictionary mapping data types to analyzed values. """
1016    for cls in self.typedefs:
1017      cls.get_types(list)
1018
1019    for cls in self.staticfuncs:
1020      cls.get_types(list)
1021
1022    for cls in self.virtualfuncs:
1023      cls.get_types(list)
1024
1025  def get_alias_translation(self, alias):
1026    for cls in self.typedefs:
1027      if cls.alias == alias:
1028        return cls.value
1029    return None
1030
1031  def get_analysis(self, value, named=True):
1032    """ Return an analysis of the value based on the class definition
1033        context.
1034        """
1035    return obj_analysis([self, self.parent], value, named)
1036
1037  def is_webview_side(self):
1038    """ Returns true if the class is implemented by the library. """
1039    return self.attribs['source'] == 'webview'
1040
1041  def is_webcore_side(self):
1042    """ Returns true if the class is implemented by the client. """
1043    return self.attribs['source'] == 'webcore'
1044
1045
1046class obj_typedef:
1047  """ Class representing a typedef statement. """
1048
1049  def __init__(self, parent, filename, value, alias):
1050    if not isinstance(parent, obj_header) \
1051        and not isinstance(parent, obj_class):
1052      raise Exception('Invalid parent object type')
1053
1054    self.parent = parent
1055    self.filename = filename
1056    self.alias = alias
1057    self.value = self.parent.get_analysis(value, False)
1058
1059  def __repr__(self):
1060    return 'typedef ' + self.value.get_type() + ' ' + self.alias + ';'
1061
1062  def get_file_name(self):
1063    """ Return the C++ header file name. """
1064    return self.filename
1065
1066  def get_capi_file_name(self):
1067    """ Return the CAPI header file name. """
1068    return get_capi_file_name(self.filename)
1069
1070  def get_alias(self):
1071    """ Return the alias. """
1072    return self.alias
1073
1074  def get_value(self):
1075    """ Return an analysis of the value based on the class or header file
1076        definition context.
1077        """
1078    return self.value
1079
1080  def get_types(self, list):
1081    """ Return a dictionary mapping data types to analyzed values. """
1082    name = self.value.get_type()
1083    if not name in list:
1084      list[name] = self.value
1085
1086
1087class obj_function:
1088  """ Class representing a function. """
1089
1090  def __init__(self, parent, filename, attrib, retval, argval, comment):
1091    self.parent = parent
1092    self.filename = filename
1093    self.attribs = str_to_dict(attrib)
1094    self.retval = obj_argument(self, retval)
1095    self.name = self.retval.remove_name()
1096    self.comment = comment
1097
1098    # build the argument objects
1099    self.arguments = []
1100    arglist = argval.split(',')
1101    argindex = 0
1102    while argindex < len(arglist):
1103      arg = arglist[argindex]
1104      if arg.find('<') >= 0 and arg.find('>') == -1:
1105        # We've split inside of a template type declaration. Join the
1106        # next argument with this argument.
1107        argindex += 1
1108        arg += ',' + arglist[argindex]
1109
1110      arg = arg.strip()
1111      if len(arg) > 0:
1112        argument = obj_argument(self, arg)
1113        if argument.needs_attrib_count_func() and \
1114            argument.get_attrib_count_func() is None:
1115          raise Exception("A 'count_func' attribute is required "+ \
1116                          "for the '"+argument.get_name()+ \
1117                          "' parameter to "+self.get_qualified_name())
1118        self.arguments.append(argument)
1119
1120      argindex += 1
1121
1122    if self.retval.needs_attrib_default_retval() and \
1123        self.retval.get_attrib_default_retval() is None:
1124      raise Exception("A 'default_retval' attribute is required for "+ \
1125                      self.get_qualified_name())
1126
1127  def __repr__(self):
1128    return '/* ' + dict_to_str(self.attribs) + ' */ ' + self.get_cpp_proto()
1129
1130  def get_file_name(self):
1131    """ Return the C++ header file name. """
1132    return self.filename
1133
1134  def get_capi_file_name(self):
1135    """ Return the CAPI header file name. """
1136    return get_capi_file_name(self.filename)
1137
1138  def get_name(self):
1139    """ Return the function name. """
1140    return self.name
1141
1142  def get_qualified_name(self):
1143    """ Return the fully qualified function name. """
1144    if isinstance(self.parent, obj_header):
1145      # global function
1146      return self.name
1147    else:
1148      # member function
1149      return self.parent.get_name() + '::' + self.name
1150
1151  def get_capi_name(self, prefix=None):
1152    """ Return the CAPI function name. """
1153    if 'capi_name' in self.attribs:
1154      return self.attribs['capi_name']
1155    return get_capi_name(self.name, False, prefix)
1156
1157  def get_comment(self):
1158    """ Return the function comment as an array of lines. """
1159    return self.comment
1160
1161  def get_attribs(self):
1162    """ Return all attributes as a dictionary. """
1163    return self.attribs
1164
1165  def has_attrib(self, name):
1166    """ Return true if the specified attribute exists. """
1167    return name in self.attribs
1168
1169  def get_attrib(self, name):
1170    """ Return the first or only value for specified attribute. """
1171    if name in self.attribs:
1172      if isinstance(self.attribs[name], list):
1173        # the value is a list
1174        return self.attribs[name][0]
1175      else:
1176        # the value is a string
1177        return self.attribs[name]
1178    return None
1179
1180  def get_attrib_list(self, name):
1181    """ Return all values for specified attribute as a list. """
1182    if name in self.attribs:
1183      if isinstance(self.attribs[name], list):
1184        # the value is already a list
1185        return self.attribs[name]
1186      else:
1187        # convert the value to a list
1188        return [self.attribs[name]]
1189    return None
1190
1191  def get_retval(self):
1192    """ Return the return value object. """
1193    return self.retval
1194
1195  def get_arguments(self):
1196    """ Return the argument array. """
1197    return self.arguments
1198
1199  def get_types(self, list):
1200    """ Return a dictionary mapping data types to analyzed values. """
1201    for cls in self.arguments:
1202      cls.get_types(list)
1203
1204  def get_capi_parts(self, defined_structs=[], isimpl=False, prefix=None):
1205    """ Return the parts of the C API function definition. """
1206    retval = ''
1207    dict = self.retval.get_type().get_capi(defined_structs)
1208    if dict['format'] == 'single':
1209      retval = dict['value']
1210
1211    name = self.get_capi_name(prefix)
1212    args = []
1213
1214    if isinstance(self, obj_function_virtual):
1215      # virtual functions get themselves as the first argument
1216      str = 'struct _' + self.parent.get_capi_name() + '* self'
1217      if isinstance(self, obj_function_virtual) and self.is_const():
1218        # const virtual functions get const self pointers
1219        str = 'const ' + str
1220      args.append(str)
1221    elif not isimpl and len(self.arguments) == 0:
1222      args.append('void')
1223
1224    if len(self.arguments) > 0:
1225      for cls in self.arguments:
1226        type = cls.get_type()
1227        dict = type.get_capi(defined_structs)
1228        if dict['format'] == 'single':
1229          args.append(dict['value'])
1230        elif dict['format'] == 'multi-arg':
1231          # add an additional argument for the size of the array
1232          type_name = type.get_name()
1233          if type.is_const():
1234            # for const arrays pass the size argument by value
1235            args.append('size_t ' + type_name + 'Count')
1236          else:
1237            # for non-const arrays pass the size argument by address
1238            args.append('size_t* ' + type_name + 'Count')
1239          args.append(dict['value'])
1240
1241    return {'retval': retval, 'name': name, 'args': args}
1242
1243  def get_capi_proto(self, defined_structs=[], suffix="", isimpl=False, prefix=None):
1244    """ Return the prototype of the C API function. """
1245    parts = self.get_capi_parts(defined_structs, isimpl, prefix)
1246    result = parts['retval']+' '+parts['name'] + suffix + \
1247             '('+', '.join(parts['args'])+')'
1248    return result
1249
1250  def get_cpp_parts(self, isimpl=False):
1251    """ Return the parts of the C++ function definition. """
1252    retval = str(self.retval)
1253    name = self.name
1254
1255    args = []
1256    if len(self.arguments) > 0:
1257      for cls in self.arguments:
1258        args.append(str(cls))
1259
1260    if isimpl and isinstance(self, obj_function_virtual):
1261      # enumeration return values must be qualified with the class name
1262      # if the type is defined in the class declaration scope.
1263      type = self.get_retval().get_type()
1264      if type.is_result_struct() and type.is_result_struct_enum() and \
1265          self.parent.has_typedef_alias(retval):
1266        retval = self.parent.get_name() + '::' + retval
1267
1268    return {'retval': retval, 'name': name, 'args': args}
1269
1270  def get_cpp_proto(self, classname=None):
1271    """ Return the prototype of the C++ function. """
1272    parts = self.get_cpp_parts()
1273    result = parts['retval'] + ' '
1274    if not classname is None:
1275      result += classname + '::'
1276    result += parts['name'] + '(' + ', '.join(parts['args']) + ')'
1277    if isinstance(self, obj_function_virtual) and self.is_const():
1278      result += ' const'
1279    return result
1280
1281  def is_same_side(self, other_class_name):
1282    """ Returns true if this function is on the same side (library or
1283            client) and the specified class. """
1284    if isinstance(self.parent, obj_class):
1285      # this function is part of a class
1286      this_is_webview_side = self.parent.is_webview_side()
1287      header = self.parent.parent
1288    else:
1289      # this function is global
1290      this_is_webview_side = True
1291      header = self.parent
1292
1293    if is_base_class(other_class_name):
1294      other_is_webview_side = False
1295    else:
1296      other_class = header.get_class(other_class_name)
1297      if other_class is None:
1298        raise Exception('Unknown class: ' + other_class_name)
1299      other_is_webview_side = other_class.is_webview_side()
1300
1301    return other_is_webview_side == this_is_webview_side
1302
1303
1304class obj_function_static(obj_function):
1305  """ Class representing a static function. """
1306
1307  def __init__(self, parent, attrib, retval, argval, comment):
1308    if not isinstance(parent, obj_class):
1309      raise Exception('Invalid parent object type')
1310    obj_function.__init__(self, parent, parent.filename, attrib, retval, argval,
1311                          comment)
1312
1313  def __repr__(self):
1314    return 'static ' + obj_function.__repr__(self) + ';'
1315
1316  def get_capi_name(self, prefix=None):
1317    """ Return the CAPI function name. """
1318    if prefix is None:
1319      # by default static functions are prefixed with the class name
1320      prefix = get_capi_name(self.parent.get_name(), False)
1321    return obj_function.get_capi_name(self, prefix)
1322
1323
1324class obj_function_virtual(obj_function):
1325  """ Class representing a virtual function. """
1326
1327  def __init__(self, parent, attrib, retval, argval, comment, vfmod):
1328    if not isinstance(parent, obj_class):
1329      raise Exception('Invalid parent object type')
1330    obj_function.__init__(self, parent, parent.filename, attrib, retval, argval,
1331                          comment)
1332    if vfmod == 'const':
1333      self.isconst = True
1334    else:
1335      self.isconst = False
1336
1337  def __repr__(self):
1338    return 'virtual ' + obj_function.__repr__(self) + ';'
1339
1340  def is_const(self):
1341    """ Returns true if the method declaration is const. """
1342    return self.isconst
1343
1344
1345class obj_argument:
1346  """ Class representing a function argument. """
1347
1348  def __init__(self, parent, argval):
1349    if not isinstance(parent, obj_function):
1350      raise Exception('Invalid parent object type')
1351
1352    self.parent = parent
1353    self.type = self.parent.parent.get_analysis(argval)
1354
1355  def __repr__(self):
1356    result = ''
1357    if self.type.is_const():
1358      result += 'const '
1359    result += self.type.get_type()
1360    if self.type.is_byref():
1361      result += '&'
1362    elif self.type.is_byaddr():
1363      result += '*'
1364    if self.type.has_name():
1365      result += ' ' + self.type.get_name()
1366    return result
1367
1368  def get_name(self):
1369    """ Return the name for this argument. """
1370    return self.type.get_name()
1371
1372  def remove_name(self):
1373    """ Remove and return the name value. """
1374    name = self.type.get_name()
1375    self.type.name = None
1376    return name
1377
1378  def get_type(self):
1379    """ Return an analysis of the argument type based on the class
1380        definition context.
1381        """
1382    return self.type
1383
1384  def get_types(self, list):
1385    """ Return a dictionary mapping data types to analyzed values. """
1386    name = self.type.get_type()
1387    if not name in list:
1388      list[name] = self.type
1389
1390  def get_raw_type(self):
1391    result = ''
1392    if self.type.is_const():
1393      result += 'const '
1394    result += self.type.get_type()
1395    if self.type.is_byref():
1396      result += '&'
1397    elif self.type.is_byaddr():
1398      result += '*'
1399    return result
1400
1401  def needs_attrib_count_func(self):
1402    """ Returns true if this argument requires a 'count_func' attribute. """
1403    # A 'count_func' attribute is required for non-const non-string vector
1404    # attribute types
1405    return self.type.has_name() and \
1406        self.type.is_result_vector() and \
1407        not self.type.is_result_vector_string() and \
1408        not self.type.is_const()
1409
1410  def get_attrib_count_func(self):
1411    """ Returns the count function for this argument. """
1412    # The 'count_func' attribute value format is name:function
1413    if not self.parent.has_attrib('count_func'):
1414      return None
1415    name = self.type.get_name()
1416    vals = self.parent.get_attrib_list('count_func')
1417    for val in vals:
1418      parts = val.split(':')
1419      if len(parts) != 2:
1420        raise Exception("Invalid 'count_func' attribute value for "+ \
1421                        self.parent.get_qualified_name()+': '+val)
1422      if parts[0].strip() == name:
1423        return parts[1].strip()
1424    return None
1425
1426  def needs_attrib_default_retval(self):
1427    """ Returns true if this argument requires a 'default_retval' attribute.
1428        """
1429    # A 'default_retval' attribute is required for enumeration return value
1430    # types.
1431    return not self.type.has_name() and \
1432        self.type.is_result_struct() and \
1433        self.type.is_result_struct_enum()
1434
1435  def get_attrib_default_retval(self):
1436    """ Returns the defualt return value for this argument. """
1437    return self.parent.get_attrib('default_retval')
1438
1439  def get_arg_type(self):
1440    """ Returns the argument type as defined in translator.README.txt. """
1441    if not self.type.has_name():
1442      raise Exception('Cannot be called for retval types')
1443
1444    # simple or enumeration type
1445    if (self.type.is_result_simple() and \
1446            self.type.get_type() != 'bool') or \
1447       (self.type.is_result_struct() and \
1448            self.type.is_result_struct_enum()):
1449      if self.type.is_byref():
1450        if self.type.is_const():
1451          return 'simple_byref_const'
1452        return 'simple_byref'
1453      elif self.type.is_byaddr():
1454        return 'simple_byaddr'
1455      return 'simple_byval'
1456
1457    # boolean type
1458    if self.type.get_type() == 'bool':
1459      if self.type.is_byref():
1460        return 'bool_byref'
1461      elif self.type.is_byaddr():
1462        return 'bool_byaddr'
1463      return 'bool_byval'
1464
1465    # structure type
1466    if self.type.is_result_struct() and self.type.is_byref():
1467      if self.type.is_const():
1468        return 'struct_byref_const'
1469      return 'struct_byref'
1470
1471    # string type
1472    if self.type.is_result_string() and self.type.is_byref():
1473      if self.type.is_const():
1474        return 'string_byref_const'
1475      return 'string_byref'
1476
1477    # *ptr type
1478    if self.type.is_result_ptr():
1479      prefix = self.type.get_result_ptr_type_prefix()
1480      same_side = self.parent.is_same_side(self.type.get_ptr_type())
1481      if self.type.is_byref():
1482        if same_side:
1483          return prefix + 'ptr_same_byref'
1484        return prefix + 'ptr_diff_byref'
1485      if same_side:
1486        return prefix + 'ptr_same'
1487      return prefix + 'ptr_diff'
1488
1489    if self.type.is_result_vector():
1490      # all vector types must be passed by reference
1491      if not self.type.is_byref():
1492        return 'invalid'
1493
1494      if self.type.is_result_vector_string():
1495        # string vector type
1496        if self.type.is_const():
1497          return 'string_vec_byref_const'
1498        return 'string_vec_byref'
1499
1500      if self.type.is_result_vector_simple():
1501        if self.type.get_vector_type() != 'bool':
1502          # simple/enumeration vector types
1503          if self.type.is_const():
1504            return 'simple_vec_byref_const'
1505          return 'simple_vec_byref'
1506
1507        # boolean vector types
1508        if self.type.is_const():
1509          return 'bool_vec_byref_const'
1510        return 'bool_vec_byref'
1511
1512      if self.type.is_result_vector_ptr():
1513        # *ptr vector types
1514        prefix = self.type.get_result_vector_ptr_type_prefix()
1515        same_side = self.parent.is_same_side(self.type.get_ptr_type())
1516        if self.type.is_const():
1517          if same_side:
1518            return prefix + 'ptr_vec_same_byref_const'
1519          return prefix + 'ptr_vec_diff_byref_const'
1520        if same_side:
1521          return prefix + 'ptr_vec_same_byref'
1522        return prefix + 'ptr_vec_diff_byref'
1523
1524    # string single map type
1525    if self.type.is_result_map_single():
1526      if not self.type.is_byref():
1527        return 'invalid'
1528      if self.type.is_const():
1529        return 'string_map_single_byref_const'
1530      return 'string_map_single_byref'
1531
1532    # string multi map type
1533    if self.type.is_result_map_multi():
1534      if not self.type.is_byref():
1535        return 'invalid'
1536      if self.type.is_const():
1537        return 'string_map_multi_byref_const'
1538      return 'string_map_multi_byref'
1539
1540    return 'invalid'
1541
1542  def get_retval_type(self):
1543    """ Returns the retval type as defined in translator.README.txt. """
1544    if self.type.has_name():
1545      raise Exception('Cannot be called for argument types')
1546
1547    if check_arg_type_is_struct(self.type.get_type()):
1548      return self.type.get_type()
1549
1550    if self.type.get_type() == 'void' and self.type.is_byaddr():
1551      return "void*"
1552
1553    if self.type.get_type() == 'uint8_t' and self.type.is_byaddr():
1554      return "uint8_t*"
1555
1556    if self.type.get_type() == 'uint32_t' and self.type.is_byaddr():
1557      return "uint32_t*"
1558
1559    if self.type.get_type() == 'char' and self.type.is_byaddr():
1560      return "char*"
1561
1562    # unsupported modifiers
1563    if self.type.is_const() or self.type.is_byref() or \
1564        self.type.is_byaddr():
1565      return 'invalid'
1566
1567    # void types don't have a return value
1568    if self.type.get_type() == 'void':
1569      return 'none'
1570
1571    if (self.type.is_result_simple() and \
1572            self.type.get_type() != 'bool') or \
1573       (self.type.is_result_struct() and self.type.is_result_struct_enum()):
1574      return 'simple'
1575
1576    if self.type.get_type() == 'bool':
1577      return 'bool'
1578
1579    if self.type.is_result_string():
1580      return 'string'
1581
1582    if self.type.is_result_ptr():
1583      prefix = self.type.get_result_ptr_type_prefix()
1584      if self.parent.is_same_side(self.type.get_ptr_type()):
1585        return prefix + 'ptr_same'
1586      else:
1587        return prefix + 'ptr_diff'
1588
1589    return 'invalid'
1590
1591  def get_retval_default(self, for_capi):
1592    """ Returns the default return value based on the retval type. """
1593    # start with the default retval attribute, if any.
1594    retval = self.get_attrib_default_retval()
1595    if not retval is None:
1596      if for_capi:
1597        # apply any appropriate C API translations.
1598        if retval == 'true':
1599          return '1'
1600        if retval == 'false':
1601          return '0'
1602      return retval
1603
1604    # next look at the retval type value.
1605    type = self.get_retval_type()
1606    if type == 'simple' or check_arg_type_is_struct(type):
1607      return self.get_type().get_result_simple_default()
1608    elif type == 'bool':
1609      return 'false'
1610    elif type == 'string':
1611      if for_capi:
1612        return 'NULL'
1613      return 'CefString()'
1614    elif type == 'refptr_same' or type == 'refptr_diff' or \
1615         type == 'rawptr_same' or type == 'rawptr_diff' or type == 'void*' or \
1616         type == 'uint8_t*' or type == 'uint32_t*' or type == 'char*':
1617      if for_capi:
1618        return 'NULL'
1619      return 'nullptr'
1620    elif type == 'ownptr_same' or type == 'ownptr_diff':
1621      if for_capi:
1622        return 'NULL'
1623      return 'CefOwnPtr<' + self.type.get_ptr_type() + '>()'
1624
1625    return ''
1626
1627
1628class obj_analysis:
1629  """ Class representing an analysis of a data type value. """
1630
1631  def __init__(self, scopelist, value, named):
1632    self.value = value
1633    self.result_type = 'unknown'
1634    self.result_value = None
1635    self.result_default = None
1636    self.ptr_type = None
1637
1638    # parse the argument string
1639    partlist = value.strip().split()
1640
1641    if named:
1642      # extract the name value
1643      self.name = partlist[-1]
1644      del partlist[-1]
1645    else:
1646      self.name = None
1647
1648    if len(partlist) == 0:
1649      raise Exception('Invalid argument value: ' + value)
1650
1651    # check const status
1652    if partlist[0] == 'const':
1653      self.isconst = True
1654      del partlist[0]
1655    else:
1656      self.isconst = False
1657
1658    if len(partlist) == 0:
1659      raise Exception('Invalid argument value: ' + value)
1660
1661    # combine the data type
1662    self.type = ' '.join(partlist)
1663
1664    # extract the last character of the data type
1665    endchar = self.name[0]
1666
1667    # check if the value is passed by reference
1668    if endchar == '&':
1669      self.isbyref = True
1670      self.name = self.name[1:]
1671    else:
1672      self.isbyref = False
1673
1674    # check if the value is passed by address
1675    if endchar == '*':
1676      self.isbyaddr = True
1677      self.name = self.name[1:]
1678    else:
1679      self.isbyaddr = False
1680
1681    # see if the value is directly identifiable
1682    if self._check_advanced(self.type):
1683      return
1684
1685    # not identifiable, so look it up
1686    translation = None
1687    for scope in scopelist:
1688      if not isinstance(scope, obj_header) \
1689          and not isinstance(scope, obj_class):
1690        raise Exception('Invalid scope object type')
1691      translation = scope.get_alias_translation(self.type)
1692      if not translation is None:
1693        break
1694
1695    if translation is None:
1696      raise Exception('Failed to translate type: ' + self.type)
1697
1698    # the translation succeeded so keep the result
1699    self.result_type = translation.result_type
1700    self.result_value = translation.result_value
1701
1702  def _check_advanced(self, value):
1703    # check for vectors
1704    if value.find('std::vector') == 0:
1705      self.result_type = 'vector'
1706      val = value[12:-1].strip()
1707      self.result_value = [self._get_basic(val)]
1708      self.result_value[0]['vector_type'] = val
1709      return True
1710
1711    # check for maps
1712    if value.find('std::map') == 0:
1713      self.result_type = 'map'
1714      vals = value[9:-1].split(',')
1715      if len(vals) == 2:
1716        self.result_value = [
1717            self._get_basic(vals[0].strip()),
1718            self._get_basic(vals[1].strip())
1719        ]
1720        return True
1721
1722    # check for multimaps
1723    if value.find('std::multimap') == 0:
1724      self.result_type = 'multimap'
1725      vals = value[14:-1].split(',')
1726      if len(vals) == 2:
1727        self.result_value = [
1728            self._get_basic(vals[0].strip()),
1729            self._get_basic(vals[1].strip())
1730        ]
1731        return True
1732
1733    # check for basic types
1734    basic = self._get_basic(value)
1735    if not basic is None:
1736      self.result_type = basic['result_type']
1737      self.result_value = basic['result_value']
1738      if 'ptr_type' in basic:
1739        self.ptr_type = basic['ptr_type']
1740      if 'result_default' in basic:
1741        self.result_default = basic['result_default']
1742      return True
1743
1744    return False
1745
1746  def _get_basic(self, value):
1747    # check for string values
1748    if value == "CefString":
1749      return {'result_type': 'string', 'result_value': None}
1750
1751    # check for simple direct translations
1752    if value in _simpletypes.keys():
1753      return {
1754          'result_type': 'simple',
1755          'result_value': _simpletypes[value][0],
1756          'result_default': _simpletypes[value][1],
1757      }
1758
1759    # check if already a C API structure
1760    if value[-2:] == '_t':
1761      return {'result_type': 'structure', 'result_value': value}
1762
1763    # check for CEF reference pointers
1764    p = re.compile('^ArkWebRefPtr<(.*?)>$', re.DOTALL)
1765    list = p.findall(value)
1766    if len(list) == 1:
1767      return {
1768          'result_type': 'refptr',
1769          'result_value': get_capi_name(list[0], True) + '*',
1770          'ptr_type': list[0]
1771      }
1772
1773    # check for CEF owned pointers
1774    p = re.compile('^CefOwnPtr<(.*?)>$', re.DOTALL)
1775    list = p.findall(value)
1776    if len(list) == 1:
1777      return {
1778          'result_type': 'ownptr',
1779          'result_value': get_capi_name(list[0], True) + '*',
1780          'ptr_type': list[0]
1781      }
1782
1783    # check for CEF raw pointers
1784    p = re.compile('^CefRawPtr<(.*?)>$', re.DOTALL)
1785    list = p.findall(value)
1786    if len(list) == 1:
1787      return {
1788          'result_type': 'rawptr',
1789          'result_value': get_capi_name(list[0], True) + '*',
1790          'ptr_type': list[0]
1791      }
1792
1793    # check for CEF structure types
1794    if value[0:3] == 'Cef' and value[-4:] != 'List':
1795      return {
1796          'result_type': 'structure',
1797          'result_value': get_capi_name(value, True)
1798      }
1799
1800    return None
1801
1802  def __repr__(self):
1803    return '(' + self.result_type + ') ' + str(self.result_value)
1804
1805  def has_name(self):
1806    """ Returns true if a name value exists. """
1807    return (not self.name is None)
1808
1809  def get_name(self):
1810    """ Return the name. """
1811    return self.name
1812
1813  def get_value(self):
1814    """ Return the C++ value (type + name). """
1815    return self.value
1816
1817  def get_type(self):
1818    """ Return the C++ type. """
1819    return self.type
1820
1821  def get_ptr_type(self):
1822    """ Return the C++ class type referenced by a ArkWebRefPtr. """
1823    if self.is_result_vector() and self.is_result_vector_ptr():
1824      # return the vector RefPtr type
1825      return self.result_value[0]['ptr_type']
1826    # return the basic RefPtr type
1827    return self.ptr_type
1828
1829  def get_vector_type(self):
1830    """ Return the C++ class type referenced by a std::vector. """
1831    if self.is_result_vector():
1832      return self.result_value[0]['vector_type']
1833    return None
1834
1835  def is_const(self):
1836    """ Returns true if the argument value is constant. """
1837    return self.isconst
1838
1839  def is_byref(self):
1840    """ Returns true if the argument is passed by reference. """
1841    return self.isbyref
1842
1843  def is_byaddr(self):
1844    """ Returns true if the argument is passed by address. """
1845    return self.isbyaddr
1846
1847  def is_result_simple(self):
1848    """ Returns true if this is a simple argument type. """
1849    return (self.result_type == 'simple')
1850
1851  def get_result_simple_type_root(self):
1852    """ Return the simple structure or basic type name. """
1853    return self.result_value
1854
1855  def get_result_simple_type(self):
1856    """ Return the simple type. """
1857    result = ''
1858    if self.is_const():
1859      result += 'const '
1860    result += self.result_value
1861    if self.is_byaddr() or self.is_byref():
1862      result += '*'
1863    return result
1864
1865  def get_result_simple_default(self):
1866    """ Return the default value fo the basic type. """
1867    return self.result_default
1868
1869  def is_result_ptr(self):
1870    """ Returns true if this is a *Ptr type. """
1871    return self.is_result_refptr() or self.is_result_ownptr() or \
1872           self.is_result_rawptr()
1873
1874  def get_result_ptr_type_root(self):
1875    """ Return the *Ptr type structure name. """
1876    return self.result_value[:-1]
1877
1878  def get_result_ptr_type(self, defined_structs=[]):
1879    """ Return the *Ptr type. """
1880    result = self.result_value
1881    if self.is_byref() or self.is_byaddr():
1882      result += '*'
1883    return result
1884
1885  def get_result_ptr_type_prefix(self):
1886    """ Returns the *Ptr type prefix. """
1887    if self.is_result_refptr():
1888      return 'ref'
1889    if self.is_result_ownptr():
1890      return 'own'
1891    if self.is_result_rawptr():
1892      return 'raw'
1893    raise Exception('Not a pointer type')
1894
1895  def is_result_refptr(self):
1896    """ Returns true if this is a RefPtr type. """
1897    return (self.result_type == 'refptr')
1898
1899  def is_result_ownptr(self):
1900    """ Returns true if this is a OwnPtr type. """
1901    return (self.result_type == 'ownptr')
1902
1903  def is_result_rawptr(self):
1904    """ Returns true if this is a RawPtr type. """
1905    return (self.result_type == 'rawptr')
1906
1907  def is_result_struct(self):
1908    """ Returns true if this is a structure type. """
1909    return (self.result_type == 'structure')
1910
1911  def is_result_struct_enum(self):
1912    """ Returns true if this struct type is likely an enumeration. """
1913    # structure values that are passed by reference or address must be
1914    # structures and not enumerations
1915    if not self.is_byref() and not self.is_byaddr():
1916      return True
1917    return False
1918
1919  def get_result_struct_type(self, defined_structs=[]):
1920    """ Return the structure or enumeration type. """
1921    result = ''
1922    is_enum = self.is_result_struct_enum()
1923    if not is_enum:
1924      if self.is_const():
1925        result += 'const '
1926    result += self.result_value
1927    if not is_enum:
1928      result += '*'
1929    return result
1930
1931  def is_result_string(self):
1932    """ Returns true if this is a string type. """
1933    return (self.result_type == 'string')
1934
1935  def get_result_string_type(self):
1936    """ Return the string type. """
1937    if not self.has_name():
1938      # Return values are string structs that the user must free. Use
1939      # the name of the structure as a hint.
1940      return 'cef_string_userfree_t'
1941    elif not self.is_const() and (self.is_byref() or self.is_byaddr()):
1942      # Parameters passed by reference or address. Use the normal
1943      # non-const string struct.
1944      return 'cef_string_t*'
1945    # Const parameters use the const string struct.
1946    return 'const cef_string_t*'
1947
1948  def is_result_vector(self):
1949    """ Returns true if this is a vector type. """
1950    return (self.result_type == 'vector')
1951
1952  def is_result_vector_string(self):
1953    """ Returns true if this is a string vector. """
1954    return self.result_value[0]['result_type'] == 'string'
1955
1956  def is_result_vector_simple(self):
1957    """ Returns true if this is a string vector. """
1958    return self.result_value[0]['result_type'] == 'simple'
1959
1960  def is_result_vector_ptr(self):
1961    """ Returns true if this is a *Ptr vector. """
1962    return self.is_result_vector_refptr() or \
1963           self.is_result_vector_ownptr() or \
1964           self.is_result_vector_rawptr()
1965
1966  def get_result_vector_ptr_type_prefix(self):
1967    """ Returns the *Ptr type prefix. """
1968    if self.is_result_vector_refptr():
1969      return 'ref'
1970    if self.is_result_vector_ownptr():
1971      return 'own'
1972    if self.is_result_vector_rawptr():
1973      return 'raw'
1974    raise Exception('Not a pointer type')
1975
1976  def is_result_vector_refptr(self):
1977    """ Returns true if this is a RefPtr vector. """
1978    return self.result_value[0]['result_type'] == 'refptr'
1979
1980  def is_result_vector_ownptr(self):
1981    """ Returns true if this is a OwnPtr vector. """
1982    return self.result_value[0]['result_type'] == 'ownptr'
1983
1984  def is_result_vector_rawptr(self):
1985    """ Returns true if this is a RawPtr vector. """
1986    return self.result_value[0]['result_type'] == 'rawptr'
1987
1988  def get_result_vector_type_root(self):
1989    """ Return the vector structure or basic type name. """
1990    return self.result_value[0]['result_value']
1991
1992  def get_result_vector_type(self, defined_structs=[]):
1993    """ Return the vector type. """
1994    if not self.has_name():
1995      raise Exception('Cannot use vector as a return type')
1996
1997    type = self.result_value[0]['result_type']
1998    value = self.result_value[0]['result_value']
1999
2000    result = {}
2001    if type == 'string':
2002      result['value'] = 'cef_string_list_t'
2003      result['format'] = 'single'
2004      return result
2005
2006    if type == 'simple':
2007      str = value
2008      if self.is_const():
2009        str += ' const'
2010      str += '*'
2011      result['value'] = str
2012    elif type == 'refptr' or type == 'ownptr' or type == 'rawptr':
2013      str = value
2014      if self.is_const():
2015        str += ' const'
2016      str += '*'
2017      result['value'] = str
2018    else:
2019      raise Exception('Unsupported vector type: ' + type)
2020
2021    # vector values must be passed as a value array parameter
2022    # and a size parameter
2023    result['format'] = 'multi-arg'
2024    return result
2025
2026  def is_result_map(self):
2027    """ Returns true if this is a map type. """
2028    return (self.result_type == 'map' or self.result_type == 'multimap')
2029
2030  def is_result_map_single(self):
2031    """ Returns true if this is a single map type. """
2032    return (self.result_type == 'map')
2033
2034  def is_result_map_multi(self):
2035    """ Returns true if this is a multi map type. """
2036    return (self.result_type == 'multimap')
2037
2038  def get_result_map_type(self, defined_structs=[]):
2039    """ Return the map type. """
2040    if not self.has_name():
2041      raise Exception('Cannot use map as a return type')
2042    if self.result_value[0]['result_type'] == 'string' \
2043        and self.result_value[1]['result_type'] == 'string':
2044      if self.result_type == 'map':
2045        return {'value': 'cef_string_map_t', 'format': 'single'}
2046      elif self.result_type == 'multimap':
2047        return {'value': 'cef_string_multimap_t', 'format': 'multi'}
2048    raise Exception('Only mappings of strings to strings are supported')
2049
2050  def get_capi(self, defined_structs=[]):
2051    """ Format the value for the C API. """
2052    result = ''
2053    format = 'single'
2054    if self.is_result_simple():
2055      result += self.get_result_simple_type()
2056    elif self.is_result_ptr():
2057      result += self.get_result_ptr_type(defined_structs)
2058    elif self.is_result_struct():
2059      result += self.get_result_struct_type(defined_structs)
2060    elif self.is_result_string():
2061      result += self.get_result_string_type()
2062    elif self.is_result_map():
2063      resdict = self.get_result_map_type(defined_structs)
2064      if resdict['format'] == 'single' or resdict['format'] == 'multi':
2065        result += resdict['value']
2066      else:
2067        raise Exception('Unsupported map type')
2068    elif self.is_result_vector():
2069      resdict = self.get_result_vector_type(defined_structs)
2070      if resdict['format'] != 'single':
2071        format = resdict['format']
2072      result += resdict['value']
2073
2074    if self.has_name():
2075      result += ' ' + self.get_name()
2076
2077    return {'format': format, 'value': result}
2078
2079
2080# test the module
2081if __name__ == "__main__":
2082  import pprint
2083  import sys
2084
2085  # verify that the correct number of command-line arguments are provided
2086  if len(sys.argv) != 2:
2087    sys.stderr.write('Usage: ' + sys.argv[0] + ' <directory>')
2088    sys.exit()
2089
2090  pp = pprint.PrettyPrinter(indent=4)
2091
2092  # create the header object
2093  header = obj_header()
2094  header.add_directory(sys.argv[1])
2095
2096  # output the type mapping
2097  types = {}
2098  header.get_types(types)
2099  pp.pprint(types)
2100  sys.stdout.write('\n')
2101
2102  # output the parsed C++ data
2103  sys.stdout.write(str(header))
2104
2105  # output the C API formatted data
2106  defined_names = header.get_defined_structs()
2107  result = ''
2108
2109  # global functions
2110  funcs = header.get_funcs()
2111  if len(funcs) > 0:
2112    for func in funcs:
2113      result += func.get_capi_proto(defined_names, "", True) + ';\n'
2114    result += '\n'
2115
2116  classes = header.get_classes()
2117  for cls in classes:
2118    # virtual functions are inside a structure
2119    result += 'struct ' + cls.get_capi_name() + '\n{\n'
2120    funcs = cls.get_virtual_funcs()
2121    if len(funcs) > 0:
2122      for func in funcs:
2123        result += '\t' + func.get_capi_proto(defined_names, "", True) + ';\n'
2124    result += '}\n\n'
2125
2126    defined_names.append(cls.get_capi_name())
2127
2128    # static functions become global
2129    funcs = cls.get_static_funcs()
2130    if len(funcs) > 0:
2131      for func in funcs:
2132        result += func.get_capi_proto(defined_names, "", True) + ';\n'
2133      result += '\n'
2134  sys.stdout.write(result)
2135