Home | History | Annotate | Download | only in pyct
      1 # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
      2 #
      3 # Licensed under the Apache License, Version 2.0 (the "License");
      4 # you may not use this file except in compliance with the License.
      5 # You may obtain a copy of the License at
      6 #
      7 #     http://www.apache.org/licenses/LICENSE-2.0
      8 #
      9 # Unless required by applicable law or agreed to in writing, software
     10 # distributed under the License is distributed on an "AS IS" BASIS,
     11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 # See the License for the specific language governing permissions and
     13 # limitations under the License.
     14 # ==============================================================================
     15 """Handling annotations on AST nodes.
     16 
     17 Adapted from Tangent.
     18 """
     19 
     20 from __future__ import absolute_import
     21 from __future__ import division
     22 from __future__ import print_function
     23 
     24 from enum import Enum
     25 
     26 
     27 class NoValue(Enum):
     28 
     29   def __repr__(self):
     30     return self.name
     31 
     32 
     33 class Basic(NoValue):
     34   """Container for annotation keys.
     35 
     36   The enum values are used strictly for documentation purposes.
     37   """
     38 
     39   QN = 'Qualified name, as it appeared in the code.'
     40   SKIP_PROCESSING = (
     41       'This node should be preserved as is and not processed any further.')
     42   INDENT_BLOCK_REMAINDER = (
     43       'When a node is annotated with this, the remainder of the block should '
     44       'be indented below it. The annotation contains a tuple '
     45       '(new_body, name_map), where `new_body` is the new indented block and '
     46       '`name_map` allows renaming symbols.')
     47 
     48 
     49 def getanno(node, key, field_name='___pyct_anno'):
     50   return getattr(node, field_name)[key]
     51 
     52 
     53 def hasanno(node, key, field_name='___pyct_anno'):
     54   return hasattr(node, field_name) and key in getattr(node, field_name)
     55 
     56 
     57 def setanno(node, key, value, field_name='___pyct_anno'):
     58   annotations = getattr(node, field_name, {})
     59   setattr(node, field_name, annotations)
     60   annotations[key] = value
     61 
     62   # So that the annotations survive gast_to_ast() and ast_to_gast()
     63   if field_name not in node._fields:
     64     node._fields += (field_name,)
     65 
     66 
     67 def delanno(node, key, field_name='___pyct_anno'):
     68   annotations = getattr(node, field_name)
     69   del annotations[key]
     70   if not annotations:
     71     delattr(node, field_name)
     72     node._fields = tuple(f for f in node._fields if f != field_name)
     73