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