Debian Codegraph @

internal/gen_tests/gen_tests.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 '''Finds yaml tests, converts them to Go tests.'''
4 from __future__ import print_function
5
6 import sys
7 import os
8 import os.path
9 import re
10 import time
11 import ast
12 from re import sub, match, split, DOTALL
13 import argparse
14 import codecs
15 import logging
16 import process_polyglot
17 import parse_polyglot
18 from process_polyglot import Unhandled, Skip, FatalSkip, SkippedTest
19 from mako.template import Template
20
21 try:
22 from cStringIO import StringIO
23 except ImportError:
24 from io import StringIO
25 from collections import namedtuple
26
27 parse_polyglot.printDebug = False
28 logger = logging.getLogger("convert_tests")
29 r = None
30
31
32 TEST_EXCLUSIONS = [
33 # python only tests
34 # 'regression/1133',
35 # 'regression/767',
36 # 'regression/1005',
37 'regression/',
38 'limits', # pending fix in issue #4965
39 # double run
40 'changefeeds/squash',
41 'arity',
42 '.rb.yaml',
43 ]
44
45 GO_KEYWORDS = [
46 'break', 'case', 'chan', 'const', 'continue', 'default', 'defer', 'else',
47 'fallthrough', 'for', 'func', 'go', 'goto', 'if', 'import', 'interface',
48 'map', 'package', 'range', 'return', 'select', 'struct', 'switch', 'type',
49 'var'
50 ]
51
52 def main():
53 logging.basicConfig(format="[%(name)s] %(message)s", level=logging.INFO)
54 start = time.clock()
55 args = parse_args()
56 if args.debug:
57 logger.setLevel(logging.DEBUG)
58 logging.getLogger('process_polyglot').setLevel(logging.DEBUG)
59 elif args.info:
60 logger.setLevel(logging.INFO)
61 logging.getLogger('process_polyglot').setLevel(logging.INFO)
62 else:
63 logger.root.setLevel(logging.WARNING)
64 if args.e:
65 evaluate_snippet(args.e)
66 exit(0)
67 global r
68 r = import_python_driver(args.python_driver_dir)
69 renderer = Renderer(
70 invoking_filenames=[
71 __file__,
72 process_polyglot.__file__,
73 ])
74 for testfile in process_polyglot.all_yaml_tests(
75 args.test_dir,
76 TEST_EXCLUSIONS):
77 logger.info("Working on %s", testfile)
78 TestFile(
79 test_dir=args.test_dir,
80 filename=testfile,
81 test_output_dir=args.test_output_dir,
82 renderer=renderer,
83 ).load().render()
84 logger.info("Finished in %s seconds", time.clock() - start)
85
86
87 def parse_args():
88 '''Parse command line arguments'''
89 parser = argparse.ArgumentParser(description=__doc__)
90 parser.add_argument(
91 "--test-dir",
92 help="Directory where yaml tests are",
93 default=""
94 )
95 parser.add_argument(
96 "--test-output-dir",
97 help="Directory to render tests to",
98 default=".",
99 )
100 parser.add_argument(
101 "--python-driver-dir",
102 help="Where the built python driver is located",
103 default=""
104 )
105 parser.add_argument(
106 "--test-file",
107 help="Only convert the specified yaml file",
108 )
109 parser.add_argument(
110 '--debug',
111 help="Print debug output",
112 dest='debug',
113 action='store_true')
114 parser.set_defaults(debug=False)
115 parser.add_argument(
116 '--info',
117 help="Print info level output",
118 dest='info',
119 action='store_true')
120 parser.set_defaults(info=False)
121 parser.add_argument(
122 '-e',
123 help="Convert an inline python reql to go reql snippet",
124 )
125 return parser.parse_args()
126
127
128 def import_python_driver(py_driver_dir):
129 '''Imports the test driver header'''
130 stashed_path = sys.path
131 sys.path.insert(0, os.path.realpath(py_driver_dir))
132 import rethinkdb as r
133 sys.path = stashed_path
134 return r
135
136 GoQuery = namedtuple(
137 'GoQuery',
138 ('is_value',
139 'line',
140 'expected_type',
141 'expected_line',
142 'testfile',
143 'line_num',
144 'runopts')
145 )
146 GoDef = namedtuple(
147 'GoDef',
148 ('line',
149 'varname',
150 'vartype',
151 'value',
152 'run_if_query',
153 'testfile',
154 'line_num',
155 'runopts')
156 )
157 Version = namedtuple("Version", "original go")
158
159 GO_DECL = re.compile(r'var (?P<var>\w+) (?P<type>.+) = (?P<value>.*)')
160
161
162 def evaluate_snippet(snippet):
163 '''Just converts a single expression snippet into java'''
164 try:
165 parsed = ast.parse(snippet, mode='eval').body
166 except Exception as e:
167 return print("Error:", e)
168 try:
169 print(ReQLVisitor(smart_bracket=True).convert(parsed))
170 except Exception as e:
171 return print("Error:", e)
172
173
174 class TestFile(object):
175 '''Represents a single test file'''
176
177 def __init__(self, test_dir, filename, test_output_dir, renderer):
178 self.filename = filename
179 self.full_path = os.path.join(test_dir, filename)
180 self.module_name = filename.split('.')[0].replace('/', '_')
181 self.test_output_dir = test_output_dir
182 self.reql_vars = {'r'}
183 self.renderer = renderer
184
185 def load(self):
186 '''Load the test file, yaml parse it, extract file-level metadata'''
187 with open(self.full_path, encoding='utf-8') as f:
188 parsed_yaml = parse_polyglot.parseYAML(f)
189 self.description = parsed_yaml.get('desc', 'No description')
190 self.table_var_names = self.get_varnames(parsed_yaml)
191 self.reql_vars.update(self.table_var_names)
192 self.raw_test_data = parsed_yaml['tests']
193 self.test_generator = process_polyglot.tests_and_defs(
194 self.filename,
195 self.raw_test_data,
196 context=process_polyglot.create_context(r, self.table_var_names),
197 custom_field='go',
198 )
199 return self
200
201 def get_varnames(self, yaml_file):
202 '''Extract table variable names from yaml variable
203 They can be specified just space separated, or comma separated'''
204 raw_var_names = yaml_file.get('table_variable_name', '')
205 if not raw_var_names:
206 return set()
207 return set(re.split(r'[, ]+', raw_var_names))
208
209 def render(self):
210 '''Renders the converted tests to a runnable test file'''
211 defs_and_test = ast_to_go(self.test_generator, self.reql_vars)
212 self.renderer.source_files = [self.full_path]
213 self.renderer.render(
214 'template.go',
215 output_dir=self.test_output_dir,
216 output_name='reql_' + self.module_name + '_test.go',
217 dependencies=[self.full_path],
218 defs_and_test=defs_and_test,
219 table_var_names=list(sorted(self.table_var_names)),
220 module_name=camel(self.module_name),
221 GoQuery=GoQuery,
222 GoDef=GoDef,
223 description=self.description,
224 )
225
226
227 def py_to_go_type(py_type):
228 '''Converts python types to their Go equivalents'''
229 if py_type is None:
230 return None
231 elif isinstance(py_type, str):
232 # This can be called on something already converted
233 return py_type
234 elif py_type.__name__ == 'function':
235 return 'func()'
236 elif (py_type.__module__ == 'datetime' and
237 py_type.__name__ == 'datetime'):
238 return 'time.Time'
239 elif py_type.__module__ == 'builtins':
240 if py_type.__name__.endswith('Error'):
241 return 'error'
242
243 return {
244 bool: 'bool',
245 bytes: '[]byte',
246 int: 'int',
247 float: 'float64',
248 str: 'string',
249 dict: 'map[interface{}]interface{}',
250 list: '[]interface{}',
251 object: 'map[interface{}]interface{}',
252 type(None): 'interface{}',
253 }[py_type]
254 elif py_type.__module__ == 'rethinkdb.ast':
255 return "r.Term"
256 # Anomalous non-rule based capitalization in the python driver
257 # return {
258 # }.get(py_type.__name__, py_type.__name__)
259 elif py_type.__module__ == 'rethinkdb.errors':
260 return py_type.__name__
261 elif py_type.__module__ == '?test?':
262 return {
263 'int_cmp': 'int',
264 'float_cmp': 'float64',
265 'err_regex': 'Err',
266 'partial': 'compare.Expected',
267 'bag': 'compare.Expected',
268 'uuid': 'compare.Regex', # clashes with ast.Uuid
269 }.get(py_type.__name__, camel(py_type.__name__))
270 elif py_type.__module__ == 'rethinkdb.query':
271 # All of the constants like minval maxval etc are defined in
272 # query.py, but no type name is provided to `type`, so we have
273 # to pull it out of a class variable
274 return camel(py_type.st)
275 else:
276 raise Unhandled(
277 "Don't know how to convert python type {}.{} to Go"
278 .format(py_type.__module__, py_type.__name__))
279
280
281 def def_to_go(item, reql_vars):
282 if is_reql(item.term.type):
283 reql_vars.add(item.varname)
284 try:
285 if is_reql(item.term.type):
286 visitor = ReQLVisitor
287 else:
288 visitor = GoVisitor
289 go_line = visitor(reql_vars,
290 type_=item.term.type,
291 is_def=True,
292 ).convert(item.term.ast)
293 except Skip as skip:
294 return SkippedTest(line=item.term.line, reason=str(skip))
295 go_decl = GO_DECL.match(go_line).groupdict()
296 return GoDef(
297 line=Version(
298 original=item.term.line,
299 go=go_line,
300 ),
301 varname=go_decl['var'],
302 vartype=go_decl['type'],
303 value=go_decl['value'],
304 run_if_query=item.run_if_query,
305 testfile=item.testfile,
306 line_num=item.line_num,
307 runopts=convert_runopts(reql_vars, go_decl['type'], item.runopts)
308 )
309
310
311 def query_to_go(item, reql_vars):
312 if item.runopts is not None:
313 converted_runopts = convert_runopts(
314 reql_vars, item.query.type, item.runopts)
315 else:
316 converted_runopts = item.runopts
317 if converted_runopts is None:
318 converted_runopts = {}
319 converted_runopts['GeometryFormat'] = '\"raw\"'
320 if 'GroupFormat' not in converted_runopts:
321 converted_runopts['GroupFormat'] = '\"map\"'
322 try:
323 is_value = False
324 if not item.query.type.__module__.startswith("rethinkdb.") or (not item.query.type.__module__.startswith("rethinkdb.") and item.query.type.__name__.endswith("Error")):
325 is_value = True
326 go_line = ReQLVisitor(
327 reql_vars, type_=item.query.type).convert(item.query.ast)
328 if is_reql(item.expected.type):
329 visitor = ReQLVisitor
330 else:
331 visitor = GoVisitor
332 go_expected_line = visitor(
333 reql_vars, type_=item.expected.type)\
334 .convert(item.expected.ast)
335 except Skip as skip:
336 return SkippedTest(line=item.query.line, reason=str(skip))
337 return GoQuery(
338 is_value=is_value,
339 line=Version(
340 original=item.query.line,
341 go=go_line,
342 ),
343 expected_type=py_to_go_type(item.expected.type),
344 expected_line=Version(
345 original=item.expected.line,
346 go=go_expected_line,
347 ),
348 testfile=item.testfile,
349 line_num=item.line_num,
350 runopts=converted_runopts,
351 )
352
353
354 def ast_to_go(sequence, reql_vars):
355 '''Converts the the parsed test data to go source lines using the
356 visitor classes'''
357 reql_vars = set(reql_vars)
358 for item in sequence:
359 if type(item) == process_polyglot.Def:
360 yield def_to_go(item, reql_vars)
361 elif type(item) == process_polyglot.CustomDef:
362 yield GoDef(line=Version(item.line, item.line),
363 testfile=item.testfile,
364 line_num=item.line_num)
365 elif type(item) == process_polyglot.Query:
366 yield query_to_go(item, reql_vars)
367 elif type(item) == SkippedTest:
368 yield item
369 else:
370 assert False, "shouldn't happen, item was {}".format(item)
371
372
373 def is_reql(t):
374 '''Determines if a type is a reql term'''
375 # Other options for module: builtins, ?test?, datetime
376 if not hasattr(t, '__module__'):
377 return True
378
379 return t.__module__ == 'rethinkdb.ast'
380
381
382 def escape_string(s, out):
383 out.write('"')
384 for codepoint in s:
385 rpr = repr(codepoint)[1:-1]
386 if rpr.startswith('\\x'):
387 rpr = '\\u00' + rpr[2:]
388 elif rpr == '"':
389 rpr = r'\"'
390 out.write(rpr)
391 out.write('"')
392
393
394 def attr_matches(path, node):
395 '''Helper function. Several places need to know if they are an
396 attribute of some root object'''
397 root, name = path.split('.')
398 ret = is_name(root, node.value) and node.attr == name
399 return ret
400
401
402 def is_name(name, node):
403 '''Determine if the current attribute node is a Name with the
404 given name'''
405 return type(node) == ast.Name and node.id == name
406
407
408 def convert_runopts(reql_vars, type_, runopts):
409 if runopts is None:
410 return None
411 return {
412 camel(key): GoVisitor(
413 reql_vars, type_=type_).convert(val)
414 for key, val in runopts.items()
415 }
416
417
418 class GoVisitor(ast.NodeVisitor):
419 '''Converts python ast nodes into a Go string'''
420
421 def __init__(self,
422 reql_vars=frozenset("r"),
423 out=None,
424 type_=None,
425 is_def=False,
426 smart_bracket=False,
427 ):
428 self.out = StringIO() if out is None else out
429 self.reql_vars = reql_vars
430 self.type = py_to_go_type(type_)
431 self._type = type_
432 self.is_def = is_def
433 self.smart_bracket = smart_bracket
434 super(GoVisitor, self).__init__()
435 self.write = self.out.write
436
437 def skip(self, message, *args, **kwargs):
438 cls = Skip
439 is_fatal = kwargs.pop('fatal', False)
440 if self.is_def or is_fatal:
441 cls = FatalSkip
442 raise cls(message, *args, **kwargs)
443
444 def convert(self, node):
445 '''Convert a text line to another text line'''
446 self.visit(node)
447 return self.out.getvalue()
448
449 def join(self, sep, items):
450 first = True
451 for item in items:
452 if first:
453 first = False
454 else:
455 self.write(sep)
456 self.visit(item)
457
458 def to_str(self, s):
459 escape_string(s, self.out)
460
461 def cast_null(self, arg):
462 if (type(arg) == ast.Name and arg.id == 'null') or \
463 (type(arg) == ast.NameConstant and arg.value == None):
464 self.write("nil")
465 else:
466 self.visit(arg)
467
468 def to_args(self, args, func='', optargs=[]):
469 optargs_first = False
470
471 self.write("(")
472 if args:
473 self.cast_null(args[0])
474 for arg in args[1:]:
475 self.write(', ')
476 self.cast_null(arg)
477 self.write(")")
478
479 if optargs:
480 self.to_args_optargs(func, optargs)
481
482 def to_args_optargs(self, func='', optargs=[]):
483 optarg_aliases = {
484 'JsOpts': 'JSOpts',
485 'HttpOpts': 'HTTPOpts',
486 'Iso8601Opts': 'ISO8601Opts',
487 'IndexCreateFuncOpts': 'IndexCreateOpts'
488 }
489 optarg_field_aliases = {
490 'nonvoting_replica_tags': 'NonVotingReplicaTags',
491 }
492
493 if not func:
494 raise Unhandled("Missing function name")
495
496 optarg_type = camel(func) + 'Opts'
497 optarg_type = optarg_aliases.get(optarg_type, optarg_type)
498 optarg_type = 'r.' + optarg_type
499
500 self.write('.OptArgs(')
501 self.write(optarg_type)
502 self.write('{')
503 for optarg in optargs:
504 # Hack to skip tests that check for unknown opt args,
505 # this is not possible in Go due to static types
506 if optarg.arg == 'return_vals':
507 self.skip("test not required since optargs are statically typed")
508 return
509 if optarg.arg == 'foo':
510 self.skip("test not required since optargs are statically typed")
511 return
512 if type(optarg.value) == ast.Name and optarg.value.id == 'null':
513 self.skip("test not required since go does not support null optargs")
514 return
515
516
517 field_name = optarg_field_aliases.get(optarg.arg, camel(optarg.arg))
518
519 self.write(field_name)
520 self.write(": ")
521 self.cast_null(optarg.value)
522 self.write(', ')
523 self.write('})')
524
525 def generic_visit(self, node):
526 logger.error("While translating: %s", ast.dump(node))
527 logger.error("Got as far as: %s", ''.join(self.out))
528 raise Unhandled("Don't know what this thing is: " + str(type(node)))
529
530 def visit_Assign(self, node):
531 if len(node.targets) != 1:
532 Unhandled("We only support assigning to one variable")
533 var = node.targets[0].id
534 self.write("var " + var + " ")
535 if is_reql(self._type):
536 self.write('r.Term')
537 else:
538 self.write(self.type)
539 self.write(" = ")
540 if is_reql(self._type):
541 ReQLVisitor(self.reql_vars,
542 out=self.out,
543 type_=self.type,
544 is_def=True,
545 ).visit(node.value)
546 elif var == 'upper_limit': # Manually set value since value in test causes an error
547 self.write('2<<52 - 1')
548 elif var == 'lower_limit': # Manually set value since value in test causes an error
549 self.write('1 - 2<<52')
550 else:
551 self.visit(node.value)
552
553 def visit_Str(self, node):
554 if node.s == 'ReqlServerCompileError':
555 node.s = 'ReqlCompileError'
556 # Hack to skip irrelevant tests
557 if match(".*Expected .* argument", node.s):
558 self.skip("argument checks not supported")
559 if match(".*argument .* must", node.s):
560 self.skip("argument checks not supported")
561 return
562 if node.s == 'Object keys must be strings.*':
563 self.skip('the Go driver automatically converts object keys to strings')
564 return
565 if node.s.startswith('\'module\' object has no attribute '):
566 self.skip('test not required since terms are statically typed')
567 return
568 self.to_str(node.s)
569
570 def visit_Bytes(self, node, skip_prefix=False, skip_suffix=False):
571 if not skip_prefix:
572 self.write("[]byte{")
573 for i, byte in enumerate(node.s):
574 self.write(str(byte))
575 if i < len(node.s)-1:
576 self.write(",")
577 if not skip_suffix:
578 self.write("}")
579 else:
580 self.write(", ")
581
582 def visit_Name(self, node):
583 name = node.id
584 if name == 'frozenset':
585 self.skip("can't convert frozensets to GroupedData yet")
586 if name in GO_KEYWORDS:
587 name += '_'
588 self.write({
589 'True': 'true',
590 'False': 'false',
591 'None': 'nil',
592 'nil': 'nil',
593 'null': 'nil',
594 'float': 'float64',
595 'datetime': 'Ast', # Use helper method instead
596 'len': 'maybeLen',
597 'AnythingIsFine': 'compare.AnythingIsFine',
598 'bag': 'compare.UnorderedMatch',
599 'partial': 'compare.PartialMatch',
600 'uuid': 'compare.IsUUID',
601 'regex': 'compare.MatchesRegexp',
602 }.get(name, name))
603
604 def visit_arg(self, node):
605 self.write(node.arg)
606 self.write(" ")
607 if is_reql(self._type):
608 self.write("r.Term")
609 else:
610 self.write("interface{}")
611
612 def visit_NameConstant(self, node):
613 if node.value is None:
614 self.write("nil")
615 elif node.value is True:
616 self.write("true")
617 elif node.value is False:
618 self.write("false")
619 else:
620 raise Unhandled(
621 "Don't know NameConstant with value %s" % node.value)
622
623 def visit_Attribute(self, node, emit_parens=True):
624 skip_parent = False
625 if attr_matches("r.ast", node):
626 # The java driver doesn't have that namespace, so we skip
627 # the `r.` prefix and create an ast class member in the
628 # test file. So stuff like `r.ast.rqlTzinfo(...)` converts
629 # to `ast.rqlTzinfo(...)`
630 skip_parent = True
631
632
633 if not skip_parent:
634 self.visit(node.value)
635 self.write(".")
636
637 attr = ReQLVisitor.convertTermName(node.attr)
638 self.write(attr)
639
640 def visit_Num(self, node):
641 self.write(repr(node.n))
642 if not isinstance(node.n, float):
643 if node.n > 9223372036854775807 or node.n < -9223372036854775808:
644 self.write(".0")
645
646 def visit_Index(self, node):
647 self.visit(node.value)
648
649 def visit_Call(self, node):
650 func = ''
651 if type(node.func) == ast.Attribute and node.func.attr == 'encode':
652 self.skip("Go tests do not currently support character encoding")
653 return
654 if type(node.func) == ast.Attribute and node.func.attr == 'error':
655 # This weird special case is because sometimes the tests
656 # use r.error and sometimes they use r.error(). The java
657 # driver only supports r.error(). Since we're coming in
658 # from a call here, we have to prevent visit_Attribute
659 # from emitting the parents on an r.error for us.
660 self.visit_Attribute(node.func, emit_parens=False)
661 elif type(node.func) == ast.Name and node.func.id == 'err':
662 # Throw away third argument as it is not used by the Go tests
663 # and Go does not support function overloading
664 node.args = node.args[:2]
665 self.visit(node.func)
666 elif type(node.func) == ast.Name and node.func.id == 'err_regex':
667 # Throw away third argument as it is not used by the Go tests
668 # and Go does not support function overloading
669 node.args = node.args[:2]
670 self.visit(node.func)
671 elif type(node.func) == ast.Name and node.func.id == 'fetch':
672 if len(node.args) == 1:
673 node.args.append(ast.Num(0))
674 elif len(node.args) > 2:
675 node.args = node.args[:2]
676 self.visit(node.func)
677 else:
678 self.visit(node.func)
679
680 if type(node.func) == ast.Attribute:
681 func = node.func.attr
682 elif type(node.func) == ast.Name:
683 func = node.func.id
684
685 self.to_args(node.args, func, node.keywords)
686
687 def visit_Dict(self, node):
688 self.write("map[interface{}]interface{}{")
689 for k, v in zip(node.keys, node.values):
690 self.visit(k)
691 self.write(": ")
692 self.visit(v)
693 self.write(", ")
694 self.write("}")
695
696 def visit_List(self, node):
697 self.write("[]interface{}{")
698 self.join(", ", node.elts)
699 self.write("}")
700
701 def visit_Tuple(self, node):
702 self.visit_List(node)
703
704 def visit_Lambda(self, node):
705 self.write("func")
706 self.to_args(node.args.args)
707 self.write(" interface{} { return ")
708 self.visit(node.body)
709 self.write("}")
710
711 def visit_Subscript(self, node):
712 if node.slice is None or type(node.slice.value) != ast.Num:
713 logger.error("While doing: %s", ast.dump(node))
714 raise Unhandled("Only integers subscript can be converted."
715 " Got %s" % node.slice.value.s)
716 self.visit(node.value)
717 self.write("[")
718 self.write(str(node.slice.value.n))
719 self.write("]")
720
721 def visit_ListComp(self, node):
722 gen = node.generators[0]
723
724 start = 0
725 end = 0
726
727 if type(gen.iter) == ast.Call and gen.iter.func.id.endswith('range'):
728 # This is really a special-case hacking of [... for i in
729 # range(i)] comprehensions that are used in the polyglot
730 # tests sometimes. It won't handle translating arbitrary
731 # comprehensions to Java streams.
732
733 if len(gen.iter.args) == 1:
734 end = gen.iter.args[0].n
735 elif len(gen.iter.args) == 2:
736 start = gen.iter.args[0].n
737 end = gen.iter.args[1].n
738 else:
739 # Somebody came up with a creative new use for
740 # comprehensions in the test suite...
741 raise Unhandled("ListComp hack couldn't handle: ", ast.dump(node))
742
743 self.write("(func() []interface{} {\n")
744 self.write(" res := []interface{}{}\n")
745 self.write(" for iterator_ := %s; iterator_ < %s; iterator_++ {\n" % (start, end))
746 self.write(" "); self.visit(gen.target); self.write(" := iterator_\n")
747 self.write(" res = append(res, ")
748 self.visit(node.elt)
749 self.write(")\n")
750 self.write(" }\n")
751 self.write(" return res\n")
752 self.write("}())")
753
754 def visit_UnaryOp(self, node):
755 opMap = {
756 ast.USub: "-",
757 ast.Not: "!",
758 ast.UAdd: "+",
759 ast.Invert: "~",
760 }
761 self.write(opMap[type(node.op)])
762 self.visit(node.operand)
763
764 def visit_BinOp(self, node):
765 opMap = {
766 ast.Add: " + ",
767 ast.Sub: " - ",
768 ast.Mult: " * ",
769 ast.Div: " / ",
770 ast.Mod: " % ",
771 }
772 if self.is_string_mul(node):
773 return
774 if self.is_array_concat(node):
775 return
776 if self.is_byte_array_add(node):
777 return
778
779 t = type(node.op)
780 if t in opMap.keys():
781 self.visit(node.left)
782 self.write(opMap[t])
783 self.visit(node.right)
784 elif t == ast.Pow:
785 if type(node.left) == ast.Num and node.left.n == 2:
786 self.visit(node.left)
787 self.write(" << ")
788 self.visit(node.right)
789 else:
790 raise Unhandled("Can't do exponent with non 2 base")
791
792 def is_byte_array_add(self, node):
793 '''Some places we do stuff like b'foo' + b'bar' and byte
794 arrays don't like that much'''
795 if (type(node.left) == ast.Bytes and
796 type(node.right) == ast.Bytes and
797 type(node.op) == ast.Add):
798 self.visit_Bytes(node.left, skip_suffix=True)
799 self.visit_Bytes(node.right, skip_prefix=True)
800 return True
801 else:
802 return False
803
804 def is_string_mul(self, node):
805 if ((type(node.left) == ast.Str and type(node.right) == ast.Num) and type(node.op) == ast.Mult):
806 self.write("\"")
807 self.write(node.left.s * node.right.n)
808 self.write("\"")
809 return True
810 elif ((type(node.left) == ast.Num and type(node.right) == ast.Str) and type(node.op) == ast.Mult):
811 self.write("\"")
812 self.write(node.left.n * node.right.s)
813 self.write("\"")
814 return True
815 else:
816 return False
817
818 def is_array_concat(self, node):
819 if ((type(node.left) == ast.List or type(node.right) == ast.List) and type(node.op) == ast.Add):
820 self.skip("Array concatenation using + operator not currently supported")
821 return True
822 else:
823 return False
824
825
826 class ReQLVisitor(GoVisitor):
827 '''Mostly the same as the GoVisitor, but converts some
828 reql-specific stuff. This should only be invoked on an expression
829 if it's already known to return true from is_reql'''
830
831 TOPLEVEL_CONSTANTS = {
832 'error'
833 }
834
835 def visit_BinOp(self, node):
836 if self.is_string_mul(node):
837 return
838 if self.is_array_concat(node):
839 return
840 if self.is_byte_array_add(node):
841 return
842 opMap = {
843 ast.Add: "Add",
844 ast.Sub: "Sub",
845 ast.Mult: "Mul",
846 ast.Div: "Div",
847 ast.Mod: "Mod",
848 ast.BitAnd: "And",
849 ast.BitOr: "Or",
850 }
851 func = opMap[type(node.op)]
852 if self.is_not_reql(node.left):
853 self.prefix(func, node.left, node.right)
854 else:
855 self.infix(func, node.left, node.right)
856
857 def visit_Compare(self, node):
858 opMap = {
859 ast.Lt: "Lt",
860 ast.Gt: "Gt",
861 ast.GtE: "Ge",
862 ast.LtE: "Le",
863 ast.Eq: "Eq",
864 ast.NotEq: "Ne",
865 }
866 if len(node.ops) != 1:
867 # Python syntax allows chained comparisons (a < b < c) but
868 # we don't deal with that here
869 raise Unhandled("Compare hack bailed on: ", ast.dump(node))
870 left = node.left
871 right = node.comparators[0]
872 func_name = opMap[type(node.ops[0])]
873 if self.is_not_reql(node.left):
874 self.prefix(func_name, left, right)
875 else:
876 self.infix(func_name, left, right)
877
878 def prefix(self, func_name, left, right):
879 self.write("r.")
880 self.write(func_name)
881 self.write("(")
882 self.visit(left)
883 self.write(", ")
884 self.visit(right)
885 self.write(")")
886
887 def infix(self, func_name, left, right):
888 self.visit(left)
889 self.write(".")
890 self.write(func_name)
891 self.write("(")
892 self.visit(right)
893 self.write(")")
894
895 def is_not_reql(self, node):
896 if type(node) in (ast.Name, ast.NameConstant,
897 ast.Num, ast.Str, ast.Dict, ast.List):
898 return True
899 else:
900 return False
901
902 def visit_Subscript(self, node):
903 self.visit(node.value)
904 if type(node.slice) == ast.Index:
905 # Syntax like a[2] or a["b"]
906 if self.smart_bracket and type(node.slice.value) == ast.Str:
907 self.write(".Field(")
908 elif self.smart_bracket and type(node.slice.value) == ast.Num:
909 self.write(".Nth(")
910 else:
911 self.write(".AtIndex(")
912 self.visit(node.slice.value)
913 self.write(")")
914 elif type(node.slice) == ast.Slice:
915 # Syntax like a[1:2] or a[:2]
916 self.write(".Slice(")
917 lower, upper, rclosed = self.get_slice_bounds(node.slice)
918 self.write(str(lower))
919 self.write(", ")
920 self.write(str(upper))
921 if rclosed:
922 self.write(', r.SliceOpts{RightBound: "closed"}')
923 self.write(")")
924 else:
925 raise Unhandled("No translation for ExtSlice")
926
927 def get_slice_bounds(self, slc):
928 '''Used to extract bounds when using bracket slice
929 syntax. This is more complicated since Python3 parses -1 as
930 UnaryOp(op=USub, operand=Num(1)) instead of Num(-1) like
931 Python2 does'''
932 if not slc:
933 return 0, -1, True
934
935 def get_bound(bound, default):
936 if bound is None:
937 return default
938 elif type(bound) == ast.UnaryOp and type(bound.op) == ast.USub:
939 return -bound.operand.n
940 elif type(bound) == ast.Num:
941 return bound.n
942 else:
943 raise Unhandled(
944 "Not handling bound: %s" % ast.dump(bound))
945
946 right_closed = slc.upper is None
947
948 return get_bound(slc.lower, 0), get_bound(slc.upper, -1), right_closed
949
950 def convertTermName(term):
951 python_clashes = {
952 # These are underscored in the python driver to avoid
953 # keywords, but they aren't java keywords so we convert
954 # them back.
955 'or_': 'Or',
956 'and_': 'And',
957 'not_': 'Not',
958 }
959 method_aliases = {
960 'get_field': 'Field',
961 'db': 'DB',
962 'db_create': 'DBCreate',
963 'db_drop': 'DBDrop',
964 'db_list': 'DBList',
965 'uuid': 'UUID',
966 'geojson': 'GeoJSON',
967 'js': 'JS',
968 'json': 'JSON',
969 'to_json': 'ToJSON',
970 'to_json_string': 'ToJSON',
971 'minval': 'MinVal',
972 'maxval': 'MaxVal',
973 'http': 'HTTP',
974 'iso8601': 'ISO8601',
975 'to_iso8601': 'ToISO8601',
976 }
977
978 return python_clashes.get(term, method_aliases.get(term, camel(term)))
979
980 def visit_Attribute(self, node, emit_parens=True):
981 is_toplevel_constant = False
982 # if attr_matches("r.row", node):
983 # elif is_name("r", node.value) and node.attr in self.TOPLEVEL_CONSTANTS:
984 if is_name("r", node.value) and node.attr in self.TOPLEVEL_CONSTANTS:
985 # Python has r.minval, r.saturday etc. We need to emit
986 # r.minval() and r.saturday()
987 is_toplevel_constant = True
988
989 initial = ReQLVisitor.convertTermName(node.attr)
990
991 self.visit(node.value)
992 self.write(".")
993 self.write(initial)
994 if initial in GO_KEYWORDS:
995 self.write('_')
996 if emit_parens and is_toplevel_constant:
997 self.write('()')
998
999 def visit_UnaryOp(self, node):
1000 if type(node.op) == ast.Invert:
1001 self.visit(node.operand)
1002 self.write(".Not()")
1003 else:
1004 super(ReQLVisitor, self).visit_UnaryOp(node)
1005
1006 def visit_Call(self, node):
1007 if (attr_equals(node.func, "attr", "index_create") and len(node.args) == 2):
1008 node.func.attr = 'index_create_func'
1009
1010 # We call the superclass first, so if it's going to fail
1011 # because of r.row or other things it fails first, rather than
1012 # hitting the checks in this method. Since everything is
1013 # written to a stringIO object not directly to a file, if we
1014 # bail out afterwards it's still ok
1015 super_result = super(ReQLVisitor, self).visit_Call(node)
1016
1017 # r.expr(v, 1) should be skipped
1018 if (attr_equals(node.func, "attr", "expr") and len(node.args) > 1):
1019 self.skip("the go driver only accepts one parameter to expr")
1020 # r.table_create("a", "b") should be skipped
1021 if (attr_equals(node.func, "attr", "table_create") and len(node.args) > 1):
1022 self.skip("the go driver only accepts one parameter to table_create")
1023 return super_result
1024
1025 class Renderer(object):
1026 '''Manages rendering templates'''
1027
1028 def __init__(self, invoking_filenames, source_files=None):
1029 self.template_file = './template.go.tpl'
1030 self.invoking_filenames = invoking_filenames
1031 self.source_files = source_files or []
1032 self.tpl = Template(filename=self.template_file)
1033 self.template_context = {
1034 'EmptyTemplate': process_polyglot.EmptyTemplate,
1035 }
1036
1037 def render(self,
1038 template_name,
1039 output_dir,
1040 output_name=None,
1041 **kwargs):
1042 if output_name is None:
1043 output_name = template_name
1044
1045 output_path = output_dir + '/' + output_name
1046
1047 results = self.template_context.copy()
1048 results.update(kwargs)
1049 try:
1050 rendered = self.tpl.render(**results)
1051 except process_polyglot.EmptyTemplate:
1052 logger.debug(" Empty template: %s", output_path)
1053 return
1054 with codecs.open(output_path, "w", "utf-8") as outfile:
1055 logger.info("Rendering %s", output_path)
1056 outfile.write(self.autogenerated_header(
1057 self.template_file,
1058 output_path,
1059 self.invoking_filenames,
1060 ))
1061 outfile.write(rendered)
1062
1063 def autogenerated_header(self, template_path, output_path, filename):
1064 rel_tpl = os.path.relpath(template_path, start=output_path)
1065 filenames = ' and '.join(os.path.basename(f)
1066 for f in self.invoking_filenames)
1067 return ('// Code generated by {}.\n'
1068 '// Do not edit this file directly.\n'
1069 '// The template for this file is located at:\n'
1070 '// {}\n').format(filenames, rel_tpl)
1071
1072 def camel(varname):
1073 'CamelCase'
1074 if re.match(r'[A-Z][A-Z0-9_]*$|[a-z][a-z0-9_]*$', varname):
1075 # if snake-case (upper or lower) camelize it
1076 suffix = "_" if varname.endswith('_') else ""
1077 return ''.join(x.title() for x in varname.split('_')) + suffix
1078 else:
1079 # if already mixed case, just capitalize the first letter
1080 return varname[0].upper() + varname[1:]
1081
1082
1083 def dromedary(varname):
1084 'dromedaryCase'
1085 if re.match(r'[A-Z][A-Z0-9_]*$|[a-z][a-z0-9_]*$', varname):
1086 chunks = varname.split('_')
1087 suffix = "_" if varname.endswith('_') else ""
1088 return (chunks[0].lower() +
1089 ''.join(x.title() for x in chunks[1:]) +
1090 suffix)
1091 else:
1092 return varname[0].lower() + varname[1:]
1093
1094 def attr_equals(node, attr, value):
1095 '''Helper for digging into ast nodes'''
1096 return hasattr(node, attr) and getattr(node, attr) == value
1097
1098 if __name__ == '__main__':
1099 main()