def as_expression(self, target=None): _index = local('_index', 'Int') name = self.temp_name(target or self.default) z = local(name, pseudo_type=['List', self.args[-1].pseudo_type[2]]) z_arg = local('_value', z.pseudo_type[1]) return [ assignment( z, Node('_go_make_slice', slice_type=z.pseudo_type, length=call('len', [self.args[0]], 'Int'))), Node( 'for_statement', sequences=Node('for_sequence_with_index', sequence=self.args[0]), iterators=Node( 'for_iterator_with_index', index=_index, iterator=self.args[1].params[0] if self.args[1].type == 'anonymous_function' else z_arg), block=self.args[1].block[:-1] + [ assignment( Node('index', sequence=z, index=_index, pseudo_type=z.pseudo_type[1]), self.args[1].block[-1].value) ] if self.args[1].type == 'anonymous_function' else assignment( Node('index', sequence=z, index=_index, pseudo_type=z.pseudo_type[1]), call(self.args[1], z_arg, z.pseudo_type[1]))), z ], None
def as_expression(self, target=None): _index = local('_index', 'Int') name = self.temp_name(target or self.default) z = local(name, pseudo_type=self.args[0].pseudo_type) if self.args[1].type == 'anonymous_function': block_test = self.args[1].block[-1].value initial = self.args[1].block[:-1] z_arg = self.args[1].params[0] else: z_arg = local('_value', z.pseudo_type[1]) block_test = call(self.args[1], z_arg, 'Boolean') initial = [] return [ Node('_go_declaration', decl=name, decl_type=z.pseudo_type), Node('for_statement', sequences=Node('for_sequence_with_index', sequence=self.args[0]), iterators=Node('for_iterator_with_index', index=_index, iterator=z_arg), block=initial + [ Node('if_statement', test=block_test, block=[ assignment( z, call('append', [z, z_arg], z.pseudo_type)) ], otherwise=None) ]), z ], None
def as_expression(self, target=None): _index = local('_index', 'Int') name = self.temp_name(target or self.default) z = local(name, pseudo_type=self.args[0].pseudo_type) if self.args[1].type == 'anonymous_function': block_test = self.args[1].block[-1].value initial = self.args[1].block[:-1] z_arg = self.args[1].params[0] else: z_arg = local('_value', z.pseudo_type[1]) block_test = call(self.args[1], z_arg, 'Boolean') initial = [] return [Node('_go_declaration', decl=name, decl_type=z.pseudo_type), Node('for_statement', sequences=Node('for_sequence_with_index', sequence=self.args[0]), iterators=Node('for_iterator_with_index', index=_index, iterator=z_arg), block=initial + [ Node('if_statement', test=block_test, block=[assignment( z, call('append', [z, z_arg], z.pseudo_type))], otherwise=None)]), z], None
def _expand_api(self, api, receiver, args, pseudo_type, equivalent): ''' the heart of api translation dsl function or <z>(<arg>, ..) can be expanded, <z> can be just a name for a global function, or #name for method, <arg> can be %{self} for self or %{n} for nth arg ''' if callable(api): if receiver: return api(receiver, *(args + [pseudo_type])) else: return api(*(args + [pseudo_type])) elif isinstance(api, str): if '(' in api: call_api, arg_code = api[:-1].split('(') new_args = [ self._parse_part(a.strip(), receiver, args, equivalent) for a in arg_code.split(',') ] else: call_api, arg_code = api, '' new_args = args if '#' in call_api: a, b = call_api.split('#') method_receiver = self._parse_part( a, receiver, args, equivalent) if a else receiver return method_call(method_receiver, b, new_args, pseudo_type=pseudo_type) elif '.' in call_api: a, b = call_api.split('.') static_receiver = self._parse_part( a, receiver, args, equivalent) if a else receiver if b[-1] != '!': return Node('static_call', receiver=static_receiver, message=b, args=new_args, pseudo_type=pseudo_type) else: return Node('attr', object=static_receiver, attr=b[:-1], pseudo_type=pseudo_type) else: if receiver: return call(call_api, [receiver] + new_args, pseudo_type=pseudo_type) else: return call(call_api, new_args, pseudo_type=pseudo_type) else: raise PseudoDSLError('%s not supported by api dsl' % str(api))
def as_expression(self): return [ Node('_go_multi_assignment', targets=[local('reader', 'Reader'), local('err', 'Error')], values=[call(attr(local('bufio', 'GoLibrary'), 'NewReader', ['Function', 'IO', 'Reader']), [attr(local('os', 'GoLibrary'), 'Stdin', 'IO')], pseudo_type='Reader')]), call( attr(local('reader', 'Reader'), 'ReadString', ['Function', 'String', 'String']), [to_node('\\n')], pseudo_type='String')], None
def as_expression(self): return [ Node('_go_multi_assignment', targets=[local('reader', 'Reader'), local('err', 'Error')], values=[ call(attr(local('bufio', 'GoLibrary'), 'NewReader', ['Function', 'IO', 'Reader']), [attr(local('os', 'GoLibrary'), 'Stdin', 'IO')], pseudo_type='Reader') ]), call(attr(local('reader', 'Reader'), 'ReadString', ['Function', 'String', 'String']), [to_node('\\n')], pseudo_type='String') ], None
def as_expression(self): return [], Node( '_py_with', call=call('open', [self.args[0], to_node('w')], 'File'), context='_f', block=[method_call(local('_f', 'File'), 'write', [self.args[1]], 'Void')], pseudo_type='Void')
def as_expression(self): return [Node( '_py_with', call=call('open', [self.args[0], to_node('r')], 'File'), context='_f', block=[method_call(local('_f', 'File'), 'read', [], 'String')], pseudo_type='Void')], None
def expand_map(receiver, func): if func.type == 'lambda': return Node( '_py_list_comp', sequence=receiver) else: return call('map', [func, receiver])
def display(*values): if all(isinstance(v.pseudo_type, str) for v in values[:-1]): name = 'puts' else: name = 'p' return call(name, values[:-1], 'Void')
def as_expression(self, target=None): t = self.temp_name(target or 'accumulator') if self.args[1].type == 'anonymous_function': initial = self.args[1].block[:-1] element = self.args[1].params[1] if target is None: target = self.args[1].params[0] elif target.name != self.args[1].params[0].name: self.args[1].block = ReduceRewriter( self.args[1].params[0].name, target.name).transform(self.args[1].block) self.args[1].params[0] = target block_result = self.args[1].block[-1].value else: initial = [] element = local('_element', self.args[0].pseudo_type[1]) if target is None: target = local(t, self.args[1].pseudo_type[-1]) block_result = call(self.args[1], [element, target], target.pseudo_type) return [ assignment(target, self.args[2]), Node('for_statement', sequences=Node('for_sequence', sequence=self.args[0]), iterators=Node('for_iterator', iterator=element), block=initial + [assignment(target, block_result)]), target ], None
def display(*values): if all(isinstance(v.pseudo_type, str) for v in values[:-1]): name = 'puts' else: name = 'p' return call(name, values[:-1], 'Void')
def as_expression(self, target=None): t = self.temp_name(target or 'accumulator') if self.args[1].type == 'anonymous_function': initial = self.args[1].block[:-1] element = self.args[1].params[1] if target is None: target = self.args[1].params[0] elif target.name != self.args[1].params[0].name: self.args[1].block = ReduceRewriter(self.args[1].params[0].name, target.name).transform(self.args[1].block) self.args[1].params[0] = target block_result = self.args[1].block[-1].value else: initial = [] element = local('_element', self.args[0].pseudo_type[1]) if target is None: target = local(t, self.args[1].pseudo_type[-1]) block_result = call(self.args[1], [element, target], target.pseudo_type) return [assignment(target, self.args[2]), Node('for_statement', sequences=Node('for_sequence', sequence=self.args[0]), iterators=Node('for_iterator', iterator=element), block=initial + [ assignment(target, block_result) ]), target], None
def expand_slice(receiver, from_=None, to=None, pseudo_type=None): if from_: if pseudo_type: #to if from_.type == 'int' and from_.value == 0: return Node('_go_slice_to', sequence=receiver, to=to, pseudo_type=pseudo_type) else: if from_.type == 'int' and from_.value < 0: from_ = Node('binary_op', op='-', left=call('len', [receiver], 'Int'), right=to_node(-from_.value), pseudo_type='Int') if to.type == 'int' and to.value < 0: to = Node('binary_op', op='-', left=call('len', [receiver], 'Int'), right=to_node(-to.value), pseudo_type='Int') return Node('_go_slice', sequence=receiver, from_=from_, to=to, pseudo_type=pseudo_type) else: pseudo_type = to return Node('_go_slice_from', sequence=receiver, from_=from_, pseudo_type=pseudo_type) elif to: if to.type == 'int' and to.value < 0: to = Node('binary_op', op='-', left=call('len', [receiver], 'Int'), right=to_node(-to.value), pseudo_type='Int') return Node('_go_slice_to', sequence=receiver, to=to, pseudo_type=pseudo_type) else: return None
def as_expression(self): return [ Node( '_py_with', call=call('open', [self.args[0], to_node('r')], 'File'), context='_f', block=[method_call(local('_f', 'File'), 'read', [], 'String')], pseudo_type='Void') ], None
def as_expression(self): return [], Node('_py_with', call=call('open', [self.args[0], to_node('w')], 'File'), context='_f', block=[ method_call(local('_f', 'File'), 'write', [self.args[1]], 'Void') ], pseudo_type='Void')
def as_expression(self): l = local(self.temp_name(''), 'String') return [Node('_go_multi_assignment', targets=[l, local('_', 'Error')], values=[Node('static_call', message='ReadFile', receiver=local('ioutil', 'Library'), args=self.args, pseudo_type='MaybeBytez')]), call('string', [l], 'String')], None
def x(receiver, test, pseudo_type): return call( local(method, ['Function', test.pseudo_type, 'Boolean']), [Node('_py_generatorcomp', sequences=Node('for_sequence', sequence=receiver), iterators=Node('for_iterator', iterator=local(test.params[0].name, test.pseudo_type[1])), block=test.block[0].value, test=None, pseudo_type=['PyGenerator', 'Boolean'])], pseudo_type='Boolean')
def expand_slice(receiver, from_=None, to=None, pseudo_type=None): if from_: if pseudo_type: #to if from_.type == 'int' and from_.value == 0: return Node('_go_slice_to', sequence=receiver, to=to, pseudo_type=pseudo_type) else: if from_.type == 'int' and from_.value < 0: from_ = Node('binary_op', op='-', left=call('len', [receiver], 'Int'), right=to_node(-from_.value), pseudo_type='Int') if to.type == 'int' and to.value < 0: to = Node('binary_op', op='-', left=call('len', [receiver], 'Int'), right=to_node(-to.value), pseudo_type='Int') return Node('_go_slice', sequence=receiver, from_=from_, to=to, pseudo_type=pseudo_type) else: pseudo_type = to return Node('_go_slice_from', sequence=receiver, from_=from_, pseudo_type=pseudo_type) elif to: if to.type == 'int' and to.value < 0: to = Node('binary_op', op='-', left=call('len', [receiver], 'Int'), right=to_node(-to.value), pseudo_type='Int') return Node('_go_slice_to', sequence=receiver, to=to, pseudo_type=pseudo_type) else: return None
def x(receiver, test, pseudo_type): return call(local(method, ['Function', test.pseudo_type, 'Boolean']), [ Node('_py_generatorcomp', sequences=Node('for_sequence', sequence=receiver), iterators=Node('for_iterator', iterator=local(test.params[0].name, test.pseudo_type[1])), block=test.block[0].value, test=None, pseudo_type=['PyGenerator', 'Boolean']) ], pseudo_type='Boolean')
def _expand_api(self, api, receiver, args, pseudo_type, equivalent): ''' the heart of api translation dsl function or <z>(<arg>, ..) can be expanded, <z> can be just a name for a global function, or #name for method, <arg> can be %{self} for self or %{n} for nth arg ''' if callable(api): if receiver: return api(receiver, *(args + [pseudo_type])) else: return api(*(args + [pseudo_type])) elif isinstance(api, str): if '(' in api: call_api, arg_code = api[:-1].split('(') new_args = [self._parse_part( a.strip(), receiver, args, equivalent) for a in arg_code.split(',')] else: call_api, arg_code = api, '' new_args = args if '#' in call_api: a, b = call_api.split('#') method_receiver = self._parse_part( a, receiver, args, equivalent) if a else receiver return method_call(method_receiver, b, new_args, pseudo_type=pseudo_type) elif '.' in call_api: a, b = call_api.split('.') static_receiver = self._parse_part( a, receiver, args, equivalent) if a else receiver if b[-1] != '!': return Node('static_call', receiver=static_receiver, message=b, args=new_args, pseudo_type=pseudo_type) else: return Node('attr', object=static_receiver, attr=b[:-1], pseudo_type=pseudo_type) else: if receiver: return call(call_api, [receiver] + new_args, pseudo_type=pseudo_type) else: return call(call_api, new_args, pseudo_type=pseudo_type) else: raise PseudoDSLError('%s not supported by api dsl' % str(api))
def as_expression(self): l = local(self.temp_name(''), 'String') return [ Node('_go_multi_assignment', targets=[l, local('_', 'Error')], values=[ Node('static_call', message='ReadFile', receiver=local('ioutil', 'Library'), args=self.args, pseudo_type='MaybeBytez') ]), call('string', [l], 'String') ], None
def as_expression(self): e = self.temp_name('') e_singular = self.singular_name() e_index = self.index() if self.field == 'keys': field_type = self.args[0].pseudo_type[1] first = local(e_singular, field_type) second = local('_', self.args[0].pseudo_type[2]) else: field_type = self.args[0].pseudo_type[2] first = local('_', self.args[0].pseudo_type[1]) second = local(e_singular, field_type) e = local(e, field_type) e_singular = local(e_singular, field_type) return [ assignment( e, Node('_go_make_slice', slice_type=['List', field_type], length=call('len', [self.args[0]], 'Int'), pseudo_type=['List', field_type])), assignment(e_index, to_node(0)), Node('for_statement', sequences=Node('for_sequence_with_items', sequence=self.args[0]), iterators=Node('for_iterator_with_items', key=first, value=second), block=[ assignment( Node('index', sequence=e, index=e_index, pseudo_type=field_type), e_singular), Node('aug_assignment', op='+', target=e_index, value=to_node(1)) ]), e ], None def as_assignment(self, target): e = self.as_expression()[0] e[3] = assignment(target, e) return e
def as_expression(self, target=None): _index = local('_index', 'Int') name = self.temp_name(target or self.default) z = local(name, pseudo_type=['List', self.args[-1].pseudo_type[2]]) z_arg = local('_value', z.pseudo_type[1]) return [assignment(z, Node('_go_make_slice', slice_type=z.pseudo_type, length=call('len', [self.args[0]], 'Int'))), Node('for_statement', sequences=Node('for_sequence_with_index', sequence=self.args[0]), iterators=Node('for_iterator_with_index', index=_index, iterator=self.args[1].params[0] if self.args[1].type == 'anonymous_function' else z_arg), block=self.args[1].block[:-1] + [ assignment(Node('index', sequence=z, index=_index, pseudo_type=z.pseudo_type[1]), self.args[1].block[-1].value)] if self.args[1].type == 'anonymous_function' else assignment(Node('index', sequence=z, index=_index, pseudo_type=z.pseudo_type[1]), call(self.args[1], z_arg, z.pseudo_type[1]))), z], None
def expand_insert(receiver, index, element): return call('append', [])
target=Node('instance_variable', name='egg', pseudo_type='Int'), value=local('ham', pseudo_type='Int')), Node('assignment', target=Node('attr', object=Node('typename', name='T'), attr='egg', pseudo_type='String'), value=local('ham', pseudo_type='String')), Node('assignment', target=Node('index', sequence=local('x', pseudo_type=['List', 'String']), index=to_node(4), pseudo_type='String'), value=to_node('String')) ] Call = [call('map', [local('x')])] MethodCall = [method_call(local('e', 'E'), 'filter', [to_node(42)])] StandardCall = [ Node('standard_call', namespace='io', function='display', args=[to_node(42)], pseudo_type='Void'), Node('standard_call', namespace='io', function='read', args=[], pseudo_type='String'), Node('standard_call', namespace='math', function='ln',
def expand_insert(receiver, index, element): return call('append', [])
def expand_push(receiver, element): return Node('assignment', target=receiver, value=call('append', [receiver, element]))
def expand_filter(receiver, func): if func.type == 'lambda': return Node( '_py_list_comp') else: return call('filter', [func, receiver])
def present(s, _): return Node('binary_op', op='>', left=call('len', [s], 'Int'), right=to_node(0), pseudo_type='Boolean')
def present(s, _): return Node('binary_op', op='>', left=call('len', [s], 'Int'), right=to_node(0), pseudo_type='Boolean')
def as_expression(self): e = self.temp_name('') e_singular = self.singular_name() e_index = self.index() if self.field == 'keys': field_type = self.args[0].pseudo_type[1] first = local(e_singular, field_type) second = local('_', self.args[0].pseudo_type[2]) else: field_type = self.args[0].pseudo_type[2] first = local('_', self.args[0].pseudo_type[1]) second = local(e_singular, field_type) e = local(e, field_type) e_singular = local(e_singular, field_type) return [assignment(e, Node('_go_make_slice', slice_type=['List', field_type], length=call('len', [self.args[0]], 'Int'), pseudo_type=['List', field_type])), assignment(e_index, to_node(0)), Node('for_statement', sequences=Node('for_sequence_with_items', sequence=self.args[0]), iterators=Node('for_iterator_with_items', key=first, value=second), block=[ assignment( Node('index', sequence=e, index=e_index, pseudo_type=field_type), e_singular), Node('aug_assignment', op='+', target=e_index, value=to_node(1))]), e], None def as_assignment(self, target): e = self.as_expression()[0] e[3] = assignment(target, e) return e
def expand_push(receiver, element): return Node( 'assignment', target=receiver, value=call('append', [receiver, element]))
class PythonTranslator(ApiTranslator): ''' Python api translator The DSL is explained in the ApiTranslator docstring ''' methods = { 'List': { '@equivalent': 'list', 'push': '#append', 'pop': '#pop', 'length': 'len', 'insert': '#insert', 'remove_at': lambda receiver, index, _: Node( '_py_del', value=Node('index', sequence=receiver, index=index), pseudo_type='Void'), 'remove': '#remove', 'slice': expand_slice, 'slice_from': expand_slice, 'slice_to': lambda receiver, to, pseudo_type: expand_slice( receiver, None, to, pseudo_type), 'repeat': to_op('*'), 'set_slice': expand_set_slice, 'set_slice_from': expand_set_slice, 'set_slice_to': lambda receiver, to, value, pseudo_type: expand_set_slice( receiver, None, to, value, pseudo_type), 'find': '#index', 'join': lambda receiver, delimiter, _: method_call( delimiter, 'join', [receiver], pseudo_type='String'), # map and filter have implicit or explicit return because otherwise they wouldnt type check 'map': lambda receiver, f, pseudo_type: Node( '_py_listcomp', sequences=Node('for_sequence', sequence=receiver), iterators=Node('for_iterator', iterator=local(f.params[0].name, f.pseudo_type[ 1])), block=f.block[0].value, test=None, pseudo_type=['List', f.pseudo_type[2]]), 'filter': lambda receiver, test, pseudo_type: Node( '_py_listcomp', sequences=Node('for_sequence', sequence=receiver), iterators=Node('for_iterator', iterator=local(test.params[0].name, test. pseudo_type[1])), block=local(test.params[0].name, test.pseudo_type[1]), test=test.block[0].value, pseudo_type=['List', test.pseudo_type[1]]), 'reduce': lambda receiver, aggregator, initial, pseudo_type: Node( 'static_call', receiver=local('functools', 'Library'), message='reduce', args=[aggregator, receiver, initial], pseudo_type=pseudo_type), 'any?': to_py_generatorcomp('any'), 'all?': to_py_generatorcomp('all'), 'sort': '#sort', 'present?': lambda receiver, _: receiver, 'empty?': lambda receiver, _: Node( 'unary_op', op='not', value=receiver, pseudo_type='Boolean'), 'contains?': contains }, 'Dictionary': { '@equivalent': 'dict', 'length': 'len', 'keys': '#keys', 'values': '#values', 'contains?': contains, 'keys': lambda receiver, pseudo_type: call(local( 'list', ['Function', 'Any', 'List']), [ method_call(receiver, 'keys', [], ['dict_keys', pseudo_type[1]]) ], pseudo_type=pseudo_type), 'values': lambda receiver, pseudo_type: call(local( 'list', ['Function', 'Any', 'List']), [ method_call(receiver, 'values', [], ['dict_values', pseudo_type[1]]) ], pseudo_type=pseudo_type), 'present?': lambda receiver, _: receiver, 'empty?': lambda receiver, _: Node( 'unary_op', op='not', value=receiver, pseudo_type='Boolean') }, 'String': { '@equivalent': 'str', 'substr': expand_slice, 'substr_from': expand_slice, 'length': 'len', 'substr_to': lambda receiver, to, _: expand_slice(receiver, None, to, 'String'), 'find': '#index', 'find_from': '#index', 'count': '#count', 'partition': '#partition', 'split': '#split', 'trim': '#strip', 'format': '#format', 'concat': to_op('+'), 'c_format': to_op('%'), 'center': '#center', 'reversed': 'reversed', 'empty?': lambda receiver, _: Node( 'unary_op', op='not', value=receiver, pseudo_type='Boolean'), 'present?': lambda receiver, _: receiver, 'contains?': lambda receiver, element, _: Node('_py_in', sequence=receiver, value=element, pseudo_type='Boolean'), 'to_int': 'int', 'pad_left': '#ljust', 'pad_right': '#rjust' }, 'Int': { 'to_float': 'float(%{self})' }, 'Float': { 'to_int': 'int(%{self})' }, 'Set': { '@equivalent': 'set', 'length': 'len', 'contains?': contains, 'union': to_op('|'), 'intersection': to_op('-'), 'present?': lambda receiver, _: receiver, 'empty?': lambda receiver, _: Node( 'unary_op', op='not', value=receiver, pseudo_type='Boolean') }, 'Tuple': { '@equivalent': 'tuple', 'length': 'len' }, 'Array': { '@equivalent': 'tuple', 'length': 'len' }, 'Regexp': { '@equivalent': '_sre.SRE_Pattern', 'match': '#match' }, 'RegexpMatch': { '@equivalent': '_sre.SRE_Match', 'group': '#group', 'has_match': lambda receiver, _: receiver } } functions = { 'global': { 'wat': lambda _: Node('block', block=[]), 'exit': lambda status, _: call('exit', [status]) }, 'io': { 'display': 'print', 'read': 'input', 'write_file': WriteFile, 'read_file': ReadFile }, 'system': { 'args': 'sys.argv!', 'arg_count': lambda _: call('len', [ attr(local('sys', 'Library'), 'argv', ['List', 'String']) ], 'Int'), 'index': lambda value, _: Node('index', sequence=attr(local('sys', 'Library'), 'argv', ['List', 'String']), index=value, pseudo_type='String') }, 'http': { 'get': 'requests.get', 'post': 'requests.post', }, 'math': { 'ln': 'math.log', 'log': 'math.log', 'tan': 'math.tan', 'sin': 'math.sin', 'cos': 'math.cos', 'pow': lambda left, right, pseudo_type: Node('binary_op', op='**', left=left, right=right, pseudo_type=pseudo_type) }, 'regexp': { 'compile': 're.compile', 'escape': 're.escape' } } dependencies = { 'Regexp': { '@all': 're' }, 'List': { 'reduce': 'functools' }, 'http': { '@all': 'requests' }, 'math': { '@all': 'math' }, 'regexp': { '@all': 're' }, 'system': { '@all': 'sys' } }
class GolangTranslator(ApiTranslator): ''' Go api translator The DSL is explained in the ApiTranslator docstring ''' methods = { 'List': { '@equivalent': 'slice', 'push': lambda receiver, element, _: assignment( receiver, call('append', [receiver, element], receiver.pseudo_type)), 'pop': lambda receiver, _: assignment( receiver, Node('_go_slice_to', sequence=receiver, to=Node('binary_op', op='-', left=call('len', [receiver], 'Int'), right=to_node(1), pseudo_type='Int'), pseudo_type=receiver.pseudo_type)), 'length': 'len', 'insert': expand_insert, 'slice': expand_slice, 'slice_from': expand_slice, 'slice_to': lambda receiver, to, pseudo_type: expand_slice( receiver, None, to, pseudo_type), 'join': 'strings.Join(%{self}, %{0})', 'map': expand_map, 'filter': expand_filter, 'find': Find, 'reduce': expand_reduce, 'contains?': ListContains, 'present?': present, 'empty?': empty }, 'Dictionary': { '@equivalent': 'map', 'length': 'len', 'contains?': Contains, 'keys': DictKeys, 'values': DictValues, 'present?': present, 'empty?': empty }, 'String': { '@equivalent': 'str', 'substr': expand_slice, 'substr_from': expand_slice, 'length': 'len', 'substr_to': lambda receiver, to, _: expand_slice( receiver, None, to, pseudo_type='String'), 'find': 'strings.Index(%{self}, %{0})', 'count': 'strings.Count(%{self}, %{0})', 'split': 'strings.Split(%{self}, %{0})', 'concat': to_op('+'), 'contains?': 'strings.Contains(%{self}, %{0})', 'present?': present, 'empty?': empty, 'find_from': lambda f, value, index, _: Node( 'binary_op', op='+', pseudo_type='Int', left=index, right=Node('static_call', receiver=local('strings', 'Library'), message='Index', args=[ Node('_go_slice_from', sequence=f, from_=index, pseudo_type='String'), value ], pseudo_type='Int')), 'to_int': Int }, 'Regexp': { '@equivalent': 'Regexp', 'match': lambda receiver, word, _: method_call( receiver, 'FindAllSubmatch', [ Node('_go_bytes', value=word, pseudo_type='Bytes'), to_node(-1) ], pseudo_type='RegexpMatch') }, 'RegexpMatch': { '@equivalent': 'R', 'group': lambda receiver, index, _: Node('index', sequence=receiver, index=Node('binary_op', op='+', left=index, right=to_node(1), pseudo_type='Int'), pseudo_type='String'), 'has_match': lambda receiver, _: Node('comparison', op='!=', left=receiver, right=Node('null', pseudo_type='None'), pseudo_type='Boolean') }, 'Set': { '@equivalent': 'map[bool]struct{}', 'length': 'len', 'contains?': Contains, 'present?': present, 'empty?': empty }, 'Tuple': { '@equivalent': 'L', 'length': lambda receiver, _: to_node(len(receiver.pseudo_type) - 1) }, 'Array': { '@equivalent': 'int[]', 'length': lambda receiver, _: to_node(receiver.pseudo_type[2]) } } functions = { 'regexp': { 'compile': 'regexp.MustCompile', 'escape': 'regexp.QuoteMeta' }, 'io': { 'display': 'fmt.Println', 'read': Read, 'read_file': ReadFile, 'write_file': 'ioutil.WriteFile' }, 'math': { 'ln': 'math.Log', 'log': 'math.Log', 'tan': 'math.Tan', 'sin': 'math.Sin', 'cos': 'math.Cos', 'pow': 'math.Pow' }, 'system': { 'args': 'os.Args!', 'arg_count': lambda _: call('len', [ attr(local('os', 'Library'), 'Args', ['List', 'String']) ], 'Int'), 'index': lambda value, _: Node('index', sequence=attr(local('os', 'Library'), 'Args', ['List', 'String']), index=value, pseudo_type='String') } } dependencies = { 'regexp': { '@all': 'regexp' }, 'io': { 'display': 'fmt', 'read': ['bufio', 'os'], 'read_file': ['io/ioutil'], 'write_file': ['io/ioutil'] }, 'math': { '@all': 'math' }, 'List': { 'join': 'strings' }, 'String': { 'find': 'strings', 'count': 'strings', 'split': 'strings', 'contains?': 'strings', 'find_from': 'strings', 'to_int': 'strconv' }, 'system': { '@all': 'os' } } errors = {}
class JSTranslator(ApiTranslator): ''' JS api translator The DSL is explained in the ApiTranslator docstring ''' methods = { 'List': { '@equivalent': 'Array', 'push': '#push', 'pop': '#pop', 'length': '.length!', 'insert': '#splice(%{self}, 0, %{0})', 'remove_at': lambda receiver, index, _: method_call( receiver, 'splice', [ index, to_node(index.value + 1) if index.type == 'int' else Node('binary_op', op='+', left=index, right=to_node(1), pseudo_type='Int') ], pseudo_type='Void'), 'remove': '_.pull(%{self}, %{0})', 'slice': '#slice', 'slice_from': '#slice', 'slice_to': '#slice(0, %{0})', 'map': '_.map(%{self}, %{0})', 'filter': '_.filter(%{self}, %{0})', 'reduce': '_.reduce(%{self}, %{0}, %{1})', 'any?': '_.any(%{self}, %{0})', 'all?': '_.all(%{self}, %{0})', 'sort': '#sort', 'empty?': empty, 'present?': present, 'find': '#indexOf', 'contains?': '_.contains(%{self}, %{0})' }, 'Dictionary': { '@equivalent': 'Object', 'length': object_len, 'keys': 'Object.keys(%{self})', 'values': 'Object.values(%{self})', 'contains?': '#hasOwnProperty', 'present?': present, 'empty?': empty }, 'String': { '@equivalent': 'String', 'substr': '#slice', 'substr_from': '#slice', 'length': '.length!', 'substr_to': '#slice(0, %{0})', 'find': '#search', 'find_from': lambda f, value, index, _: Node( 'binary_op', op='+', pseudo_type='Int', left=index, right=method_call(method_call(f, 'slice', [index], 'String'), 'search', [value], 'Int')), 'count': lambda f, count, _: attr( method_call(LODASH, 'where', [count], ['List', 'String']), 'length', 'Int'), 'concat': to_op('+'), 'partition': lambda f, delimiter, _: Node( 'index', sequence=method_call(LODASH, 'partition', [delimiter], 'String' ), index=to_node(1), pseudo_type=['Tuple', 'String', 'String', 'String']), 'split': '#split', 'trim': '#trim', 'reversed': lambda f, _: method_call( method_call( method_call(f, 'split', [to_node('')], ['List', 'String']), 'reverse', [], ['List', 'String']), 'join', [to_node('')], 'String'), 'center': '_.pad(%{self}, %{0}, %{1})', 'present?': lambda f, _: f, 'empty?': lambda f, _: Node( 'unary_op', op='not', value=f, pseudo_type='Boolean'), 'contains?': '_.contains(%{self}, %{0})', 'to_int': 'parseInt', 'pad_left': '_.padLeft(%{self}, %{0}, %{1})', 'pad_right': '_.padRight(%{self}, %{0}, %{1})' }, 'Tuple': { '@equivalent': 'Array', 'length': '.length!' }, 'Array': { '@equivalent': 'Array', 'length': '.length!' }, 'Set': { '@equivalent': 'Object', 'length': object_len, 'contains?': '_.contains(%{self}, %{0})', 'intersection': '_.intersection(%{self}, %{0})', 'union': '_.union(%{self}, %{0})', 'present?': present, 'empty?': empty }, 'RegexpMatch': { '@equivalent': 'Array', 'group': lambda receiver, index, _: Node('index', sequence=receiver, index=to_node(1 + index.value) if index.type == 'int' else Node( 'binary_op', op='+', left=to_node(1), right=index, pseudo_type='Int'), pseudo_type='String'), 'has_match': lambda receiver, _: receiver }, 'Regexp': { '@equivalent': 'Regexp', 'match': '#exec' } } functions = { 'global': { 'wat': lambda _: Node('block', block=[]), 'exit': lambda status, _: call('exit', [status]) }, 'system': { 'args': 'process.argv!', 'arg_count': lambda _: Node('binary_op', op='-', left=attr( attr(local('process', 'Library'), 'argv', ['List', 'String']), 'length', 'Int'), right=to_node(1), pseudo_type='Int'), 'index': lambda value, _: Node('index', sequence=attr(local('process', 'Library'), 'argv', ['List', 'String']), index=to_node(value.value + 1) if value.type == 'int' else Node('binary_op', op='+', left=value, right=value, pseudo_type='Int'), pseudo_type='String') }, 'io': { 'display': 'console.log', 'read_file': "fs.readFileSync(%{0}, 'utf8')", 'write_file': "fs.writeFileSync(%{0}, %{1}, 'utf8')", }, 'math': { 'ln': 'Math.log', 'log': 'Math.log', 'tan': 'Math.tan', 'sin': 'Math.sin', 'cos': 'Math.cos', 'pow': 'Math.pow' }, 'regexp': { 'compile': lambda value, _: Node('new_instance', class_name='RegExp', args=[value], pseudo_type='Regexp'), 'escape': '_.escapeRegExp' } } js_dependencies = {'_': 'lodash'} dependencies = { 'io': { 'read_file': 'fs', 'write_file': 'fs' }, 'regexp': { 'escape': 'lodash' } }
Typename = [typename('Egg')] InstanceVariable = [Node('instance_variable', name='egg')] Attr = [Node('attr', object=local('e'), attr='egg')] Assignment = [ Node('assignment', target=local('egg', pseudo_type='Int'), value=local('ham', pseudo_type='Int')), Node('assignment', target=Node('instance_variable', name='egg', pseudo_type='Int'), value=local('ham', pseudo_type='Int')), Node('assignment', target=Node('attr', object=Node('typename', name='T'), attr='egg', pseudo_type='String'), value=local('ham', pseudo_type='String')), Node('assignment', target=Node('index', sequence=local('x', pseudo_type=['List', 'String']), index=to_node(4), pseudo_type='String'), value=to_node('String')) ] Call = [call('map', [local('x')])] MethodCall = [method_call(local('e', 'E'), 'filter', [to_node(42)])] StandardCall = [ Node('standard_call', namespace='io', function='display', args=[to_node(42)], pseudo_type='Void'), Node('standard_call', namespace='io', function='read', args=[], pseudo_type='String'), Node('standard_call', namespace='math', function='ln', args=[Node('local', name='ham', pseudo_type='Int')], pseudo_type='Float'), assignment( local('source', pseudo_type='String'), Node('standard_call', namespace='io', function='read_file', args=[to_node('f.py')], pseudo_type='String')) ] IoDisplay = standard_call('io', 'display', [to_node(2), to_node('z')], 'Void') IoRead = assignment(local('source', 'String'), standard_call('io', 'read', [], 'String')) IoReadFile = assignment(local('source', 'String'), standard_call('io', 'read_file', [to_node('z.py')], 'String')) IoWriteFile = standard_call('io', 'write_file', [to_node('z.py'), local('source', 'String')], 'Void')