1# Copyright 2016 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"""Converter for slice operations.""" 16 17import gast 18 19from tensorflow.python.autograph.core import converter 20from tensorflow.python.autograph.lang import directives 21from tensorflow.python.autograph.pyct import templates 22 23 24class SliceTransformer(converter.Base): 25 """Converts slicing operations to their TF counterpart. 26 27 Currently, relying on the default slice operator that Tensor uses is 28 insufficient, because TensorArray and tensor lists use dedicated index read 29 and write functions. 30 """ 31 32 def _process_single_assignment(self, target, value): 33 if not isinstance(target, gast.Subscript): 34 return None 35 s = target.slice 36 if isinstance(s, (gast.Tuple, gast.Slice)): 37 return None 38 39 template = """ 40 target = ag__.set_item(target, key, item) 41 """ 42 return templates.replace( 43 template, target=target.value, key=target.slice, item=value) 44 45 def visit_Assign(self, node): 46 node = self.generic_visit(node) 47 # TODO(mdan): Support unpackings and multiple assignments. 48 if len(node.targets) != 1: 49 raise NotImplementedError('multiple assignment') 50 replacement = self._process_single_assignment(node.targets[0], node.value) 51 if replacement is not None: 52 return replacement 53 return node 54 55 def visit_Subscript(self, node): 56 node = self.generic_visit(node) 57 s = node.slice 58 if isinstance(s, (gast.Tuple, gast.Slice)): 59 return node 60 61 if not isinstance(node.ctx, gast.Load): 62 # Index writes are handled at a higher level, one at which the rvalue is 63 # also available. 64 return node 65 66 dtype = self.get_definition_directive( 67 node.value, 68 directives.set_element_type, 69 'dtype', 70 default=templates.replace_as_expression('None')) 71 72 template = """ 73 ag__.get_item( 74 target, 75 key, 76 opts=ag__.GetItemOpts(element_dtype=dtype)) 77 """ 78 return templates.replace_as_expression( 79 template, target=node.value, key=s, dtype=dtype) 80 81 82def transform(node, ctx): 83 return SliceTransformer(ctx).visit(node) 84