示例#1
0
def normalize(f, from_, to):
    if to.type == 'int':
        if to.value < 0:
            if from_.type != 'int':
                return Node('binary_op',
                    op='-', 
                    left=Node('binary_op',
                        op='-',
                        left=attr(f, 'Length', 'Int'),
                        right=to,
                        pseudo_type='Int'),
                    right=from_,
                    pseudo_type='Int')
            else:
                return Node('binary_op',
                    op='-', 
                    left=attr(f, 'Length', 'Int'),
                    right=to_node(-to.value + from_.value),
                    pseudo_type='Int')
        else:
            if from_.type != 'int':
                return Node('binary_op',
                    op='-', 
                    left=to,
                    right=from_,
                    pseudo_type='Int')
            else:
                return to_node(to.value - from_.value)
    else:
        if from_.type == 'int' and from_.value == 0:
            return to
        else:
            return Node('binary_op', op='-', left=to, right=from_, pseudo_type='Int')
示例#2
0
def expand_slice(receiver, from_, to, pseudo_type=None):
    return method_call(
        method_call(
            receiver, 
            'Take', 
            
            [Node('binary_op', op='-', left=attr(receiver, 'Length', 'Int'), right=to_node(-to.value), pseudo_type='Int') if to.type == 'int' and to.value < 0 else to],
            pseudo_type=pseudo_type),
        'Drop', 
        [Node('binary_op', op='-', left=attr(receiver, 'Length', 'Int'), right=to_node(-from_.value), pseudo_type='Int') if from_.type == 'int' and from_.value < 0 else from_],
        pseudo_type=pseudo_type)
示例#3
0
 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
示例#4
0
 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
示例#5
0
 def transform_index(self, n, in_block=False, assignment=None):
     if general_type(n.sequence.pseudo_type) == 'Tuple':
         class_name, class_node = self.tuple_definitions.get(safe_serialize_type(n.sequence.pseudo_type), (None, None))
         # we can have only literal int index of tuple because typecheck
         if class_name:
             return attr(local(n.sequence, class_name), camel_case(class_node.attrs[n.index.value].name), pseudo_type=n.pseudo_type)
     return n
示例#6
0
def split(f, delimiter, pseudo_type):
    if delimiter.type == 'string' and (len(delimiter.value) == 1 or delimiter.value == '\\n'):
        return method_call(f, 'Split', [Node('char', value=delimiter.value, pseudo_type='Char')], ['List', 'String'])
    else:
        return method_call(f, 
            'Split', 
            [Node('array', elements=[delimiter]), attr(typename('StringSplitOptions', 'Library'), 'None', 'CSharpNone')], 
            pseudo_type=['List', 'String'])
示例#7
0
def object_len(l, _):
    return attr(
        method_call(
            typename('Object', 'Type'),
            'keys',
            [l],
            ['List', l.pseudo_type[1]]),
        'length',
        'Int')
示例#8
0
 def transform_index(self, n, in_block=False, assignment=None):
     if general_type(n.sequence.pseudo_type) == 'Tuple':
         class_name, class_node = self.tuple_definitions.get(
             safe_serialize_type(n.sequence.pseudo_type), (None, None))
         # we can have only literal int index of tuple because typecheck
         if class_name:
             return attr(local(n.sequence, class_name),
                         camel_case(class_node.attrs[n.index.value].name),
                         pseudo_type=n.pseudo_type)
     return n
示例#9
0
def pad(f, count, fill, pseudo_type):
    return method_call(
        method_call(
            f,
            'PadLeft',
            [Node('binary_op',
                op='+',
                left=Node('binary_op',
                    op='/',
                    left=Node('binary_op',
                        op='-',
                        left=count,
                        right=attr(f, 'Length', 'Int'),
                        pseudo_type='Int'),
                    right=to_node(2),
                    pseudo_type='Int'),
                right=attr(f, 'Length', 'Int'),
                pseudo_type='Int'),
            fill],
            pseudo_type='String'),
        'PadRight',
        [count, fill],
        'String')
示例#10
0
def empty(f, _):
    return Node('comparison',
                op='==',
                left=attr(f, 'length', pseudo_type='Int'),
                right=to_node(0),
                pseudo_type='Boolean')
示例#11
0
def object_len(l, _):
    return attr(
        method_call(typename('Object', 'Type'), 'keys', [l],
                    ['List', l.pseudo_type[1]]), 'length', 'Int')
示例#12
0
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'
        }
    }
示例#13
0
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 = {}
示例#14
0
def present(f, _):
    return Node('comparison',
        op='>',
        left=attr(f, 'length', pseudo_type='Int'),
        right=to_node(0),
        pseudo_type='Boolean')
示例#15
0
 def transform_local(self, node, in_block=False, assignment=None):
     if node.name in self.old_params:
         return attr(self.l, camel_case(node.name)) # aware of tuple name updates
     else:
         return node
示例#16
0
class CSharpTranslator(ApiTranslator):
    '''
    CSharp api translator

    The DSL is explained in the ApiTranslator docstring
    '''

    methods = {
        'List': {
            '@equivalent':
            'List',
            'push':
            '#Insert',
            'pop':
            lambda l, _: method_call(l,
                                     'RemoveAt', [
                                         Node('binary_op',
                                              op='-',
                                              left=attr(l, 'Length', 'Int'),
                                              right=to_node(1),
                                              pseudo_type='Int')
                                     ],
                                     pseudo_type='Void'),
            'insert':
            '#Insert',
            'remove_at':
            '#RemoveAt',
            'remove':
            '#Remove',
            'length':
            '.Length!',
            'slice':
            expand_slice,
            'slice_from':
            lambda l, from_, pseudo_type: method_call(
                l,
                'Drop', [
                    Node('binary_op',
                         op='-',
                         left=attr(l, 'Length', 'Int'),
                         right=to_node(-from_.value),
                         pseudo_type='Int')
                    if from_.type == 'int' and from_.value < 0 else from_
                ],
                pseudo_type=pseudo_type),
            'slice_to':
            lambda l, to, pseudo_type: method_call(
                l,
                'Take', [
                    Node('binary_op',
                         op='-',
                         left=attr(l, 'Length', 'Int'),
                         right=to_node(-to.value),
                         pseudo_type='Int')
                    if to.type == 'int' and to.value < 0 else to
                ],
                pseudo_type=pseudo_type),
            'slice_':
            '#Slice',
            'join':
            lambda l, delimiter, _: method_call(delimiter, 'Join', [receiver],
                                                'String'),
            'map':
            linq('Select'),
            'filter':
            linq('Where'),
            'reduce':
            linq('Aggregate', False, swap=True),
            'all?':
            linq('All'),
            'any?':
            linq('Any'),
            'concat':
            '#AddRange',
            'present?':
            '#Any',
            'empty?':
            empty,
            'find':
            '#IndexOf',
            'contains?':
            '#Contains',
            'sort':
            '#Sort'
        },
        'Dictionary': {
            '@equivalent': 'Dictionary',
            'length': '.Length!',
            'keys': '#Keys',
            'values': '#Values',
            'contains?': '#Contains',
            'present?': '#Any',
            'empty?': empty
        },
        'String': {
            '@equivalent':
            'String',
            'length':
            '.Length!',
            'substr':
            lambda f, from_, to, pseudo_type: method_call(
                f, 'Substring', [from_, normalize(f, from_, to)], pseudo_type),
            'substr_from':
            '#Substring',
            'substr_to':
            lambda f, to, pseudo_type: method_call(f, 'Substring', [
                to_node(0), normalize(f, to_node(0), to)
            ], pseudo_type),
            'find_from':
            '#IndexOf',
            'find':
            '#IndexOf',
            'count':
            lambda f, element, pseudo_type: method_call(
                f,
                'Count', [
                    Node('anonymous_function',
                         params=[local('sub', 'String')],
                         block=[
                             Node('comparison',
                                  op='==',
                                  left=local('sub', 'String'),
                                  right=local('s', 'String'),
                                  pseudo_type='Boolean')
                         ],
                         return_type='Boolean',
                         pseudo_type=['Function', 'String', 'Boolean'])
                ],
                pseudo_type='Int'),
            'concat':
            to_op('+'),
            'split':
            split,
            'trim':
            '#Trim',
            'center':
            pad,
            'present?':
            lambda f, _: Node('comparison',
                              op='!=',
                              left=attr(f, 'Length', 'Int'),
                              right=to_node(0),
                              pseudo_type='Boolean'),
            'empty?':
            lambda f, _: Node('comparison',
                              op='==',
                              left=attr(f, 'Length', 'Int'),
                              right=to_node(0),
                              pseudo_type='Boolean'),
            'contains?':
            '#Contains',
            'to_int':
            'Int32.Parse(%{self})',
            'pad_left':
            '#PadLeft',
            'pad_right':
            '#PadRight'
        },
        'Set': {
            '@equivalent': 'HashSet',
            'length': '.Length!',
            'contains?': '#Contains',
            'union': '#Union',
            'intersection': '#Intersection',
            'present?': '#Any',
            'empty?': empty
        },
        'Regexp': {
            '@equivalent': 'Regexp',
            'match': '#match'
        },
        'RegexpMatch': {
            '@equivalent':
            'RegexpMatch',
            'group':
            lambda receiver, index, _: Node(
                'index',
                sequence=attr(
                    Node('index',
                         sequence=attr(receiver, 'Groups',
                                       ['List', 'CSharpRegexGroup']),
                         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='CSharpRegexGroup'), 'Captures',
                    ['List', 'RegexpMatch']),
                index=to_node(0),
                pseudo_type='RegexpMatch'),
            'has_match':
            '.Success!'
        },
        'Array': {
            '@equivalent': 'Any[]',
            'length': lambda receiver, _: to_node(receiver.pseudo_type[2])
        },
        'Tuple': {
            '@equivalent': 'Tuple',
            'length': lambda _, pseudo_type: to_node(len(pseudo_type) - 1)
        }
    }

    functions = {
        'io': {
            'display': Display,
            'read': 'Console.ReadLine',
            'read_file': 'File.ReadAllText',
            'write_file': 'File.WriteAllText'
        },
        'math': {
            'ln': 'Math.Log',
            'log': 'Math.Log',
            'tan': 'Math.Tan',
            'sin': 'Math.Sin',
            'cos': 'Math.Cos',
            'pow': 'Math.Pow'
        },
        'http': {},
        'system': {
            'args':
            lambda _: local('args', ['List', 'String']),
            'index':
            lambda index, _: Node('index',
                                  sequence=local('args', ['List', 'String']),
                                  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='String'),
            'arg_count':
            lambda _: Node('binary_op',
                           op='+',
                           left=attr(local('args', ['List', 'String']),
                                     'Length', 'Int'),
                           right=to_node(1),
                           pseudo_type='Int')
        },
        'regexp': {
            'compile':
            lambda value, _: Node('new_instance',
                                  class_name='Regex',
                                  args=[value],
                                  pseudo_type='Regexp'),
            'escape':
            'Regex.Escape'
        }
    }

    dependencies = {
        'List': {
            '@all': 'System.Collections.Generic',
            'map': 'System.Linq',
            'filter': 'System.Linq',
            'any?': 'System.Linq',
            'all?': 'System.Linq',
            'reduce': 'System.Linq'
        },
        'String': {
            '@all': 'System.Text'
        },
        'Dictionary': {
            '@all': 'System.Collections.Generic',
        },
        'io': {
            'read_file': 'System.IO',
            'write_file': 'System.IO'
        },
        'regexp': {
            '@all': 'System.Text.RegularExpressions'
        }
    }
示例#17
0
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'
        }
    }
示例#18
0
 def transform_local(self, node, in_block=False, assignment=None):
     if node.name in self.old_params:
         return attr(self.l,
                     camel_case(node.name))  # aware of tuple name updates
     else:
         return node