aboutsummaryrefslogtreecommitdiff
path: root/tools/namespacer.py
blob: 966e917cf2120d95503ba029e24fa54cf4b75594 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/python

'''
Tool that generates namespace boilerplate. Given

  _mangled_name1_ = MyClass::MyClass()
  _mangled_name2_ = MyClass::~MyClass()
  _mangled_name3_ = MyClass::DoSomething(int)

the tool will generate

  MyClass = {
    'MyClass':     _mangled_name1_,
    '~MyClass':  _mangled_name2_,
    'DoSomething': _mangled_name3_
  };

You can then do the following in JavaScript:

  MyClass.MyClass(ptr);
  MyClass['~MyClass'](ptr); // Need string here, due to |~|
  MyClass.DoSomething(ptr, 17);

Note that you need to send the |this| pointer yourself. TODO:
a more OO boilerplate on top of that.
'''

import os, sys, json

data = open(sys.argv[1], 'r').readlines()

space = {}

for line in data:
  line = line.rstrip()

  realname, signature = line.split(' = ')
  signature = signature.replace(') const', ')')
  signature = signature[:-1].split('(')
  func, params = signature[0], '('.join(signature[1:])

  if ' ' in func:
    i = func.index(' ')
    ret = func[:i]
    if '<' not in ret and '[' not in ret and '(' not in ret:
      func = func[i+1:]

  funcparts = ['Namespace'] + func.split('::')

  currspace = space
  for part in funcparts[:-1]:
    currspace = currspace.setdefault(part, {})
  currspace.setdefault(funcparts[-1], []).append((realname,params));

def clean(currspace):
  if type(currspace) is list:
    if len(currspace) == 1:
      return currspace[0][0]
    else:
      ret = {}
      for item in currspace:
        i = str(len(ret)/2)
        ret[i] = item[0]
        ret[i + '_params'] = item[1]
      return ret
  else:
    for key in currspace.keys():
      currspace[key] = clean(currspace[key])
    return currspace

space = clean(space)

def finalize(line):
  try:
    key, val = line.split(': ')
    assert val != '}' and '_params"' not in key
    return key + ': ' + val.replace('"', '')
  except:
    return line

print '\n'.join(map(finalize, json.dumps(space, sort_keys=True, indent=2).split('\n')))