-
Notifications
You must be signed in to change notification settings - Fork 10
/
generator.py
414 lines (334 loc) · 12.8 KB
/
generator.py
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import os
import sys
import shutil
__author__ = 'epinault'
from qi import Session
import pprint
from urllib2 import urlopen
import bs4 as BeautifulSoup
TEMPLATE_VOID = """
/**
* %(method_desc)s
* %(method_params)s
*/
public %(outtype)s %(methodName)s(%(args)s) throws CallError, InterruptedException{
call("%(method)s"%(extraparams)s).get();
}"""
TEMPLATE_RETURN = """
/**
* %(method_desc)s
* %(method_params)s
*/
public %(outtype)s %(methodName)s(%(args)s) throws CallError, InterruptedException {
return (%(outtype)s)call("%(method)s"%(extraparams)s).get();
}"""
TEMPLATE_CLASS = """/**
* Copyright (c) 2015 Aldebaran Robotics. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the COPYING file.
* Created by epinault and tcruz
*/
package com.aldebaran.qi.helper.proxies;
import com.aldebaran.qi.*;
import com.aldebaran.qi.helper.*;
import java.util.List;
import java.util.Map;
import java.util.List;
/**
* %(module_desc)s
* @see <a href="%(module_link_overview)s">NAOqi APIs for %(module_name)s </a>
* NAOqi V%(nVersion)s
*/
public class %(module_name)s extends %(module_parent)s {
private Async%(module_name)s asyncProxy;
public %(module_name)s(Session session) throws Exception{
super(session);
asyncProxy = new Async%(module_name)s();
asyncProxy.setService(getService());
}
/**
* Get the async version of this proxy
*
* @return a Async%(module_name)s object
*/
public Async%(module_name)s async() {
return asyncProxy;
}
%(content)s
public class Async%(module_name)s extends %(module_parent)s {
protected Async%(module_name)s(){
super();
}
%(content_async)s
}
}
"""
TEMPLATE_VOID_ASYNC = """
/**
* %(method_desc)s
* %(method_params)s
* @return The Future
*/
public Future<Void> %(methodName)s(%(args)s) throws CallError, InterruptedException{
return call("%(method)s"%(extraparams)s);
}"""
TEMPLATE_RETURN_ASYNC = """
/**
* %(method_desc)s
* %(method_params)s
*/
public Future<%(outtype)s> %(methodName)s(%(args)s) throws CallError, InterruptedException {
return call("%(method)s"%(extraparams)s);
}"""
BLACKLIST_METHODS = set("registerEvent, unregisterEvent, metaObject, terminate, property, setProperty, registerEventWithSignature, enableStats, enableTrace, pCall, stats, properties, subscriber".split(", "))
BLACKLIST_MODULES = set("ALTabletService, ".split(", "))
OPENERS, CLOSERS = '([{<', ')]}>'
EXPECTED_CLOSER = dict(zip(OPENERS, CLOSERS))
linksDicOverview = {}
linksDicApi = {}
version = ""
URL_2_3 = "http://doc.aldebaran.lan/doc/release-2.3/aldeb-doc/naoqi/"
URL_2_1 = "http://doc.aldebaran.com/2-1/naoqi/"
URL_OTHER = "http://doc.aldebaran.lan/doc/master/aldeb-doc/naoqi/"
docURLRoot = ""
naoqiVersion = ""
def get_subtrees(closer, symbols):
trees = []
while symbols:
head = symbols[0]
tail = symbols[1:]
if head in OPENERS:
subtrees, symbols = get_subtrees(EXPECTED_CLOSER[head], tail)
if head != '<': # Fuck <, man.
trees.append((head, subtrees))
elif head in CLOSERS:
assert head == closer, "Unexpected closer, got %s, expected %s" % (head, closer)
return trees, tail
else:
trees.append(head)
symbols = tail
return trees, ''
def totree(symbols):
trees, symbols = get_subtrees('', symbols)
return trees
##############################################################
# Tests
##############################################################
BASIC_TYPE = {
'[': 'List<',
'{': 'Map<',
"i": "Integer",
"I": "Integer",
"c": "Character",
"s": "String",
"v": "void",
"o": "AnyObject",
"X": "Object",
"b": "Boolean",
"m": "Object",
"f": "Float",
"L":"Long",
"l":"Long",
"d":"Double"
}
COMPLEX_TYPE = ()
def parseTree(trees, names, level):
result = ""
for i, entry in enumerate(trees):
if isinstance(entry, tuple):
kind, subtrees = entry
if kind == "(":
result += "Tuple"+str(len(subtrees))+"<"
else:
result += BASIC_TYPE[kind]
# typesTranslated.append(NAMES[kind])
result += parseTree(subtrees, None, level + 1)
if level == 0:
result += "> "+names[i]+", "
else:
result += ">, "
else:
if level == 0:
result += BASIC_TYPE[entry] + " "+names[i]+", "
else:
result += BASIC_TYPE[entry] + ", "
# typesTranslated.append(NAMES[entry])
result = result [0:-2]
return result
def translate(typecode):
tree = totree(typecode)
return parseTree(tree, None, 1)
def camelcasify(s):
words = s.split()
return words[0] + "".join([w.capitalize() for w in words[1:]])
def translateArgument(signatures, paraminfo):
anonvari = [0]
def getvarname(d):
if d and d['name'] and d['name'] != "string" :
return d['name']
else:
anonvari[0] += 1
return "param%i" % anonvari[0]
names = map(getvarname, paraminfo)
names = map(cleanJavaName, names)
names = map(camelcasify, names)
tree = totree(signatures[1:-1])
for i, t in enumerate(tree):
if i+1 > len(names):
names.append(getvarname(None))
if len(tree) != len(names):
names = names[0:len(tree)]
print names
return parseTree(tree,names, 0), ", ".join(names)
# def translate2(typecode):
# return typemap2.get(typecode, "Object")
#
# def translateType(stype):
# print map(translate2, stype)
def cleanJavaName(name):
if name == "package":
return "package1"
# if name == "int":
# return "integer"
# if name == "string":
# return "string1"
# if name == "service":
# return "serviceName"
return name
def translateFunc(methodData, isAsync):
# return " " + translate(method["returnSignature"]) + " " + method["name"] + "(" + translateArgument(method["parametersSignature"], method["parameters"]) + ")"
outtype = translate(methodData["returnSignature"])
method = methodData["name"]
method_desc = methodData["description"]
methodName = cleanJavaName(method)
args, extraparams = translateArgument(methodData["parametersSignature"], methodData["parameters"])
if extraparams :
extraparams = ", "+extraparams
method_params = ""
for param in methodData["parameters"]:
method_params += "\n * @param "+param["name"]+" "+param["description"]
if outtype == "void":
if isAsync:
return TEMPLATE_VOID_ASYNC % locals()
else:
return TEMPLATE_VOID % locals()
else:
if methodData["returnDescription"]:
method_params += "\n * @return "+methodData["returnDescription"]
if isAsync:
return TEMPLATE_RETURN_ASYNC % locals()
else:
return TEMPLATE_RETURN % locals()
def native(method):
return " " + method["returnSignature"] + " " + method["name"] + method["parametersSignature"]
# return " " + method["returnSignature"] + " " + method["name"] + "(" + method["parametersSignature"] + ")"
def _iter_services(address):
session = Session()
session.connect('tcp://'+address+':9559')
print "Number of services : "+str(len(session.services()))
for servicesDesc in session.services():
module_name = servicesDesc["name"]
if not module_name.startswith('_') and module_name not in BLACKLIST_MODULES:
yield module_name, session.service(module_name)
def generate_java(address):
directory = "src/main/java/com/aldebaran/qi/helper/proxies"
global naoqiVersion
if os.path.exists(directory):
shutil.rmtree(directory)
os.makedirs(directory)
for module_name, service in _iter_services(address):
if module_name in linksDicOverview and module_name not in BLACKLIST_MODULES:
nVersion = naoqiVersion[:3]+".x"
content = ""
content_async=""
meta = service.metaObject()
module_desc = meta["description"]
module_link_overview = docURLRoot+linksDicOverview[module_name]
# module_link_api = docURLRoot+linksDicApi[module_name]
methods = meta["methods"]
# print "Service %s" % (module_name)
# print methods.values()
print module_name+" -- Number of methods : "+str(len(methods))
for method in methods.values() :
# print native(method)
if method["name"] not in BLACKLIST_METHODS and not method["name"].startswith("_"):
if module_name == "ALMemory":
module_parent = "ALMemoryHelper"
else:
module_parent = "ALProxy"
content += translateFunc(method, False)+"\n"
content_async += translateFunc(method, True)+"\n"
with open(directory+"/"+module_name + ".java", "w") as outfile:
module_link_overview = module_link_overview.encode('utf-8')
outfile.write(TEMPLATE_CLASS % locals())
outfile.close()
# break
def find_errors():
for module_name, service in _iter_services():
meta = service.metaObject()
undocumented = []
complained = [False]
def complain():
if not complained[0]:
complained[0] = True
print
print module_name + ":"
for methodData in meta["methods"].values():
methodname = methodData["name"]
signatures = methodData["parametersSignature"].strip("()")
paramDescs = methodData["parameters"]
paramNames = [d['name'] for d in methodData["parameters"]]
if len(signatures) < len(paramNames):
complain()
print " PROBLEM IN %s.%s(%s)" %(module_name, methodname, signatures)
print " expected %i args, doc gives %i: %s" % (len(signatures), len(paramNames), ", ".join(paramNames))
#pprint.pprint(paramDescs)
#print " signature", signatures
#return
elif (len(signatures) > len(paramNames)) and (methodname not in BLACKLIST_METHODS) and (not methodname.startswith('_'))\
and ("[" not in signatures) and ("{" not in signatures):
undocumented.append(methodname + methodData["parametersSignature"])
if undocumented:
complain()
print " %i functions with undocumented params: %s" % (len(undocumented), ", ".join(undocumented))
EXAMPLE = {'description': 'Set if the input concepts are copied', 'parameters': [
{'name': 'copyInput', 'description': 'False to optimize'}], 'parametersSignature': '(({I(Issss[(ss)<MetaMethodParameter,name,description>]s)<MetaMethod,uid,returnSignature,name,parametersSignature,description,parameters,returnDescription>}{I(Iss)<MetaSignal,uid,name,signature>}{I(Iss)<MetaProperty,uid,name,signature>}s)<MetaObject,methods,signals,properties,description>)', 'name': '_copyInputConcepts', 'returnDescription': '', 'returnSignature': 'v', 'uid': 238L}
# {'name': '', 'description': 'False to optimize'}], 'parametersSignature': '(i[f][f][f][f][f][f][f][f])', 'name': '_copyInputConcepts', 'returnDescription': '', 'returnSignature': 'v', 'uid': 238L}
def test():
print "================================"
pprint.pprint(EXAMPLE)
print "================================"
print translateFunc(EXAMPLE)
print "================================"
def fillLinksMap(address):
global docURLRoot
global naoqiVersion
session = Session()
session.connect('tcp://'+address+':9559')
system = session.service("ALSystem")
naoqiVersion = system.systemVersion()
if naoqiVersion[:3] == "2.3":
docURLRoot = URL_2_3
elif naoqiVersion[:3] == "2.1" :
docURLRoot = URL_2_1
else:
docURLRoot = URL_OTHER
url = docURLRoot+"index.html"
print "Parse : "+url
html = urlopen(url).read()
soup = BeautifulSoup.BeautifulSoup(html)
elements = soup.findAll("li")
for element in elements:
key = element.text.split(' ', 1)[0]
links = element.findAll("a")
if len(links) > 1:
# linksDicApi[key] = links[0]["href"]
linksDicOverview[key] = links[1]["href"]
if __name__ == "__main__":
if len(sys.argv) < 2:
print "ip or name.local of the robot needed"
else:
fillLinksMap(sys.argv[1])
generate_java(sys.argv[1])
# test()
# find_errors()