github.com/grumpyhome/grumpy@v0.3.1-0.20201208125205-7b775405bdf1/grumpy-tools-src/grumpy_tools/compiler/expr.py (about)

     1  # coding=utf-8
     2  
     3  # Copyright 2016 Google Inc. All Rights Reserved.
     4  #
     5  # Licensed under the Apache License, Version 2.0 (the "License");
     6  # you may not use this file except in compliance with the License.
     7  # You may obtain a copy of the License at
     8  #
     9  #     http://www.apache.org/licenses/LICENSE-2.0
    10  #
    11  # Unless required by applicable law or agreed to in writing, software
    12  # distributed under the License is distributed on an "AS IS" BASIS,
    13  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  # See the License for the specific language governing permissions and
    15  # limitations under the License.
    16  
    17  """Classes representing generated expressions."""
    18  
    19  from __future__ import unicode_literals
    20  
    21  import abc
    22  
    23  from grumpy_tools.compiler import util
    24  
    25  
    26  class GeneratedExpr(object):
    27    """GeneratedExpr is a generated Go expression in transcompiled output."""
    28  
    29    __metaclass__ = abc.ABCMeta
    30  
    31    def __enter__(self):
    32      return self
    33  
    34    def __exit__(self, unused_type, unused_value, unused_traceback):
    35      self.free()
    36  
    37    @abc.abstractproperty
    38    def expr(self):
    39      pass
    40  
    41    def free(self):
    42      pass
    43  
    44  
    45  class GeneratedTempVar(GeneratedExpr):
    46    """GeneratedTempVar is an expression result stored in a temporary value."""
    47  
    48    def __init__(self, block_, name, type_):
    49      self.block = block_
    50      self.name = name
    51      self.type_ = type_
    52  
    53    @property
    54    def expr(self):
    55      return self.name
    56  
    57    def free(self):
    58      self.block.free_temp(self)
    59  
    60  
    61  class GeneratedLocalVar(GeneratedExpr):
    62    """GeneratedLocalVar is the Go local var corresponding to a Python local."""
    63  
    64    def __init__(self, name):
    65      self._name = name
    66  
    67    @property
    68    def expr(self):
    69      return util.adjust_local_name(self._name)
    70  
    71  
    72  class GeneratedLiteral(GeneratedExpr):
    73    """GeneratedLiteral is a generated literal Go expression."""
    74  
    75    def __init__(self, expr):
    76      self._expr = expr
    77  
    78    @property
    79    def expr(self):
    80      return self._expr
    81  
    82  
    83  nil_expr = GeneratedLiteral('nil')
    84  
    85  
    86  class BlankVar(GeneratedExpr):
    87    def __init__(self):
    88      self.name = '_'
    89  
    90    @property
    91    def expr(self):
    92      return '_'
    93  
    94  
    95  blank_var = BlankVar()