python_code
stringlengths
0
1.02M
repo_name
stringlengths
9
48
file_path
stringlengths
5
114
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for converter module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.core import converter_testing from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import compiler from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import templates from tensorflow.python.platform import test class TestConverter(converter.Base): pass class ConversionOptionsTest(converter_testing.TestCase): def test_to_ast(self): opts = converter.ConversionOptions() opts_ast = opts.to_ast() template = ''' def test_fn(): return opts_ast ''' opts_packed = templates.replace(template, opts_ast=opts_ast) reparsed, _, _ = compiler.ast_to_object(opts_packed) reparsed.__dict__['ag__'] = self.make_fake_mod( 'fake_ag', converter.ConversionOptions, converter.Feature) reparsed_opts = reparsed.test_fn() self.assertEqual(opts.recursive, reparsed_opts.recursive) self.assertEqual(opts.force_conversion, reparsed_opts.force_conversion) self.assertEqual( opts.internal_convert_user_code, reparsed_opts.internal_convert_user_code) self.assertEqual(opts.optional_features, reparsed_opts.optional_features) class ConverterBaseTest(converter_testing.TestCase): def test_get_definition_directive_basic(self): directive_key = object def test_fn(): a = 1 return a ns = {} node, ctx = self.prepare(test_fn, ns) symbol_a = node.body[1].value defs, = anno.getanno(symbol_a, anno.Static.ORIG_DEFINITIONS) defs.directives[directive_key] = { 'test_arg': parser.parse_expression('foo'), 'other_arg': parser.parse_expression('bar'), } c = TestConverter(ctx) value = c.get_definition_directive(symbol_a, directive_key, 'test_arg', None) self.assertEqual(value.id, 'foo') def test_get_definition_directive_default(self): directive_key = object def test_fn(): a = 1 return a ns = {} node, ctx = self.prepare(test_fn, ns) symbol_a = node.body[1].value c = TestConverter(ctx) value = c.get_definition_directive(symbol_a, directive_key, 'test_arg', parser.parse_expression('default')) self.assertEqual(value.id, 'default') def test_get_definition_directive_multiple_consistent(self): directive_key = object def test_fn(): a = 1 if a: a = 2 return a ns = {} node, ctx = self.prepare(test_fn, ns) symbol_a = node.body[2].value defs = anno.getanno(symbol_a, anno.Static.ORIG_DEFINITIONS) defs[0].directives[directive_key] = { 'test_arg': parser.parse_expression('foo'), 'other_arg': parser.parse_expression('bar'), } defs[1].directives[directive_key] = { 'test_arg': parser.parse_expression('foo'), 'other_arg': parser.parse_expression('baz'), } c = TestConverter(ctx) value = c.get_definition_directive(symbol_a, directive_key, 'test_arg', None) self.assertEqual(value.id, 'foo') def test_get_definition_directive_multiple_inconsistent(self): directive_key = object def test_fn(): a = 1 if a: a = 2 return a ns = {} node, ctx = self.prepare(test_fn, ns) symbol_a = node.body[2].value defs = anno.getanno(symbol_a, anno.Static.ORIG_DEFINITIONS) defs[0].directives[directive_key] = { 'test_arg': parser.parse_expression('foo'), } defs[1].directives[directive_key] = { 'test_arg': parser.parse_expression('bar'), } c = TestConverter(ctx) with self.assertRaises(ValueError): c.get_definition_directive(symbol_a, directive_key, 'test_arg', None) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/core/converter_test.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities used to capture Python idioms.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function class Undefined(object): """Represents an undefined symbol in Python. This is used to reify undefined symbols, which is required to use the functional form of loops. Example: while n > 0: n = n - 1 s = n return s # Runtime error if n == 0 This is valid Python code and will not result in an error as long as n is positive. The use of this class is to stay as close to Python semantics as possible for staged code of this nature. Converted version of the above showing the possible usage of this class: s = Undefined('s') init_state = (s,) s = while_loop(cond, body, init_state) return s # s is an instance of Undefined if the loop never runs Attributes: symbol_name: Text, identifier for the undefined symbol """ def __init__(self, symbol_name): # TODO(aqj) Possibly remove this after Symbols are fully integrated. self.symbol_name = symbol_name def is_undefined(value): """Checks whether Autograph has determined that a given value is undefined. This only works in places where Autograph reifies undefined symbols. Note that if this function is passed a truly undefined symbol the call-site will raise NameError. Args: value: value to test for undefinedness Returns: Boolean, whether the input value is undefined. """ return isinstance(value, Undefined) # TODO(mdan): Refactor as a RetVal object, aggregating the value and do_return. class UndefinedReturnValue(object): """Represents a default return value from a function (None in Python).""" pass def retval(value): """Returns the actual value that a return statement should produce.""" if isinstance(value, UndefinedReturnValue): return None return value def is_undefined_return(value): """Checks whether `value` is the default return value.""" return isinstance(value, UndefinedReturnValue)
tensorflow-master
tensorflow/python/autograph/operators/special_values.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Logical boolean operators: not, and, or.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import tensor_util from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gen_math_ops def not_(a): """Functional form of "not".""" if tensor_util.is_tensor(a): return _tf_not(a) return _py_not(a) def _tf_not(a): """Implementation of the "not_" operator for TensorFlow.""" return gen_math_ops.logical_not(a) def _py_not(a): """Default Python implementation of the "not_" operator.""" return not a def and_(a, b): """Functional form of "and". Uses lazy evaluation semantics.""" a_val = a() if tensor_util.is_tensor(a_val): return _tf_lazy_and(a_val, b) return _py_lazy_and(a_val, b) def _tf_lazy_and(cond, b): """Lazy-eval equivalent of "and" for Tensors.""" # TODO(mdan): Enforce cond is scalar here? return control_flow_ops.cond(cond, b, lambda: cond) def _py_lazy_and(cond, b): """Lazy-eval equivalent of "and" in Python.""" return cond and b() def or_(a, b): """Functional form of "or". Uses lazy evaluation semantics.""" a_val = a() if tensor_util.is_tensor(a_val): return _tf_lazy_or(a_val, b) return _py_lazy_or(a_val, b) def _tf_lazy_or(cond, b): """Lazy-eval equivalent of "or" for Tensors.""" # TODO(mdan): Enforce cond is scalar here? return control_flow_ops.cond(cond, lambda: cond, b) def _py_lazy_or(cond, b): """Lazy-eval equivalent of "or" in Python.""" return cond or b() def eq(a, b): """Functional form of "equal".""" if tensor_util.is_tensor(a) or tensor_util.is_tensor(b): return _tf_equal(a, b) return _py_equal(a, b) def _tf_equal(a, b): """Overload of "equal" for Tensors.""" return gen_math_ops.equal(a, b) def _py_equal(a, b): """Overload of "equal" that falls back to Python's default implementation.""" return a == b def not_eq(a, b): """Functional form of "not-equal".""" return not_(eq(a, b))
tensorflow-master
tensorflow/python/autograph/operators/logical.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for python_lang_utils module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.operators import special_values from tensorflow.python.platform import test class SpecialValuesTest(test.TestCase): def test_undefined(self): undefined_symbol = special_values.Undefined('name') self.assertEqual(undefined_symbol.symbol_name, 'name') undefined_symbol2 = special_values.Undefined('name') self.assertNotEqual(undefined_symbol, undefined_symbol2) self.assertTrue(special_values.is_undefined(undefined_symbol)) self.assertTrue(special_values.is_undefined(undefined_symbol2)) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/operators/special_values_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Structures that allow uniform control over the dispatch process.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections # TODO(mdan): This is where macro override controls fit. class DispatchContext(collections.namedtuple( 'DispatchContext', ('options',))): """Allows passing additional parameters to the specific implementations. Attributes: options: Optional dict of extra arguments that may be required by specific implementations. """ def option(self, name): return self.options[name] NO_CTX = DispatchContext(options={})
tensorflow-master
tensorflow/python/autograph/operators/dispatch_context.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Control flow statements: loops, conditionals, etc. Note: most of these operators accept pairs of get_state/set_state functions, to capture mutations that the corresponding code blocks might make. These mutations only need to be captured when staging the control flow, and they just work when reverting to Python behavior. __Examples__ ``` while cond: self.x += i ``` When the functionalized version is executed as a Python loop, it just works: ``` def loop_body(): self.x += i # works as expected for Python loops ``` But it won't work for TF loops: ``` def loop_body(): self.x += i # self.x has the wrong value! ``` get_state/set_state allow piping the mutations through the loop variables as well, in effect changing the loop body: ``` def loop_body(self_x): self.x = self_x # self.x now has the proper value self.x += i # the original block self_x = self.x # write self.x back into the loop vars return self_x self_x = tf.while_loop(...) self.x = self_x # the result is not properly captured ``` """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.operators import py_builtins from tensorflow.python.autograph.operators import special_values from tensorflow.python.autograph.utils import ag_logging from tensorflow.python.autograph.utils import tensors from tensorflow.python.data.experimental.ops import scan_ops from tensorflow.python.data.experimental.ops import take_while_ops from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.ops import iterator_ops from tensorflow.python.framework import constant_op from tensorflow.python.framework import func_graph from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import tensor_array_ops LIMIT_PYTHON_ITERATIONS = True PYTHON_MAX_ITERATIONS = 100000000 # Fails in about one minute for empty loops. WARN_INEFFICIENT_UNROLL = True INEFFICIENT_UNROLL_MIN_ITERATIONS = 3000 INEFFICIENT_UNROLL_MIN_OPS = 1 def _disallow_undefs_into_loop(*values): """Ensures that all values in the state are defined when entering a loop.""" undefined = tuple(filter(special_values.is_undefined, values)) if undefined: raise ValueError( 'TensorFlow requires that the following symbols must be defined' ' before the loop: {}'.format(tuple(s.symbol_name for s in undefined))) for value in values: if special_values.is_undefined_return(value): # Assumption: the loop will only capture the variable which tracks the # return value if the loop contained a return statement. # TODO(mdan): This should be checked at the place where return occurs. raise ValueError( 'Return statements are not supported within a TensorFlow loop.') def for_stmt(iter_, extra_test, body, get_state, set_state, init_vars): """Functional form of a for statement. The loop operates on a state, which includes all symbols that are variant across loop iterations, excluding the iterate as well as the variables local to the loop. For example, given the loop below that calculates the geometric and arithmetic means or some numbers: geo_mean = 1 arith_mean = 0 for i in range(n): a = numbers[i] geo_mean *= a arith_mean += a The state is represented by the variables geo_mean and arith_mean. The argument for initial_state may contain the tuple (1, 0), the body will include the arguments geo_mean and arith_mean and will return a tuple representing the new values for geo_mean and respectively arith_mean. Args: iter_: The entity being iterated over. extra_test: Callable with the state as arguments, and boolean return type. An additional loop condition. body: Callable with the iterate and the state as arguments, and state as return type. The actual loop body. get_state: Additional callable which can capture additional state (such as the values of composite symbols). This is only useful when staging the loop. set_state: Additional callable which save values captured by get_state back into the Python environment. This is only useful when staging the loop. init_vars: Tuple containing the initial state. Returns: Tuple containing the final state. """ if tensor_util.is_tensor(iter_): return _known_len_tf_for_stmt(iter_, extra_test, body, get_state, set_state, init_vars) if isinstance(iter_, dataset_ops.DatasetV2): return _tf_dataset_for_stmt(iter_, extra_test, body, get_state, set_state, init_vars) if isinstance(iter_, iterator_ops.IteratorV2): return _tf_iterator_for_stmt(iter_, extra_test, body, get_state, set_state, init_vars) # Note: This experimental interface is subject to change. custom_handler = getattr(iter_, '_autograph_for_loop', None) if custom_handler is not None: # TODO(mdan): TensorFlow-specific verification - handlers should perform it. _disallow_undefs_into_loop(*init_vars) # TODO(mdan): Enable get_state/set_state separately. return custom_handler(extra_test, body, init_vars) return _py_for_stmt(iter_, extra_test, body, get_state, set_state, init_vars) def _py_for_stmt(iter_, extra_test, body, get_state, set_state, init_vars): """Overload of for_stmt that executes a Python for loop.""" del get_state, set_state state = init_vars for target in iter_: if extra_test is not None and not extra_test(*state): break state = body(target, *state) return state def _known_len_tf_for_stmt(iter_, extra_test, body, get_state, set_state, init_vars): """Overload of for_stmt that iterates over TF entities that admit a length.""" _disallow_undefs_into_loop(*init_vars) n = py_builtins.len_(iter_) # TODO(b/117628877): Revisit performance once XLA has the necessary support. # Note: using a TensorArray creates an extra copy, but can calculate # gradients more efficiently than StridedSlice. ta = tensor_array_ops.TensorArray(iter_.dtype, size=n) iter_ = ta.unstack(iter_) def while_body(iterate_index, *loop_vars): iterate = iter_.read(iterate_index) new_vars = body(iterate, *loop_vars) loop_vars = (iterate_index + 1,) if new_vars: loop_vars += new_vars return loop_vars def while_cond(iterate_index, *loop_vars): if extra_test is not None: return control_flow_ops.cond( iterate_index < n, lambda: extra_test(*loop_vars), lambda: False) return iterate_index < n results = _tf_while_stmt( while_cond, while_body, get_state, set_state, init_vars=(0,) + init_vars, opts=dict(maximum_iterations=n)) # Dropping the iteration index because it's not syntactically visible. # TODO(mdan): Don't. if isinstance(results, (tuple, list)): assert len(results) >= 1 # Has at least the iterate. if len(results) > 1: results = results[1:] else: results = () return results def _tf_iterator_for_stmt(itr, extra_test, body, get_state, set_state, init_vars): """Overload of for_stmt that iterates over TF Iterators. See for_loop.""" _disallow_undefs_into_loop(*init_vars) def while_body_actual(opt_iterate, *loop_vars): new_vars = body(opt_iterate.get_value(), *loop_vars) # TODO(mdan): Fix this inconsistency in the converter. if new_vars is None: new_vars = () return new_vars def while_body(has_next, loop_vars): """Main loop body.""" opt_iterate = iterator_ops.get_next_as_optional(itr) has_next = opt_iterate.has_value() if not init_vars: # cond_v2 requires at least one state tensor in V1. dummy_state = (constant_op.constant(()),) else: dummy_state = () # TODO(mdan): If tf.while_loop supported Optional, this could be avoided. new_vars = control_flow_ops.cond( has_next, lambda: dummy_state + while_body_actual(opt_iterate, *loop_vars), lambda: dummy_state + loop_vars, ) if dummy_state: new_vars = new_vars[1:] return has_next, new_vars def while_cond(has_next, loop_vars): if extra_test is not None: return control_flow_ops.cond( has_next, lambda: extra_test(*loop_vars), lambda: False) return has_next _, final_vars = _tf_while_stmt( while_cond, while_body, get_state, set_state, init_vars=(True, init_vars), opts=None) return final_vars def _tf_dataset_for_stmt(ds, extra_test, body, get_state, set_state, init_vars): """Overload of for_stmt that iterates over TF Datasets.""" _disallow_undefs_into_loop(*init_vars) if extra_test is not None: assert init_vars, 'Lowering should always add state.' return _dataset_for_stmt_with_extra_test(ds, extra_test, body, get_state, set_state, init_vars) return _dataset_for_stmt_no_extra_test(ds, body, get_state, set_state, init_vars) def _dataset_for_stmt_with_extra_test(ds, extra_test, body, get_state, set_state, init_vars): """Overload of _dataset_for_stmt with early stopping. See for_stmt.""" # TODO(mdan): Simplify this - following it is extremely difficult. def scan_body(aug_vars, iterate): """The main loop body wrapper. Only calculates the stop condition.""" loop_vars, state = aug_vars def true_fn(): set_state(state) outputs = body(iterate, *loop_vars) return outputs, get_state() extra_cond = extra_test(*loop_vars) new_vars, new_state = control_flow_ops.cond( extra_cond, true_fn, lambda: (loop_vars, state)) scan_outputs = new_vars, new_state, extra_cond # Note: new_aug_vars is the actual state of scan; scan_outputs is its output # (hence the redundancy). # get_state will pull any mutations that body may have made. new_aug_vars = new_vars, new_state return new_aug_vars, scan_outputs def take_while_predicate(unused_loop_vars, unused_state, extra_cond): return extra_cond def reduce_body(unused_aug_vars, scan_outputs): output_aug_vars, output_state, extra_cond = scan_outputs del extra_cond return output_aug_vars, output_state init_state = get_state() aug_vars = init_vars, init_state ds = ds.apply(scan_ops.scan(aug_vars, scan_body)) ds = ds.apply(take_while_ops.take_while(take_while_predicate)) final_aug_vars = ds.reduce(aug_vars, reduce_body) final_vars, final_state = final_aug_vars set_state(final_state) return final_vars def _dataset_for_stmt_no_extra_test(ds, body, get_state, set_state, init_vars): """Overload of _dataset_for_stmt without early stopping. See for_stmt.""" init_state = get_state() assert isinstance(init_vars, tuple) assert isinstance(init_state, tuple) # Workaround for Dataset.reduce not allowing empty state tensors - create # a dummy state variable that remains unused. # TODO(mdan): reduce should allow and match empty structures. no_vars = not init_vars no_state = not init_state if no_vars: init_vars = (constant_op.constant(0),) if no_state: init_state = (constant_op.constant(0),) def reduce_body(aug_vars, iterate): """The main loop body wrapper.""" loop_vars, state = aug_vars if not no_state: set_state(state) if no_vars: body(iterate) new_vars = loop_vars else: new_vars = body(iterate, *loop_vars) if no_state: new_state = state else: new_state = get_state() return new_vars, new_state aug_vars = init_vars, get_state() final_vars, final_state = ds.reduce(aug_vars, reduce_body) set_state(final_state) if no_vars: return () return final_vars def while_stmt(test, body, get_state, set_state, init_vars, opts=None): """Functional form of a while statement. The loop operates on a so-called state, which includes all symbols that are variant across loop iterations. In what follows we refer to state as either a tuple of entities that represent an actual state, or a list of arguments of the corresponding types. Args: test: Callable with the state as arguments, and boolean return type. The loop condition. body: Callable with the state as arguments, and state as return type. The actual loop body. get_state: Additional callable which can capture additional state (such as the values of composite symbols). This is only useful when staging the loop. set_state: Additional callable which save values captured by get_state back into the Python environment. This is only useful when staging the loop. init_vars: Tuple containing the initial state. opts: Optional dict of extra loop parameters. Returns: Tuple containing the final state. """ # Evaluate the initial test once in order to do the dispatch. The evaluation # is isolated to minimize unwanted side effects. # TODO(mdan): Do a full iteration - some state types might lower to Tensor. with func_graph.FuncGraph('tmp').as_default(): init_test = test(*init_vars) # TensorFlow: Multiple evaluations are acceptable in this case, so we're fine # with the re-evaluation of `test` that `_tf_while_stmt` will make. if tensors.is_dense_tensor(init_test): return _tf_while_stmt(test, body, get_state, set_state, init_vars, opts) # Normal Python: We already consumed one evaluation of `test`; consistently, # unroll one iteration before dispatching to a normal loop. # TODO(mdan): Push the "init_test" value via opts into _py_while_stmt? if not init_test: return init_vars init_vars = body(*init_vars) return _py_while_stmt(test, body, get_state, set_state, init_vars, opts) def _tf_while_stmt(test, body, get_state, set_state, init_vars, opts): """Overload of while_stmt that stages a TF while_stmt.""" _disallow_undefs_into_loop(*init_vars) if opts is None: opts = {} # TODO(mdan): Simplify this. loop_vars_slice = slice(len(init_vars)) state_slice = slice(len(init_vars), None) def aug_test(*aug_loop_vars): state = aug_loop_vars[state_slice] set_state(state) return test(*aug_loop_vars[loop_vars_slice]) def aug_body(*aug_loop_vars): state = aug_loop_vars[state_slice] set_state(state) loop_vars = body(*aug_loop_vars[loop_vars_slice]) return loop_vars + get_state() # Non-v2 while_loop unpacks the results when there is only one return value. # This enforces consistency across versions. opts['return_same_structure'] = True aug_init_vars = init_vars + get_state() final_aug_vars = control_flow_ops.while_loop(aug_test, aug_body, aug_init_vars, **opts) final_state = final_aug_vars[state_slice] set_state(final_state) return final_aug_vars[loop_vars_slice] class _PythonLoopChecker(object): """Verifies Python loops for TF-specific limits.""" def __init__(self): self.iterations = 0 self.check_inefficient_unroll = WARN_INEFFICIENT_UNROLL # Triggered when we decided to test the op counts. self.check_op_count_after_iteration = False def _get_ops(self): return ops.get_default_graph().get_operations() def _check_unroll_limits(self): if LIMIT_PYTHON_ITERATIONS and self.iterations > PYTHON_MAX_ITERATIONS: raise ValueError('iteration limit exceeded') def _stop_checking_inefficient_unroll(self): self.check_inefficient_unroll = False self.ops_before_iteration = None def _verify_ineffcient_unroll(self): """Checks for possibly-inefficient creation of ops in a Python loop.""" assert self.ops_before_iteration is not None ops_after_iteration = self._get_ops() new_ops = tuple( op for op in ops_after_iteration if op not in self.ops_before_iteration) if len(new_ops) < INEFFICIENT_UNROLL_MIN_OPS: return False # TODO(mdan): Add location information. ag_logging.warn( 'TensorFlow ops are being created in a Python loop with large number' ' of iterations. This can lead to slow startup. Did you mean to use a' ' TensorFlow loop? For example, `while True:` is a Python loop, and' ' `while tf.constant(True):` is a TensorFlow loop. The following' ' ops were created after iteration %s: %s', self.iterations, new_ops) return True def before_iteration(self): """Called before each iteration in a Python loop.""" if (self.check_inefficient_unroll and self.iterations > INEFFICIENT_UNROLL_MIN_ITERATIONS): self.ops_before_iteration = self._get_ops() self.check_op_count_after_iteration = True def after_iteration(self): """Called after each iteration in a Python loop.""" self.iterations += 1 self._check_unroll_limits() if self.check_inefficient_unroll and self.check_op_count_after_iteration: did_warn = self._verify_ineffcient_unroll() if did_warn: self._stop_checking_inefficient_unroll() # Only warn once. elif self.iterations > INEFFICIENT_UNROLL_MIN_ITERATIONS + 3: # Once deciding to check the op counts, only do it for a few iterations. self._stop_checking_inefficient_unroll() def _py_while_stmt(test, body, get_state, set_state, init_vars, opts): """Overload of while_stmt that executes a Python while loop.""" del opts, get_state, set_state if __debug__: checker = _PythonLoopChecker() loop_vars = init_vars while test(*loop_vars): if __debug__: checker.before_iteration() loop_vars = body(*loop_vars) if __debug__: checker.after_iteration() return loop_vars def if_stmt(cond, body, orelse, get_state, set_state): """Functional form of an if statement. Args: cond: Boolean. body: Callable with no arguments, and outputs of the positive (if) branch as return type. orelse: Callable with no arguments, and outputs of the negative (else) branch as return type. get_state: Function that returns a tuple containing the values of all composite symbols modified within the conditional. This allows access to state that branches may mutate through side effects. This function is not needed and should not be called when dispatching to code matching Python's default semantics. This is useful for checkpointing to avoid unintended side-effects when staging requires evaluating all code-paths. set_state: Function to set the values of all composite symbols modified within the conditional. This is the complement to get_state, used to restore checkpointed values. The single argument a tuple containing values for each composite symbol that may be modified in a branch of the conditional. The is usually the result of a call to get_state. Returns: Tuple containing the statement outputs. """ # Note: tf.cond doesn't support SparseTensor. if tensors.is_dense_tensor(cond): return tf_if_stmt(cond, body, orelse, get_state, set_state) else: return _py_if_stmt(cond, body, orelse) def tf_if_stmt(cond, body, orelse, get_state, set_state): """Overload of if_stmt that stages a TF cond.""" body = _wrap_disallow_undefs_from_cond(body, branch_name='if') orelse = _wrap_disallow_undefs_from_cond(orelse, branch_name='else') body = _isolate_state(body, get_state, set_state) orelse = _isolate_state(orelse, get_state, set_state) # `state` currently includes the values of any composite symbols (e.g. `a.b`) # composites modified by the loop. `final_vars` includes the values of basic # symbols (e.g. `a`) which cannot be passed by reference and must be returned. # See _isolate_state. # TODO(mdan): We should minimize calls to get/set_state. final_vars, final_state = control_flow_ops.cond(cond, body, orelse) set_state(final_state) return final_vars def _isolate_state(func, get_state, set_state): """Wraps func to (best-effort) isolate state mutations that func may do. The simplest example of state mutation is mutation of variables (via e.g. attributes), or modification of globals. This allows us to more safely execute this function without worrying about side effects when the function wasn't normally expected to execute. For example, staging requires that the function is executed ahead of time, and we need to ensure its effects are not observed during normal execution. Args: func: () -> Any get_state: () -> Any, returns the current state set_state: (Any) -> None, resets the state to the specified values. Typically the result of an earlier call to `get_state`. Returns: Tuple[Any, Any], where the first element is the return value of `func`, and the second is the final state values. """ def wrapper(): init_state = get_state() new_vars = func() # TODO(mdan): These should be copies, lest set_state might affect them. new_state = get_state() set_state(init_state) return new_vars, new_state return wrapper def _wrap_disallow_undefs_from_cond(func, branch_name): """Wraps conditional branch to disallow returning undefined symbols.""" def wrapper(): """Calls function and raises an error if undefined symbols are returned.""" results = func() if isinstance(results, tuple): results_tuple = results else: results_tuple = results, undefined = tuple(filter(special_values.is_undefined, results_tuple)) if undefined: raise ValueError( 'The following symbols must also be initialized in the {} branch: {}.' ' Alternatively, you may initialize them before the if' ' statement.'.format(branch_name, tuple(s.symbol_name for s in undefined))) for result in results_tuple: if special_values.is_undefined_return(result): raise ValueError( 'A value must also be returned from the {} branch. If a value is ' 'returned from one branch of a conditional a value must be ' 'returned from all branches.'.format(branch_name)) return results return wrapper def _py_if_stmt(cond, body, orelse): """Overload of if_stmt that executes a Python if statement.""" return body() if cond else orelse()
tensorflow-master
tensorflow/python/autograph/operators/control_flow.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """This module implements operators that AutoGraph overloads. Note that "operator" is used loosely here, and includes control structures like conditionals and loops, implemented in functional form, using for example closures for the body. """ # Naming conventions: # * operator names match the name usually used for the respective Python # idiom; examples: for_stmt, list_append # * operator arguments match either of: # - the corresponding Python AST attribute (e.g. the condition of an if # statement is called test) if the operator represents an AST construct # - the names used in the Python docs, if the operator is a function (e.g. # list_ and x for append, see # https://docs.python.org/3.7/tutorial/datastructures.html) # # All operators may accept a final argument named "opts", of a type that # subclasses namedtuple and contains any arguments that are only required # for some specializations of the operator. from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.operators.control_flow import for_stmt from tensorflow.python.autograph.operators.control_flow import if_stmt from tensorflow.python.autograph.operators.control_flow import while_stmt from tensorflow.python.autograph.operators.data_structures import list_append from tensorflow.python.autograph.operators.data_structures import list_pop from tensorflow.python.autograph.operators.data_structures import list_stack from tensorflow.python.autograph.operators.data_structures import ListPopOpts from tensorflow.python.autograph.operators.data_structures import ListStackOpts from tensorflow.python.autograph.operators.data_structures import new_list from tensorflow.python.autograph.operators.exceptions import assert_stmt from tensorflow.python.autograph.operators.logical import and_ from tensorflow.python.autograph.operators.logical import eq from tensorflow.python.autograph.operators.logical import not_ from tensorflow.python.autograph.operators.logical import not_eq from tensorflow.python.autograph.operators.logical import or_ from tensorflow.python.autograph.operators.py_builtins import float_ from tensorflow.python.autograph.operators.py_builtins import int_ from tensorflow.python.autograph.operators.py_builtins import len_ from tensorflow.python.autograph.operators.py_builtins import print_ from tensorflow.python.autograph.operators.py_builtins import range_ from tensorflow.python.autograph.operators.slices import get_item from tensorflow.python.autograph.operators.slices import GetItemOpts from tensorflow.python.autograph.operators.slices import set_item from tensorflow.python.autograph.operators.special_values import is_undefined from tensorflow.python.autograph.operators.special_values import is_undefined_return from tensorflow.python.autograph.operators.special_values import retval from tensorflow.python.autograph.operators.special_values import Undefined from tensorflow.python.autograph.operators.special_values import UndefinedReturnValue
tensorflow-master
tensorflow/python/autograph/operators/__init__.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for logical module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.operators import logical from tensorflow.python.framework import constant_op from tensorflow.python.framework import test_util from tensorflow.python.platform import test class LogicalOperatorsTest(test.TestCase): def assertNotCalled(self): self.fail('this should not be called') def _tf_true(self): return constant_op.constant(True) def _tf_false(self): return constant_op.constant(False) def test_and_python(self): self.assertTrue(logical.and_(lambda: True, lambda: True)) self.assertTrue(logical.and_(lambda: [1], lambda: True)) self.assertListEqual(logical.and_(lambda: True, lambda: [1]), [1]) self.assertFalse(logical.and_(lambda: False, lambda: True)) self.assertFalse(logical.and_(lambda: False, self.assertNotCalled)) @test_util.run_deprecated_v1 def test_and_tf(self): with self.cached_session() as sess: t = logical.and_(self._tf_true, self._tf_true) self.assertEqual(self.evaluate(t), True) t = logical.and_(self._tf_true, lambda: True) self.assertEqual(self.evaluate(t), True) t = logical.and_(self._tf_false, lambda: True) self.assertEqual(self.evaluate(t), False) # TODO(mdan): Add a test for ops with side effects. def test_or_python(self): self.assertFalse(logical.or_(lambda: False, lambda: False)) self.assertFalse(logical.or_(lambda: [], lambda: False)) self.assertListEqual(logical.or_(lambda: False, lambda: [1]), [1]) self.assertTrue(logical.or_(lambda: False, lambda: True)) self.assertTrue(logical.or_(lambda: True, self.assertNotCalled)) @test_util.run_deprecated_v1 def test_or_tf(self): with self.cached_session() as sess: t = logical.or_(self._tf_false, self._tf_true) self.assertEqual(self.evaluate(t), True) t = logical.or_(self._tf_false, lambda: True) self.assertEqual(self.evaluate(t), True) t = logical.or_(self._tf_true, lambda: True) self.assertEqual(self.evaluate(t), True) # TODO(mdan): Add a test for ops with side effects. def test_not_python(self): self.assertFalse(logical.not_(True)) self.assertFalse(logical.not_([1])) self.assertTrue(logical.not_([])) def test_not_tf(self): with self.cached_session() as sess: t = logical.not_(self._tf_false()) self.assertEqual(self.evaluate(t), True) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/operators/logical_test.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for special symbol handling.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.operators import special_values from tensorflow.python.autograph.operators import symbols from tensorflow.python.platform import test Undefined = special_values.Undefined AttributeAccessSymbol = symbols.AttributeAccessSymbol SubscriptSymbol = symbols.SubscriptSymbol ValueSymbol = symbols.ValueSymbol class SymbolsTest(test.TestCase): def test_value_symbol_returns_value(self): a = 42 a_symbol = ValueSymbol('a', a) self.assertEqual(a_symbol.maybe_compute_value(), a) self.assertEqual(a_symbol.name, 'a') def test_attribute_access_missing_attribute(self): class Foo(object): pass a = Foo() a_symbol = ValueSymbol('a', a) a_b_symbol = AttributeAccessSymbol(a_symbol, 'b') self.assertEqual(a_symbol.maybe_compute_value(), a) self.assertIsInstance(a_b_symbol.maybe_compute_value(), Undefined) self.assertEqual(a_b_symbol.maybe_compute_value().symbol_name, 'a.b') def test_attribute_access_undefined_target(self): a = Undefined('a') a_symbol = ValueSymbol('a', a) a_b_symbol = AttributeAccessSymbol(a_symbol, 'b') self.assertEqual(a_symbol.maybe_compute_value(), a) self.assertIsInstance(a_b_symbol.maybe_compute_value(), Undefined) self.assertEqual(a_b_symbol.maybe_compute_value().symbol_name, 'a.b') def test_attribute_access_basic(self): class Foo(object): def __init__(self): self.b = 'this is an attribute' a = Foo() a_symbol = ValueSymbol('a', a) a_b_symbol = AttributeAccessSymbol(a_symbol, 'b') self.assertEqual(a_symbol.maybe_compute_value(), a) self.assertEqual(a_b_symbol.maybe_compute_value(), a.b) def test_item_access_undefined_index(self): class Foo(object): def __getitem__(self, key): return 'this is an item' a = Foo() b = Undefined('b') a_symbol = ValueSymbol('a', a) b_symbol = ValueSymbol('b', b) a_b_symbol = SubscriptSymbol(a_symbol, b_symbol) self.assertEqual(a_symbol.maybe_compute_value(), a) self.assertEqual(b_symbol.maybe_compute_value(), b) self.assertIsInstance(a_b_symbol.maybe_compute_value(), Undefined) self.assertEqual(a_b_symbol.maybe_compute_value().symbol_name, 'a[b]') def test_item_access_no_getitem(self): class Foo(object): pass a = Foo() b = 42 a_symbol = ValueSymbol('a', a) b_symbol = ValueSymbol('b', b) a_b_symbol = SubscriptSymbol(a_symbol, b_symbol) self.assertEqual(a_symbol.maybe_compute_value(), a) self.assertEqual(b_symbol.maybe_compute_value(), b) self.assertIsInstance(a_b_symbol.maybe_compute_value(), Undefined) self.assertEqual(a_b_symbol.maybe_compute_value().symbol_name, 'a[b]') def test_item_access_undefined_root(self): a = Undefined('a') b = 42 a_symbol = ValueSymbol('a', a) b_symbol = ValueSymbol('b', b) a_b_symbol = SubscriptSymbol(a_symbol, b_symbol) self.assertEqual(a_symbol.maybe_compute_value(), a) self.assertEqual(b_symbol.maybe_compute_value(), b) self.assertIsInstance(a_b_symbol.maybe_compute_value(), Undefined) self.assertEqual(a_b_symbol.maybe_compute_value().symbol_name, 'a[b]') def test_item_access_basic(self): class Foo(object): def __getitem__(self, key): return 'this is an item' a = Foo() b = 42 a_symbol = ValueSymbol('a', a) b_symbol = ValueSymbol('b', b) a_b_symbol = SubscriptSymbol(a_symbol, b_symbol) self.assertEqual(a_symbol.maybe_compute_value(), a) self.assertEqual(b_symbol.maybe_compute_value(), b) self.assertEqual(a_b_symbol.maybe_compute_value(), a[b]) def test_item_access_after_attribute_access(self): class Foo(object): def __getitem__(self, key): return 'this is an item' class Bar(object): def __init__(self): self.b = Foo() a = Bar() c = 42 a_symbol = ValueSymbol('a', a) c_symbol = ValueSymbol('c', c) a_b_symbol = AttributeAccessSymbol(a_symbol, 'b') a_b_c_symbol = SubscriptSymbol(a_b_symbol, c_symbol) self.assertEqual(a_symbol.maybe_compute_value(), a) self.assertEqual(c_symbol.maybe_compute_value(), c) self.assertEqual(a_b_symbol.maybe_compute_value(), a.b) self.assertEqual(a_b_c_symbol.maybe_compute_value(), a.b[c]) def test_attribute_access_after_item_access(self): class Bar(object): def __init__(self): self.c = object() item = Bar() class Foo(object): def __getitem__(self, key): return item a = Foo() b = 42 a_symbol = ValueSymbol('a', a) b_symbol = ValueSymbol('b', b) a_b_symbol = SubscriptSymbol(a_symbol, b_symbol) a_b_c_symbol = AttributeAccessSymbol(a_b_symbol, 'c') self.assertEqual(a_symbol.maybe_compute_value(), a) self.assertEqual(b_symbol.maybe_compute_value(), b) self.assertEqual(a_b_symbol.maybe_compute_value(), a[b]) self.assertEqual(a_b_c_symbol.maybe_compute_value(), a[b].c) def test_item_access_after_item_access(self): class Bar(object): def __getitem__(self, key): return 'this is an item' item = Bar() class Foo(object): def __getitem__(self, key): return item a = Foo() b = 42 c = 43 a_symbol = ValueSymbol('a', a) b_symbol = ValueSymbol('b', b) c_symbol = ValueSymbol('b', c) a_b_symbol = SubscriptSymbol(a_symbol, b_symbol) a_b_c_symbol = SubscriptSymbol(a_b_symbol, c_symbol) self.assertEqual(a_symbol.maybe_compute_value(), a) self.assertEqual(b_symbol.maybe_compute_value(), b) self.assertEqual(a_b_symbol.maybe_compute_value(), a[b]) self.assertEqual(a_b_c_symbol.maybe_compute_value(), a[b][c]) def test_attribute_access_after_attribute_access(self): class Bar(object): def __init__(self): self.c = object() class Foo(object): def __init__(self): self.b = Bar() a = Foo() a_symbol = ValueSymbol('a', a) a_b_symbol = AttributeAccessSymbol(a_symbol, 'b') a_b_c_symbol = AttributeAccessSymbol(a_b_symbol, 'c') self.assertEqual(a_symbol.maybe_compute_value(), a) self.assertEqual(a_b_symbol.maybe_compute_value(), a.b) self.assertEqual(a_b_c_symbol.maybe_compute_value(), a.b.c) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/operators/symbols_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Abstract representation of composite symbols that can used in staging code. This provides a way to checkpoint the values of symbols that may be undefined entering staged control flow. This checkpointing is necessary to prevent some unintended side-effects. For example checkpointing prevents side-effects in one branch of a conditional from leaking into another. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.operators import special_values is_undefined = special_values.is_undefined Undefined = special_values.Undefined class Symbol(object): """Representation of a simple or composite Python symbol. Subclasses should implement `maybe_compute_value(self)` that returns the value corresponding to the symbol or Undefined if no such value exists. """ def __init__(self, name): self.name = name class ValueSymbol(Symbol): """Representation of a simple Python symbol with a concrete value. This includes variables and literals. Since we are reifying undefined symbols `Undefined` is also a valid value. """ def __init__(self, name, value): super(ValueSymbol, self).__init__(name) self.value = value def maybe_compute_value(self): return self.value class AttributeAccessSymbol(Symbol): """Representation of Python attribute access e.g. `a.b`.""" def __init__(self, parent_symbol, attr_name): super(AttributeAccessSymbol, self).__init__( parent_symbol.name + '.' + attr_name) self.attr_name = attr_name self.parent_symbol = parent_symbol def maybe_compute_value(self): """Compute the value corresponding to the attribute access or `Undefined`. This will be `Undefined` if no such value exists either because there is no such attribute or if the base is itself undefined. Returns: value corresponding to the attribute access or `Undefined` """ parent_value = self.parent_symbol.maybe_compute_value() if (is_undefined(parent_value) or getattr(parent_value, self.attr_name, None) is None): return Undefined(self.name) else: return parent_value.__getattribute__(self.attr_name) class SubscriptSymbol(Symbol): """Representation of Python subscript access e.g. `a[b]`.""" def __init__(self, parent_symbol, index_symbol): super(SubscriptSymbol, self).__init__( parent_symbol.name + '[' + index_symbol.name + ']') self.index_symbol = index_symbol self.parent_symbol = parent_symbol def maybe_compute_value(self): """Compute the value corresponding to the subscript access or `Undefined`. This will be `Undefined` if no such value exists either because there is no element corresponding to the given subscript or if the base itself is not defined. Returns: value corresponding to the subscript access or `Undefined` """ parent_value = self.parent_symbol.maybe_compute_value() index_value = self.index_symbol.maybe_compute_value() if is_undefined(parent_value) or is_undefined(index_value): return Undefined(self.name) else: try: return parent_value[index_value] except (IndexError, KeyError, TypeError): # Reify the lack of an object for the given index/key # This allows us to define them later without regret return Undefined(self.name)
tensorflow-master
tensorflow/python/autograph/operators/symbols.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Operators corresponding to Python builtin functions. List of built-in functions: https://docs.python.org/3/library/functions.html """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import inspect import six from tensorflow.python.autograph.utils import py_func from tensorflow.python.autograph.utils import tensors from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gen_parsing_ops from tensorflow.python.ops import gen_string_ops from tensorflow.python.ops import list_ops from tensorflow.python.ops import math_ops UNSPECIFIED = object() def overload_of(f): if f in SUPPORTED_BUILTINS: return BUILTIN_FUINCTIONS_MAP[f.__name__] return f def eval_in_original_context(f, args, caller_level_delta): """Executes the eval function with the user-specified globals/locals.""" ctx_frame = inspect.currentframe() for _ in range(caller_level_delta + 1): ctx_frame = ctx_frame.f_back args = ( args[0], ctx_frame.f_globals if len(args) < 2 else args[1], ctx_frame.f_locals if len(args) < 3 else args[2], ) return f(*args) def abs_(x): if tensor_util.is_tensor(x): return _tf_abs(x) return _py_abs(x) def _tf_abs(x): return math_ops.abs(x) def _py_abs(x): return abs(x) def float_(x=0): if tensor_util.is_tensor(x): return _tf_float(x) return _py_float(x) def _tf_float(x): # TODO(mdan): We shouldn't assume float32. if x.dtype == dtypes.string: return gen_parsing_ops.string_to_number(x, out_type=dtypes.float32) return math_ops.cast(x, dtype=dtypes.float32) def _py_float(x): return float(x) def int_(x=0, base=UNSPECIFIED): if tensor_util.is_tensor(x): return _tf_int(x, base) return _py_int(x, base) def _tf_int(x, base): if base not in (10, UNSPECIFIED): raise NotImplementedError('base {} not supported for int'.format(base)) # TODO(mdan): We shouldn't assume int32. if x.dtype == dtypes.string: return gen_parsing_ops.string_to_number(x, out_type=dtypes.int32) return math_ops.cast(x, dtype=dtypes.int32) def _py_int(x, base): if base is UNSPECIFIED: return int(x) return int(x, base) def len_(s): if tensors.is_tensor_array(s): return _tf_tensor_array_len(s) elif tensors.is_tensor_list(s): return _tf_tensor_list_len(s) elif tensor_util.is_tensor(s): return _tf_tensor_len(s) return _py_len(s) def _tf_tensor_array_len(s): return s.size() def _tf_tensor_list_len(s): return list_ops.tensor_list_length(s) def _tf_tensor_len(s): """Overload of len_ for Tensor arguments.""" # Statically shaped tensors: length is known ahead of time. if s.shape.ndims and s.shape.dims[0].value is not None: return s.shape.dims[0].value # Static shape of unknown dimensions: use dynamic shape but statically # chech that it's a scalar. shape = array_ops.shape(s) assert shape.shape, 'shape tensor of zero size? {}'.format(shape) if shape.shape[0] == 0: raise ValueError( 'len requires a non-scalar tensor, got one of shape {}'.format(shape)) if shape.shape.dims[0].value is not None: return array_ops.shape(s)[0] # Fully dynamic shape: use ops. rank = array_ops.rank(s) def raise_zero_rank_error(): msg = gen_string_ops.string_join( ['len requires non-zero rank, got ', gen_string_ops.as_string(rank)]) with ops.control_dependencies([control_flow_ops.Assert(False, [msg])]): return constant_op.constant(0, dtype=dtypes.int32) return control_flow_ops.cond(rank > 0, lambda: array_ops.shape(s)[0], raise_zero_rank_error) def _py_len(s): return len(s) def print_(*objects, **kwargs): """Overload of the print builtin.""" # Note: Python 2.6 doesn't support explicit keywords after starargs. unknown_kwargs = tuple( set(kwargs.keys()) - set(('sep', 'end', 'file', 'flush'))) if unknown_kwargs: raise ValueError('invalid keyword arguments: {}'.format(unknown_kwargs)) # TODO(mdan): Use next.flatten(objects) instead? if any(tensor_util.is_tensor(o) for o in objects): # TODO(mdan): use tf.print instead. return _tf_py_func_print(objects, kwargs) else: _py_print(*objects, **kwargs) def _py_print(*objects, **kwargs): print(*objects, **kwargs) def _tf_py_func_print(objects, kwargs): """Overload of print_ as a py_func implementation.""" override_kwargs = {k: v for k, v in kwargs.items() if v is not UNSPECIFIED} if 'flush' not in override_kwargs: # Defaulting to flushing the console in graph mode, which helps reduce # garbled output in IPython. override_kwargs['flush'] = True def print_wrapper(*vals): vals = tuple(v.numpy() if tensor_util.is_tensor(v) else v for v in vals) if six.PY3: # TensorFlow doesn't seem to generate Unicode when passing strings to # py_func. This causes the print to add a "b'" wrapper to the output, # which is probably never what you want. vals = tuple( v.decode('utf-8') if isinstance(v, bytes) else v for v in vals) six.print_(*vals, **override_kwargs) return py_func.wrap_py_func( print_wrapper, None, objects, use_dummy_return=True) def range_(start_or_stop, stop=UNSPECIFIED, step=UNSPECIFIED): if any(tensor_util.is_tensor(s) for s in (start_or_stop, stop, step)): return _tf_range(start_or_stop, stop, step) return _py_range(start_or_stop, stop, step) def _tf_range(start_or_stop, stop, step): """Overload of range_ that generates a TF range tensor.""" # Note: for static inputs (e.g. constants), tf.range errors out at graph # construction time, instead of returning an empty tensor. Preventing the # graph construction error aligns the semantics with Python. # TODO(mdan): We should optimize this when a full tensor is not required. if step is not UNSPECIFIED: # TODO(mdan): Add argument coercion similar to other cases. return math_ops.range(start_or_stop, stop, step) if stop is not UNSPECIFIED: stop = math_ops.maximum(start_or_stop, stop) return math_ops.range(start_or_stop, stop) start_or_stop = math_ops.maximum(start_or_stop, 0) return math_ops.range(start_or_stop) def _py_range(start_or_stop, stop, step): if step is not UNSPECIFIED: return range(start_or_stop, stop, step) if stop is not UNSPECIFIED: return range(start_or_stop, stop) return range(start_or_stop) SUPPORTED_BUILTINS = (abs, float, int, len, print, range) if six.PY2: SUPPORTED_BUILTINS += (xrange,) BUILTIN_FUINCTIONS_MAP = { 'abs': abs_, 'float': float_, 'int': int_, 'len': len_, 'print': print_, 'range': range_, # TODO(mdan): This might make more sense as tf.data.range. 'xrange': range_, }
tensorflow-master
tensorflow/python/autograph/operators/py_builtins.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for control_flow module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import re import sys import six from tensorflow.python.autograph.operators import control_flow from tensorflow.python.autograph.utils import ag_logging from tensorflow.python.data.ops import dataset_ops from tensorflow.python.eager import def_function from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import gen_math_ops from tensorflow.python.ops import variables from tensorflow.python.platform import test class ForLoopTest(test.TestCase): def test_tensor(self): with ops.Graph().as_default(): s = control_flow.for_stmt( constant_op.constant([1, 2, 3, 4]), extra_test=lambda s: True, body=lambda i, s: (s * 10 + i,), get_state=lambda: (), set_state=lambda _: None, init_vars=(0,)) self.assertEqual(self.evaluate(s), (1234,)) def test_tensor_with_extra_test_only_python_state(self): class MutableObject(object): field_1 = constant_op.constant(0, dtype=dtypes.int32) field_2 = constant_op.constant(1, dtype=dtypes.int32) state = MutableObject() def get_state(): return (state.field_1, state.field_2) def set_state(new_state): state.field_1, state.field_2 = new_state def body(i): state.field_1 += i state.field_2 *= i return () control_flow.for_stmt( iter_=constant_op.constant([1, 2, 3, 4]), body=body, extra_test=lambda: state.field_1 < 6, get_state=get_state, set_state=set_state, init_vars=()) self.assertEqual(self.evaluate(state.field_1), 6) self.assertEqual(self.evaluate(state.field_2), 6) def test_python(self): s = control_flow.for_stmt( range(5), extra_test=lambda s: True, body=lambda i, s: (s * 10 + i,), get_state=None, set_state=None, init_vars=(0,)) self.assertEqual(s, (1234,)) def test_tf_dataset(self): with ops.Graph().as_default(): s = control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=None, body=lambda i, s: (s * 10 + i,), get_state=lambda: (), set_state=lambda _: None, init_vars=(constant_op.constant(0, dtype=dtypes.int64),)) self.assertEqual(self.evaluate(s), (1234,)) def test_dataset_with_extra_test(self): s = control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=lambda s: s < 3, body=lambda i, s: (s + i,), get_state=lambda: (), set_state=lambda _: None, init_vars=(constant_op.constant(0, dtype=dtypes.int64),)) self.assertEqual(self.evaluate(s), (3,)) def test_dataset_with_extra_test_and_state(self): state = [constant_op.constant(0, dtype=dtypes.int64)] def get_state(): return (state[0],) def set_state(new_state): state[0], = new_state def body(i, s): state[0] += i return (s + i,) s = control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=lambda s: s < 3, body=body, get_state=get_state, set_state=set_state, init_vars=(constant_op.constant(0, dtype=dtypes.int64),)) self.assertEqual(self.evaluate(s), (3,)) self.assertEqual(self.evaluate(state[0]), (3,)) def test_dataset_with_extra_test_no_extra_iterations(self): def guarded_body(i, s): with ops.control_dependencies((control_flow_ops.Assert(i < 3, (i,)),)): return s + i, s = control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=lambda s: s < 3, body=guarded_body, get_state=lambda: (), set_state=lambda _: None, init_vars=(constant_op.constant(0, dtype=dtypes.int64),)) self.assertEqual(self.evaluate(s), (3,)) @test_util.run_v2_only def test_tf_dataset_no_loop_vars(self): v = variables.Variable(0, dtype=dtypes.int64) self.evaluate(v.initializer) def stateless_with_side_effects(i): v.assign(v.read_value() * 10 + i) # function is important here, because ops test for its presence. @def_function.function(autograph=False) def test_fn(): control_flow.for_stmt( dataset_ops.Dataset.range(5), extra_test=None, body=stateless_with_side_effects, get_state=lambda: (), set_state=lambda _: None, init_vars=()) test_fn() self.assertEqual(self.evaluate(v.read_value()), 1234) def test_tf_iterator(self): # graph-mode iterators are only supported inside tf.function. @def_function.function(autograph=False) def test_fn(): itr = iter(dataset_ops.Dataset.range(5)) return control_flow.for_stmt( itr, extra_test=None, body=lambda i, s: (s * 10 + i,), get_state=lambda: (), set_state=lambda _: None, init_vars=(constant_op.constant(0, dtype=dtypes.int64),)) s, = test_fn() self.assertAllEqual(s, 1234) @test_util.run_v2_only def test_tf_iterator_no_loop_vars(self): v = variables.Variable(0, dtype=dtypes.int64) def stateless_with_side_effects(i): v.assign(v.read_value() * 10 + i) # graph-mode iterators are only supported inside tf.function. @def_function.function(autograph=False) def test_fn(): control_flow.for_stmt( iter(dataset_ops.Dataset.range(5)), extra_test=None, body=stateless_with_side_effects, get_state=lambda: (), set_state=lambda _: None, init_vars=()) test_fn() self.assertEqual(self.evaluate(v.read_value()), 1234) class WhileLoopTest(test.TestCase): @test_util.run_deprecated_v1 def test_tensor(self): n = constant_op.constant(5) results = control_flow.while_stmt( test=lambda i, s: i < n, body=lambda i, s: (i + 1, s + i), get_state=lambda: (), set_state=lambda _: None, init_vars=(0, 0)) self.assertEqual((5, 10), self.evaluate(results)) def test_tensor_with_tf_side_effects_in_cond(self): n = constant_op.constant(5, dtype=dtypes.int64) v = variables.Variable(0, dtype=dtypes.int64) def get_and_increment(v): v.assign(v.read_value() + 1) return v.read_value() # function is important here, because ops test for its presence. @def_function.function(autograph=False) def test_fn(): return control_flow.while_stmt( test=lambda i: get_and_increment(v) < n, body=lambda i: (i + 1,), get_state=lambda: (), set_state=lambda _: None, init_vars=(0,)) results = test_fn() self.evaluate(v.initializer) self.assertEqual(self.evaluate(results), (4,)) self.assertEqual(self.evaluate(v), (5,)) def test_tensor_with_python_state(self): n = constant_op.constant(5) class MutableObject(object): field = constant_op.constant(0, dtype=dtypes.int32) state = MutableObject() def get_state(): return (state.field,) def set_state(new_state): state.field, = new_state def body(i, s): state.field += i return (i + 1, s + i) s = control_flow.while_stmt( test=lambda i, s: i < n, body=body, get_state=get_state, set_state=set_state, init_vars=(0, 0)) self.assertEqual(self.evaluate(s), (5, 10)) self.assertEqual(self.evaluate(state.field), 10) @test_util.run_deprecated_v1 def test_python_with_tensor_state(self): n = 5 results = control_flow.while_stmt( test=lambda i, s: i < n, body=lambda i, s: (i + 1, s + i), get_state=lambda: (), set_state=lambda _: None, init_vars=(0, constant_op.constant(0))) result_i, result_s = results self.assertEqual(5, result_i) self.assertEqual(10, self.evaluate(result_s)) def test_python(self): n = 5 results = control_flow.while_stmt( test=lambda i, s: i < n, body=lambda i, s: (i + 1, s + i), get_state=None, set_state=None, init_vars=(0, 0)) self.assertEqual((5, 10), results) def test_python_infinite_loop(self): if __debug__: with test.mock.patch.object(control_flow, 'PYTHON_MAX_ITERATIONS', 100): with self.assertRaisesRegexp(ValueError, 'iteration limit'): control_flow.while_stmt( test=lambda _: True, body=lambda i: (i + 1,), get_state=None, set_state=None, init_vars=(0,)) def test_python_long_loop_unroll_warning(self): if __debug__: with test.mock.patch.object( control_flow, 'INEFFICIENT_UNROLL_MIN_ITERATIONS', 10): with ops.Graph().as_default(): out_capturer = six.StringIO() with test.mock.patch.object(sys, 'stdout', out_capturer): ag_logging.echo_log_to_stdout = True sys.stdout = out_capturer control_flow.while_stmt( test=lambda i, _: i < 100, body=lambda i, _: (i + 1, gen_math_ops.add(i, 1),), get_state=None, set_state=None, init_vars=(0, None)) self.assertTrue(re.match( r'.*ops.*loop.*large.*iterations.*Add.*', out_capturer.getvalue())) class IfStmtTest(test.TestCase): def single_return_if_stmt(self, cond): return control_flow.if_stmt( cond=cond, body=lambda: 1, orelse=lambda: -1, get_state=lambda: (), set_state=lambda _: None) def multi_return_if_stmt(self, cond): return control_flow.if_stmt( cond=cond, body=lambda: (1, 2), orelse=lambda: (-1, -2), get_state=lambda: (), set_state=lambda _: None) @test_util.run_deprecated_v1 def test_tensor(self): with self.cached_session(): t = self.single_return_if_stmt(constant_op.constant(True)) self.assertEqual(1, self.evaluate(t)) t = self.single_return_if_stmt(constant_op.constant(False)) self.assertEqual(-1, self.evaluate(t)) def test_python(self): self.assertEqual(1, self.single_return_if_stmt(True)) self.assertEqual(-1, self.single_return_if_stmt(False)) @test_util.run_deprecated_v1 def test_tensor_multiple_returns(self): with self.cached_session(): t = self.multi_return_if_stmt(constant_op.constant(True)) self.assertAllEqual([1, 2], self.evaluate(t)) t = self.multi_return_if_stmt(constant_op.constant(False)) self.assertAllEqual([-1, -2], self.evaluate(t)) def test_python_multiple_returns(self): self.assertEqual((1, 2), self.multi_return_if_stmt(True)) self.assertEqual((-1, -2), self.multi_return_if_stmt(False)) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/operators/control_flow_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Operators specific to data structures: list append, subscripts, etc.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import list_ops from tensorflow.python.ops import tensor_array_ops # TODO(mdan): Once control flow supports objects, repackage as a class. def new_list(iterable=None): """The list constructor. Args: iterable: Optional elements to fill the list with. Returns: A list-like object. The exact return value depends on the initial elements. """ if iterable: elements = tuple(iterable) else: elements = () if elements: # When the list contains elements, it is assumed to be a "Python" lvalue # list. return _py_list_new(elements) return tf_tensor_list_new(elements) def tf_tensor_array_new(elements, element_dtype=None, element_shape=None): """Overload of new_list that stages a Tensor list creation.""" elements = tuple(ops.convert_to_tensor(el) for el in elements) all_dtypes = set(el.dtype for el in elements) if len(all_dtypes) == 1: inferred_dtype, = tuple(all_dtypes) if element_dtype is not None and element_dtype != inferred_dtype: raise ValueError( 'incompatible dtype; specified: {}, inferred from {}: {}'.format( element_dtype, elements, inferred_dtype)) elif len(all_dtypes) > 1: raise ValueError( 'TensorArray requires all elements to have the same dtype:' ' {}'.format(elements)) else: if element_dtype is None: raise ValueError('dtype is required to create an empty TensorArray') all_shapes = set(tuple(el.shape.as_list()) for el in elements) if len(all_shapes) == 1: inferred_shape, = tuple(all_shapes) if element_shape is not None and element_shape != inferred_shape: raise ValueError( 'incompatible shape; specified: {}, inferred from {}: {}'.format( element_shape, elements, inferred_shape)) elif len(all_shapes) > 1: raise ValueError( 'TensorArray requires all elements to have the same shape:' ' {}'.format(elements)) # TODO(mdan): We may want to allow different shapes with infer_shape=False. else: inferred_shape = None if element_dtype is None: element_dtype = inferred_dtype if element_shape is None: element_shape = inferred_shape l = tensor_array_ops.TensorArray( dtype=element_dtype, size=len(elements), dynamic_size=True, infer_shape=(element_shape is None), element_shape=element_shape) for i, el in enumerate(elements): l = l.write(i, el) return l def tf_tensor_list_new(elements, element_dtype=None, element_shape=None): """Overload of new_list that stages a Tensor list creation.""" if tensor_util.is_tensor(elements): if element_shape is not None: raise ValueError( 'element shape may not be specified when creating list from tensor') element_shape = array_ops.shape(elements)[1:] l = list_ops.tensor_list_from_tensor(elements, element_shape=element_shape) return l elements = tuple(ops.convert_to_tensor(el) for el in elements) all_dtypes = set(el.dtype for el in elements) if len(all_dtypes) == 1: inferred_dtype = tuple(all_dtypes)[0] if element_dtype is not None and element_dtype != inferred_dtype: raise ValueError( 'incompatible dtype; specified: {}, inferred from {}: {}'.format( element_dtype, elements, inferred_dtype)) elif all_dtypes: # Heterogeneous lists are ok. if element_dtype is not None: raise ValueError( 'specified dtype {} is inconsistent with that of elements {}'.format( element_dtype, elements)) inferred_dtype = dtypes.variant else: inferred_dtype = dtypes.variant all_shapes = set(tuple(el.shape.as_list()) for el in elements) if len(all_shapes) == 1: inferred_shape = array_ops.shape(elements[0]) if element_shape is not None and element_shape != inferred_shape: raise ValueError( 'incompatible shape; specified: {}, inferred from {}: {}'.format( element_shape, elements, inferred_shape)) elif all_shapes: # Heterogeneous lists are ok. if element_shape is not None: raise ValueError( 'specified shape {} is inconsistent with that of elements {}'.format( element_shape, elements)) inferred_shape = constant_op.constant(-1) # unknown shape, by convention else: inferred_shape = constant_op.constant(-1) # unknown shape, by convention if element_dtype is None: element_dtype = inferred_dtype if element_shape is None: element_shape = inferred_shape element_shape = ops.convert_to_tensor(element_shape, dtype=dtypes.int32) l = list_ops.empty_tensor_list( element_shape=element_shape, element_dtype=element_dtype) for el in elements: l = list_ops.tensor_list_push_back(l, el) return l def _py_list_new(elements): """Overload of new_list that creates a Python list.""" return list(elements) def list_append(list_, x): """The list append function. Note: it is unspecified where list_ will be mutated or not. If list_ is a TensorFlow entity, it will not be typically mutated. If list_ is a plain list, it will be. In general, if the list is mutated then the return value should point to the original entity. Args: list_: An entity that supports append semantics. x: The element to append. Returns: Same as list_, after the append was performed. Raises: ValueError: if list_ is not of a known list-like type. """ if isinstance(list_, tensor_array_ops.TensorArray): return _tf_tensorarray_append(list_, x) elif tensor_util.is_tensor(list_): if list_.dtype == dtypes.variant: return _tf_tensor_list_append(list_, x) else: raise ValueError( 'tensor lists are expected to be Tensors with dtype=tf.variant,' ' instead found %s' % list_) else: return _py_list_append(list_, x) def _tf_tensor_list_append(list_, x): """Overload of list_append that stages a Tensor list write.""" def empty_list_of_elements_like_x(): tensor_x = ops.convert_to_tensor(x) return list_ops.empty_tensor_list( element_shape=array_ops.shape(tensor_x), element_dtype=tensor_x.dtype) list_ = control_flow_ops.cond( list_ops.tensor_list_length(list_) > 0, lambda: list_, empty_list_of_elements_like_x, ) return list_ops.tensor_list_push_back(list_, x) def _tf_tensorarray_append(list_, x): """Overload of list_append that stages a TensorArray write.""" return list_.write(list_.size(), x) def _py_list_append(list_, x): """Overload of list_append that executes a Python list append.""" # Revert to the original call. list_.append(x) return list_ class ListPopOpts( collections.namedtuple('ListPopOpts', ('element_dtype', 'element_shape'))): pass def list_pop(list_, i, opts): """The list pop function. Note: it is unspecified where list_ will be mutated or not. If list_ is a TensorFlow entity, it will not be typically mutated. If list_ is a plain list, it will be. In general, if the list is mutated then the return value should point to the original entity. Args: list_: An entity that supports pop semantics. i: Optional index to pop from. May be None. opts: A ListPopOpts. Returns: Tuple (x, out_list_): out_list_: same as list_, after the removal was performed. x: the removed element value. Raises: ValueError: if list_ is not of a known list-like type or the operation is not supported for that type. """ assert isinstance(opts, ListPopOpts) if isinstance(list_, tensor_array_ops.TensorArray): raise ValueError('TensorArray does not support item removal') elif tensor_util.is_tensor(list_): if list_.dtype == dtypes.variant: return _tf_tensor_list_pop(list_, i, opts) else: raise ValueError( 'tensor lists are expected to be Tensors with dtype=tf.variant,' ' instead found %s' % list_) else: return _py_list_pop(list_, i) def _tf_tensor_list_pop(list_, i, opts): """Overload of list_pop that stages a Tensor list pop.""" if i is not None: raise NotImplementedError('tensor lists only support removing from the end') if opts.element_dtype is None: raise ValueError('cannot pop from a list without knowing its element ' 'type; use set_element_type to annotate it') if opts.element_shape is None: raise ValueError('cannot pop from a list without knowing its element ' 'shape; use set_element_type to annotate it') list_out, x = list_ops.tensor_list_pop_back( list_, element_dtype=opts.element_dtype) x.set_shape(opts.element_shape) return list_out, x def _py_list_pop(list_, i): """Overload of list_pop that executes a Python list append.""" if i is None: x = list_.pop() else: x = list_.pop(i) return list_, x # TODO(mdan): Look into reducing duplication between all these containers. class ListStackOpts( collections.namedtuple('ListStackOpts', ('element_dtype', 'original_call'))): pass def list_stack(list_, opts): """The list stack function. This does not have a direct correspondent in Python. The closest idiom to this is tf.append or np.stack. It's different from those in the sense that it accepts a Tensor list, rather than a list of tensors. It can also accept TensorArray. When the target is anything else, the dispatcher will rely on ctx.original_call for fallback. Args: list_: An entity that supports append semantics. opts: A ListStackOpts object. Returns: The output of the stack operation, typically a Tensor. """ assert isinstance(opts, ListStackOpts) if isinstance(list_, tensor_array_ops.TensorArray): return _tf_tensorarray_stack(list_) elif tensor_util.is_tensor(list_): if list_.dtype == dtypes.variant: return _tf_tensor_list_stack(list_, opts) else: # No-op for primitive Tensor arguments. return list_ else: return _py_list_stack(list_, opts) def _tf_tensorarray_stack(list_): """Overload of list_stack that stages a TensorArray stack.""" return list_.stack() def _tf_tensor_list_stack(list_, opts): """Overload of list_stack that stages a Tensor list write.""" if opts.element_dtype is None: raise ValueError('cannot stack a list without knowing its element type;' ' use set_element_type to annotate it') return list_ops.tensor_list_stack(list_, element_dtype=opts.element_dtype) def _py_list_stack(list_, opts): """Overload of list_stack that executes a Python list append.""" # Revert to the original call. return opts.original_call(list_)
tensorflow-master
tensorflow/python/autograph/operators/data_structures.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Exception handling statements: assert, etc.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import tensor_util from tensorflow.python.ops import control_flow_ops from tensorflow.python.util import tf_inspect def assert_stmt(expression1, expression2): """Functional form of an assert statement. This follows the semantics of the Python assert statement, however the concrete implementations may deviate from it. See the respective implementation for details. In general, the assert statement should not be used for control flow. Furthermore, it is encouraged that the assertion expressions should not have side effects. Args: expression1: Any expression2: Callable[[], Any], returns the expression to include in the error message when expression1 evaluates to False. When expression1 is True, the result of expression2 will not be evaluated, however, expression2 itself may be evaluated in some implementations. Returns: Any, implementation-dependent. Raises: ValueError: if any arguments are illegal. """ if not callable(expression2): raise ValueError('{} must be a callable'.format(expression2)) args, _, keywords, _ = tf_inspect.getargspec(expression2) if args or keywords: raise ValueError('{} may not have any arguments'.format(expression2)) if tensor_util.is_tensor(expression1): return _tf_assert_stmt(expression1, expression2) else: return _py_assert_stmt(expression1, expression2) def _tf_assert_stmt(expression1, expression2): """Overload of assert_stmt that stages a TF Assert. This implementation deviates from Python semantics as follows: (1) the assertion is verified regardless of the state of __debug__ (2) on assertion failure, the graph execution will fail with tensorflow.errors.ValueError, rather than AssertionError. Args: expression1: tensorflow.Tensor, must evaluate to a tf.bool scalar expression2: Callable[[], Union[tensorflow.Tensor, List[tensorflow.Tensor]]] Returns: tensorflow.Operation """ expression2_tensors = expression2() if not isinstance(expression2_tensors, list): expression2_tensors = [expression2_tensors] return control_flow_ops.Assert(expression1, expression2_tensors) def _py_assert_stmt(expression1, expression2): """Overload of assert_stmt that executes a Python assert statement.""" assert expression1, expression2() return None
tensorflow-master
tensorflow/python/autograph/operators/exceptions.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for data_structures module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.operators import data_structures from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import list_ops from tensorflow.python.ops import tensor_array_ops from tensorflow.python.platform import test class ListTest(test.TestCase): def test_new_list_empty(self): l = data_structures.new_list() # Can't evaluate an empty list. # TODO(mdan): sess.run should allow tf.variant maybe? self.assertTrue(isinstance(l, ops.Tensor)) def test_new_list_tensor(self): l = data_structures.new_list([3, 4, 5]) self.assertAllEqual(l, [3, 4, 5]) def test_tf_tensor_list_new(self): l = data_structures.tf_tensor_list_new([3, 4, 5]) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.int32) with self.cached_session() as sess: self.assertAllEqual(self.evaluate(t), [3, 4, 5]) def test_tf_tensor_list_new_empty(self): l = data_structures.tf_tensor_list_new([], element_dtype=dtypes.int32, element_shape=()) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.int32) with self.cached_session() as sess: self.assertAllEqual(self.evaluate(t), []) def test_tf_tensor_list_new_from_tensor(self): l = data_structures.tf_tensor_list_new(constant_op.constant([3, 4, 5])) t = list_ops.tensor_list_stack(l, element_dtype=dtypes.int32) with self.cached_session() as sess: self.assertAllEqual(self.evaluate(t), [3, 4, 5]) @test_util.run_deprecated_v1 def test_tf_tensor_list_new_illegal_input(self): with self.assertRaises(ValueError): data_structures.tf_tensor_list_new([3, 4.0]) # TODO(mdan): It might make more sense to type cast in this case. with self.assertRaises(ValueError): data_structures.tf_tensor_list_new([3, 4], element_dtype=dtypes.float32) # Tensor lists do support heterogeneous lists. self.assertIsNot(data_structures.tf_tensor_list_new([3, [4, 5]]), None) with self.assertRaises(ValueError): data_structures.tf_tensor_list_new([3, 4], element_shape=(2,)) with self.assertRaises(ValueError): data_structures.tf_tensor_list_new( constant_op.constant([1, 2, 3]), element_shape=[1]) def test_tf_tensor_array_new(self): l = data_structures.tf_tensor_array_new([3, 4, 5]) t = l.stack() with self.cached_session() as sess: self.assertAllEqual(self.evaluate(t), [3, 4, 5]) def test_tf_tensor_array_new_illegal_input(self): with self.assertRaises(ValueError): data_structures.tf_tensor_array_new([3, 4.0]) with self.assertRaises(ValueError): data_structures.tf_tensor_array_new([3, 4], element_dtype=dtypes.float32) with self.assertRaises(ValueError): data_structures.tf_tensor_array_new([3, [4, 5]]) with self.assertRaises(ValueError): data_structures.tf_tensor_array_new([3, 4], element_shape=(2,)) with self.assertRaises(ValueError): data_structures.tf_tensor_array_new([], element_shape=(2,)) # TAs can infer the shape. self.assertIsNot( data_structures.tf_tensor_array_new([], element_dtype=dtypes.float32), None) def test_append_tensor_list(self): l = data_structures.new_list() x = constant_op.constant([1, 2, 3]) l = data_structures.list_append(l, x) t = list_ops.tensor_list_stack(l, element_dtype=x.dtype) with self.cached_session() as sess: self.assertAllEqual(self.evaluate(t), [[1, 2, 3]]) @test_util.run_v1_only("b/117943489") def test_append_tensorarray(self): l = tensor_array_ops.TensorArray(dtypes.int32, size=0, dynamic_size=True) l1 = data_structures.list_append(l, 1) l2 = data_structures.list_append(l1, 2) with self.cached_session() as sess: self.assertAllEqual(self.evaluate(l1.stack()), [1]) self.assertAllEqual(self.evaluate(l2.stack()), [1, 2]) def test_append_python(self): l = [] self.assertAllEqual(data_structures.list_append(l, 1), [1]) self.assertAllEqual(data_structures.list_append(l, 2), [1, 2]) def test_pop_tensor_list(self): initial_list = constant_op.constant([[1, 2], [3, 4]]) elem_shape = constant_op.constant([2]) l = list_ops.tensor_list_from_tensor(initial_list, element_shape=elem_shape) opts = data_structures.ListPopOpts( element_dtype=initial_list.dtype, element_shape=(2,)) with self.assertRaises(NotImplementedError): data_structures.list_pop(l, 0, opts) with self.cached_session() as sess: l, x = data_structures.list_pop(l, None, opts) self.assertAllEqual(self.evaluate(x), [3, 4]) t = list_ops.tensor_list_stack(l, element_dtype=initial_list.dtype) self.assertAllEqual(self.evaluate(t), [[1, 2]]) def test_pop_python(self): l = [1, 2, 3] opts = data_structures.ListPopOpts(element_dtype=None, element_shape=()) self.assertAllEqual(data_structures.list_pop(l, None, opts), ([1, 2], 3)) self.assertAllEqual(data_structures.list_pop(l, None, opts), ([1], 2)) def test_stack_tensor_list(self): initial_list = constant_op.constant([[1, 2], [3, 4]]) elem_shape = constant_op.constant([2]) l = list_ops.tensor_list_from_tensor(initial_list, element_shape=elem_shape) opts = data_structures.ListStackOpts( element_dtype=initial_list.dtype, original_call=None) with self.cached_session() as sess: t = data_structures.list_stack(l, opts) self.assertAllEqual(self.evaluate(t), self.evaluate(initial_list)) @test_util.run_deprecated_v1 def test_stack_tensor_list_empty(self): l = list_ops.empty_tensor_list( element_shape=None, element_dtype=dtypes.variant) opts = data_structures.ListStackOpts( element_dtype=dtypes.int32, original_call=None) # TODO(mdan): Allow stacking empty lists if the dtype and shape are known. with self.assertRaises(ValueError): data_structures.list_stack(l, opts) def test_stack_fallback(self): def dummy_function(l): # Lazy person's mock: just transform the argument in a way in which we # can check that this function was indeed called. return [x * 2 for x in l] opts = data_structures.ListStackOpts( element_dtype=None, original_call=dummy_function) self.assertAllEqual(data_structures.list_stack([1, 2], opts), [2, 4]) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/operators/data_structures_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slices module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.operators import slices from tensorflow.python.framework import constant_op from tensorflow.python.ops import list_ops from tensorflow.python.platform import test class SlicesTest(test.TestCase): def test_set_item_tensor_list(self): initial_list = constant_op.constant([[1, 2], [3, 4]]) elem_shape = constant_op.constant([2]) l = list_ops.tensor_list_from_tensor(initial_list, element_shape=elem_shape) l = slices.set_item(l, 0, [5, 6]) with self.cached_session() as sess: t = list_ops.tensor_list_stack(l, element_dtype=initial_list.dtype) self.assertAllEqual(self.evaluate(t), [[5, 6], [3, 4]]) def test_get_item_tensor_list(self): initial_list = constant_op.constant([[1, 2], [3, 4]]) elem_shape = constant_op.constant([2]) l = list_ops.tensor_list_from_tensor(initial_list, element_shape=elem_shape) t = slices.get_item( l, 1, slices.GetItemOpts(element_dtype=initial_list.dtype)) with self.cached_session() as sess: self.assertAllEqual(self.evaluate(t), [3, 4]) def test_get_item_tensor_string(self): initial_str = constant_op.constant('abcd') t = slices.get_item(initial_str, 1, slices.GetItemOpts(element_dtype=initial_str.dtype)) with self.cached_session() as sess: self.assertEqual(self.evaluate(t), b'b') initial_list_str = constant_op.constant(['abcd', 'bcde']) t = slices.get_item(initial_list_str, 1, slices.GetItemOpts(element_dtype=initial_str.dtype)) with self.cached_session() as sess: self.assertEqual(self.evaluate(t), b'bcde') if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/operators/slices_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Operators specific to slicing operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_util from tensorflow.python.ops import gen_array_ops from tensorflow.python.ops import gen_string_ops from tensorflow.python.ops import list_ops from tensorflow.python.ops import tensor_array_ops # TODO(mdan): Support extended slices. class GetItemOpts(collections.namedtuple('GetItemOpts', ('element_dtype',))): pass def get_item(target, i, opts): """The slice read operator (i.e. __getitem__). Note: it is unspecified whether target will be mutated or not. In general, if target is mutable (like Python lists), it will be mutated. Args: target: An entity that supports getitem semantics. i: Index to read from. opts: A GetItemOpts object. Returns: The read element. Raises: ValueError: if target is not of a supported type. """ assert isinstance(opts, GetItemOpts) if isinstance(target, tensor_array_ops.TensorArray): return _tf_tensorarray_get_item(target, i) elif tensor_util.is_tensor(target): if target.dtype == dtypes.variant: return _tf_tensor_list_get_item(target, i, opts) elif target.dtype == dtypes.string and target.shape.ndims == 0: return _tf_tensor_string_get_item(target, i) else: return _tf_tensor_get_item(target, i) else: return _py_get_item(target, i) def _tf_tensorarray_get_item(target, i): """Overload of get_item that stages a TensorArray read.""" return target.read(i) def _tf_tensor_list_get_item(target, i, opts): """Overload of get_item that stages a Tensor list read.""" if opts.element_dtype is None: raise ValueError('cannot retrieve from a list without knowing its ' 'element type; use set_element_type to annotate it') x = list_ops.tensor_list_get_item(target, i, element_dtype=opts.element_dtype) return x def _tf_tensor_get_item(target, i): """Overload of get_item that stages a Tensor (not Tensor list) read.""" return target[i] def _tf_tensor_string_get_item(target, i): """Overload of get_item that stages a Tensor string read.""" x = gen_string_ops.substr(target, i, 1) return x def _py_get_item(target, i): """Overload of get_item that executes a Python list modification.""" return target[i] def set_item(target, i, x): """The slice write operator (i.e. __setitem__). Note: it is unspecified whether target will be mutated or not. In general, if target is mutable (like Python lists), it will be mutated. Args: target: An entity that supports setitem semantics. i: Index to modify. x: The new element value. Returns: Same as target, after the update was performed. Raises: ValueError: if target is not of a supported type. """ if isinstance(target, tensor_array_ops.TensorArray): return _tf_tensorarray_set_item(target, i, x) elif tensor_util.is_tensor(target): if target.dtype == dtypes.variant: return _tf_tensor_list_set_item(target, i, x) else: return _tf_tensor_set_item(target, i, x) else: return _py_set_item(target, i, x) def _tf_tensorarray_set_item(target, i, x): """Overload of set_item that stages a TensorArray write.""" return target.write(i, x) def _tf_tensor_list_set_item(target, i, x): """Overload of set_item that stages a Tensor list update.""" return list_ops.tensor_list_set_item(target, i, x) def _tf_tensor_set_item(target, i, x): """Overload of set_item that stages a Tensor scatter update.""" return gen_array_ops.tensor_scatter_update(target, ((i,),), (x,)) def _py_set_item(target, i, x): """Overload of set_item that executes a Python list modification.""" target[i] = x return target
tensorflow-master
tensorflow/python/autograph/operators/slices.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for exceptions module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.operators import exceptions from tensorflow.python.framework import constant_op from tensorflow.python.framework import errors_impl from tensorflow.python.framework import test_util from tensorflow.python.platform import test class ExceptionsTest(test.TestCase): def test_assert_tf_untriggered(self): with self.cached_session() as sess: t = exceptions.assert_stmt( constant_op.constant(True), lambda: constant_op.constant('ignored')) self.evaluate(t) @test_util.run_deprecated_v1 def test_assert_tf_triggered(self): with self.cached_session() as sess: t = exceptions.assert_stmt( constant_op.constant(False), lambda: constant_op.constant('test message')) with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, 'test message'): self.evaluate(t) @test_util.run_deprecated_v1 def test_assert_tf_multiple_printed_values(self): two_tensors = [ constant_op.constant('test message'), constant_op.constant('another message') ] with self.cached_session() as sess: t = exceptions.assert_stmt( constant_op.constant(False), lambda: two_tensors) with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, 'test message.*another message'): self.evaluate(t) def test_assert_python_untriggered(self): side_effect_trace = [] def expression_with_side_effects(): side_effect_trace.append(object()) return 'test message' exceptions.assert_stmt(True, expression_with_side_effects) self.assertListEqual(side_effect_trace, []) def test_assert_python_triggered(self): if not __debug__: # Python assertions only be tested when in debug mode. return side_effect_trace = [] tracer = object() def expression_with_side_effects(): side_effect_trace.append(tracer) return 'test message' with self.assertRaisesRegexp(AssertionError, 'test message'): exceptions.assert_stmt(False, expression_with_side_effects) self.assertListEqual(side_effect_trace, [tracer]) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/operators/exceptions_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for py_builtins module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import six from tensorflow.python.autograph.operators import data_structures from tensorflow.python.autograph.operators import py_builtins from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors_impl from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import tensor_array_ops from tensorflow.python.platform import test class PyBuiltinsTest(test.TestCase): def test_abs(self): self.assertEqual(py_builtins.abs_(-1), 1) with self.cached_session() as sess: t = py_builtins.abs_(constant_op.constant(-1)) self.assertEqual(self.evaluate(t), 1) t = py_builtins.abs_(constant_op.constant([-1, 2, -3])) self.assertAllEqual(self.evaluate(t), [1, 2, 3]) def test_float(self): self.assertEqual(py_builtins.float_(10), 10.0) self.assertEqual(py_builtins.float_('10.0'), 10.0) with self.cached_session() as sess: t = py_builtins.float_(constant_op.constant(1, dtype=dtypes.int64)) self.assertEqual(self.evaluate(t), 1.0) st = py_builtins.float_(constant_op.constant('1.0')) self.assertEqual(self.evaluate(st), 1.0) def test_int(self): self.assertEqual(py_builtins.int_(10.0), 10) self.assertEqual(py_builtins.int_('11', 2), 3) with self.cached_session() as sess: t = py_builtins.int_(constant_op.constant(1, dtype=dtypes.float64)) self.assertEqual(self.evaluate(t), 1) st = py_builtins.int_(constant_op.constant('1')) self.assertEqual(self.evaluate(st), 1) st = py_builtins.int_(constant_op.constant('1'), 10) self.assertEqual(self.evaluate(st), 1) def test_int_unsupported_base(self): t = constant_op.constant(1, dtype=dtypes.float64) with self.assertRaises(NotImplementedError): py_builtins.int_(t, 2) def test_len(self): self.assertEqual(py_builtins.len_([1, 2, 3]), 3) with self.cached_session() as sess: t = py_builtins.len_(constant_op.constant([[1], [2], [3]])) self.assertEqual(t, 3) ta = py_builtins.len_(tensor_array_ops.TensorArray(dtypes.int32, size=5)) self.assertEqual(self.evaluate(ta), 5) tl = py_builtins.len_(data_structures.tf_tensor_list_new([3, 4, 5])) self.assertEqual(self.evaluate(tl), 3) def test_len_scalar(self): with self.assertRaises(ValueError): py_builtins.len_(constant_op.constant(1)) @test_util.run_deprecated_v1 def test_len_dynamic_shape(self): with self.cached_session() as sess: p = array_ops.placeholder(dtype=dtypes.int32, shape=None) t = py_builtins.len_(p) self.assertEqual(sess.run(t, {p: [1, 2, 3]}), 3) with self.assertRaises(errors_impl.InvalidArgumentError): t = py_builtins.len_(p) sess.run(t, {p: 1}) @test_util.run_deprecated_v1 def test_print_tensors(self): try: out_capturer = six.StringIO() sys.stdout = out_capturer with self.cached_session() as sess: sess.run(py_builtins.print_(constant_op.constant('test message'), 1)) self.assertEqual(out_capturer.getvalue(), 'test message 1\n') finally: sys.stdout = sys.__stdout__ @test_util.run_deprecated_v1 def test_print_complex(self): try: out_capturer = six.StringIO() sys.stdout = out_capturer with self.cached_session() as sess: sess.run( py_builtins.print_(constant_op.constant('test message'), [1, 2])) self.assertEqual(out_capturer.getvalue(), 'test message [1, 2]\n') finally: sys.stdout = sys.__stdout__ def test_range(self): self.assertListEqual(list(py_builtins.range_(3)), [0, 1, 2]) self.assertListEqual(list(py_builtins.range_(1, 3)), [1, 2]) self.assertListEqual(list(py_builtins.range_(2, 0, -1)), [2, 1]) def test_range_tensor(self): with self.cached_session() as sess: r = py_builtins.range_(constant_op.constant(3)) self.assertAllEqual(self.evaluate(r), [0, 1, 2]) r = py_builtins.range_(1, constant_op.constant(3)) self.assertAllEqual(self.evaluate(r), [1, 2]) r = py_builtins.range_(2, 0, constant_op.constant(-1)) self.assertAllEqual(self.evaluate(r), [2, 1]) def test_range_tensor_empty_range(self): with self.session() as sess: r = py_builtins.range_(constant_op.constant(-3)) self.assertAllEqual(self.evaluate(r), []) r = py_builtins.range_(5, constant_op.constant(2)) self.assertAllEqual(self.evaluate(r), []) def test_eval_in_original_context(self): def caller_1(lvl_delta): l = 1 # pylint:disable=unused-variable return py_builtins.eval_in_original_context(eval, ('l',), lvl_delta) def caller_2(lvl_delta): l = 2 # pylint:disable=unused-variable return caller_1(lvl_delta) def caller_3(lvl_delta): l = 3 # pylint:disable=unused-variable return caller_2(lvl_delta) self.assertEqual(caller_3(0), 1) self.assertEqual(caller_3(1), 2) self.assertEqual(caller_3(2), 3) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/operators/py_builtins_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Lowers list comprehensions into for and if statements. Example: result = [x * x for x in xs] becomes result = [] for x in xs: elt = x * x result.append(elt) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.pyct import templates # TODO(mdan): This should covert directly to operator calls. class ListCompTransformer(converter.Base): """Lowers list comprehensions into standard control flow.""" def visit_Assign(self, node): if not isinstance(node.value, gast.ListComp): return self.generic_visit(node) if len(node.targets) > 1: raise NotImplementedError('multiple assignments') target, = node.targets list_comp_node = node.value template = """ target = [] """ initialization = templates.replace(template, target=target) template = """ target.append(elt) """ body = templates.replace(template, target=target, elt=list_comp_node.elt) for gen in reversed(list_comp_node.generators): for gen_if in reversed(gen.ifs): template = """ if test: body """ body = templates.replace(template, test=gen_if, body=body) template = """ for target in iter_: body """ body = templates.replace( template, iter_=gen.iter, target=gen.target, body=body) return initialization + body def transform(node, ctx): return ListCompTransformer(ctx).visit(node)
tensorflow-master
tensorflow/python/autograph/converters/list_comprehensions.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for logical_expressions module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.converters import logical_expressions from tensorflow.python.autograph.core import converter_testing from tensorflow.python.framework import constant_op from tensorflow.python.framework import test_util from tensorflow.python.platform import test class LogicalExpressionTest(converter_testing.TestCase): @test_util.run_deprecated_v1 def test_equals(self): def test_fn(a, b): return a == b with self.converted(test_fn, logical_expressions, {}) as result: with self.cached_session() as sess: self.assertTrue(sess.run(result.test_fn(constant_op.constant(1), 1))) self.assertFalse(sess.run(result.test_fn(constant_op.constant(1), 2))) @test_util.run_deprecated_v1 def test_bool_ops(self): def test_fn(a, b, c): return (a or b) and (a or b or c) and not c with self.converted(test_fn, logical_expressions, {}) as result: with self.cached_session() as sess: self.assertTrue( sess.run(result.test_fn(constant_op.constant(True), False, False))) self.assertFalse( sess.run(result.test_fn(constant_op.constant(True), False, True))) @test_util.run_deprecated_v1 def test_comparison(self): def test_fn(a, b, c, d): return a < b == c > d with self.converted(test_fn, logical_expressions, {}) as result: with self.cached_session() as sess: # Note: having just the first constant a tensor tests that the # operations execute in the correct order. If anything other than # a < b executed first, the result would be a Python scalar and not a # Tensor. This is valid as long as the dispat is automatic based on # type. self.assertTrue( sess.run(result.test_fn(constant_op.constant(1), 2, 2, 1))) self.assertFalse( sess.run(result.test_fn(constant_op.constant(1), 2, 2, 3))) def test_default_ops(self): def test_fn(a, b): return a in b with self.converted(test_fn, logical_expressions, {}) as result: self.assertTrue(result.test_fn('a', ('a',))) def test_unary_ops(self): def test_fn(a): return ~a, -a, +a with self.converted(test_fn, logical_expressions, {}) as result: self.assertEqual(result.test_fn(1), (-2, -1, 1)) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/logical_expressions_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for continue_statements module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.converters import continue_statements from tensorflow.python.autograph.core import converter_testing from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.platform import test class ContinueCanonicalizationTest(converter_testing.TestCase): def assertTransformedEquivalent(self, test_fn, *inputs): with self.converted(test_fn, continue_statements, {'ops': ops}, constant_op.constant) as result: self.assertEqual(test_fn(*inputs), result.test_fn(*inputs)) def test_basic(self): def test_fn(x): v = [] while x > 0: x -= 1 if x % 2 == 0: continue v.append(x) return v self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 1) self.assertTransformedEquivalent(test_fn, 3) self.assertTransformedEquivalent(test_fn, 4) def test_multiple_continues(self): def test_fn(x): v = [] while x > 0: x -= 1 if x > 1: continue if x > 2: continue v.append(x) return v self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 1) self.assertTransformedEquivalent(test_fn, 3) self.assertTransformedEquivalent(test_fn, 4) def test_multiple_continues_in_nested_scope(self): def test_fn(a): v = [] for x in a: x -= 1 if x > 100: continue try: raise ValueError('intentional') except ValueError: continue v.append(x) return v self.assertTransformedEquivalent(test_fn, []) self.assertTransformedEquivalent(test_fn, [1]) self.assertTransformedEquivalent(test_fn, [2]) self.assertTransformedEquivalent(test_fn, [1, 2, 3]) def test_for_loop(self): def test_fn(a): v = [] for x in a: x -= 1 if x % 2 == 0: continue v.append(x) return v self.assertTransformedEquivalent(test_fn, []) self.assertTransformedEquivalent(test_fn, [1]) self.assertTransformedEquivalent(test_fn, [2]) self.assertTransformedEquivalent(test_fn, [1, 2, 3]) def test_nested_with(self): def test_fn(x): v = [] while x > 0: x -= 1 with ops.name_scope(''): if x % 2 == 0: continue v.append(x) return v self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 1) self.assertTransformedEquivalent(test_fn, 3) self.assertTransformedEquivalent(test_fn, 4) def test_nested_multiple_withs(self): def test_fn(x): v = [] while x > 0: x -= 1 with ops.name_scope(''): if x % 2 == 0: continue with ops.name_scope(''): v.append(x) v.append(x) return v self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 1) self.assertTransformedEquivalent(test_fn, 3) self.assertTransformedEquivalent(test_fn, 4) def test_nested_multiple_withs_and_statements(self): def test_fn(x): v = [] while x > 0: x -= 1 with ops.name_scope(''): if x % 2 == 0: continue v.append(x) v.append(x) with ops.name_scope(''): v.append(x) v.append(x) return v self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 1) self.assertTransformedEquivalent(test_fn, 3) self.assertTransformedEquivalent(test_fn, 4) def test_nested_multiple_withs_and_nested_withs(self): def test_fn(x): v = [] while x > 0: x -= 1 with ops.name_scope(''): if x % 2 == 0: continue with ops.name_scope(''): v.append(x) v.append(x) with ops.name_scope(''): v.append(x) v.append(x) return v self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 1) self.assertTransformedEquivalent(test_fn, 3) self.assertTransformedEquivalent(test_fn, 4) def test_nested(self): def test_fn(x): v = [] u = [] w = [] while x > 0: x -= 1 if x % 2 == 0: if x % 3 != 0: u.append(x) else: w.append(x) continue v.append(x) return v, u, w self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 1) self.assertTransformedEquivalent(test_fn, 3) self.assertTransformedEquivalent(test_fn, 4) def test_multiple_guarded_continues_with_side_effects(self): def test_fn(x): def track(u, x): u.append(x) return x u = [] v = [] while x > 0: x -= 1 if track(u, x) > 1: continue if track(u, x) > 2: continue v.append(x) return u, v self.assertTransformedEquivalent(test_fn, 3) self.assertTransformedEquivalent(test_fn, 2) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/continue_statements_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Converter for list operations. This includes converting Python lists to TensorArray/TensorList. """ # TODO(mdan): Elaborate the logic here. # TODO(mdan): Does it even make sense to attempt to try to use TAs? # The current rule (always convert to TensorArray) is naive and insufficient. # In general, a better mechanism could look like: # * convert to TensorList by default # * leave as Python list if the user explicitly forbids it # * convert to TensorArray only when complete write once behavior can be # guaranteed (e.g. list comprehensions) from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.lang import directives from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import templates from tensorflow.python.autograph.pyct.static_analysis.annos import NodeAnno # Tags for local state. POP_USES = 'pop_uses' class ListTransformer(converter.Base): """Converts lists and related operations to their TF counterpart.""" def visit_List(self, node): node = self.generic_visit(node) template = """ ag__.new_list(elements) """ return templates.replace_as_expression(template, elements=node) def _replace_append_call(self, node): assert len(node.args) == 1 assert isinstance(node.func, gast.Attribute) template = """ target = ag__.list_append(target, element) """ return templates.replace( template, target=node.func.value, element=node.args[0]) def _replace_pop_call(self, node): # Expressions that use pop() are converted to a statement + expression. # # For example: # # print(target.pop()) # # ... is converted to: # # target, target_pop = ag__.list_pop(target) # print(target_pop) # # Here, we just generate the variable name and swap it in, # and _generate_pop_operation will handle the rest. # # Multiple uses of pop() are allowed: # # print(tartget.pop(), target.pop()) # print(tartget.pop().pop()) # assert isinstance(node.func, gast.Attribute) scope = anno.getanno(node, NodeAnno.ARGS_SCOPE) target_node = node.func.value # Attempt to use a related name if one exists. Otherwise use something # generic. if anno.hasanno(target_node, anno.Basic.QN): target_name = anno.getanno(target_node, anno.Basic.QN).ssf() else: target_name = 'list_' pop_var_name = self.ctx.namer.new_symbol(target_name, scope.referenced) pop_uses = self.get_local(POP_USES, []) pop_uses.append((node, pop_var_name)) self.set_local(POP_USES, pop_uses) return templates.replace_as_expression('var_name', var_name=pop_var_name) def _replace_stack_call(self, node): assert len(node.args) == 1 dtype = self.get_definition_directive( node.args[0], directives.set_element_type, 'dtype', default=templates.replace_as_expression('None')) template = """ ag__.list_stack( target, opts=ag__.ListStackOpts( element_dtype=dtype, original_call=orig_call)) """ return templates.replace_as_expression( template, dtype=dtype, target=node.args[0], orig_call=node.func) def visit_Call(self, node): node = self.generic_visit(node) # TODO(mdan): This is insufficient if target is a function argument. # In the case of function arguments, we need to add the list to the # function's return value, because it is being modified. # TODO(mdan): Checking just the name is brittle, can it be improved? if isinstance(node.func, gast.Attribute): func_name = node.func.attr if func_name == 'append' and (len(node.args) == 1): node = self._replace_append_call(node) elif func_name == 'pop' and (len(node.args) <= 1): node = self._replace_pop_call(node) elif (func_name == 'stack' and (len(node.args) == 1) and (not node.keywords or node.keywords[0].arg == 'strict')): # This avoids false positives with keyword args. # TODO(mdan): handle kwargs properly. node = self._replace_stack_call(node) return node def _generate_pop_operation(self, original_call_node, pop_var_name): assert isinstance(original_call_node.func, gast.Attribute) if original_call_node.args: pop_element = original_call_node.args[0] else: pop_element = parser.parse_expression('None') # The call will be something like "target.pop()", and the dtype is hooked to # target, hence the func.value. # TODO(mdan): For lists of lists, this won't work. # The reason why it won't work is because it's unclear how to annotate # the list as a "list of lists with a certain element type" when using # operations like `l.pop().pop()`. dtype = self.get_definition_directive( original_call_node.func.value, directives.set_element_type, 'dtype', default=templates.replace_as_expression('None')) shape = self.get_definition_directive( original_call_node.func.value, directives.set_element_type, 'shape', default=templates.replace_as_expression('None')) template = """ target, pop_var_name = ag__.list_pop( target, element, opts=ag__.ListPopOpts(element_dtype=dtype, element_shape=shape)) """ return templates.replace( template, target=original_call_node.func.value, pop_var_name=pop_var_name, element=pop_element, dtype=dtype, shape=shape) def _postprocess_statement(self, node): """Inserts any separate pop() calls that node may use.""" pop_uses = self.get_local(POP_USES, None) if pop_uses: replacements = [] for original_call_node, pop_var_name in pop_uses: replacements.extend( self._generate_pop_operation(original_call_node, pop_var_name)) replacements.append(node) node = replacements self.exit_local_scope() return node, None # TODO(mdan): Should we have a generic visit_block instead? # Right now it feels that a visit_block would add too much magic that's # hard to follow. def _visit_and_process_block(self, block): return self.visit_block( block, before_visit=self.enter_local_scope, after_visit=self._postprocess_statement) def visit_FunctionDef(self, node): node.args = self.generic_visit(node.args) node.decorator_list = self.visit_block(node.decorator_list) node.body = self._visit_and_process_block(node.body) return node def visit_For(self, node): node.target = self.visit(node.target) node.body = self._visit_and_process_block(node.body) node.orelse = self._visit_and_process_block(node.orelse) return node def visit_While(self, node): node.test = self.visit(node.test) node.body = self._visit_and_process_block(node.body) node.orelse = self._visit_and_process_block(node.orelse) return node def visit_If(self, node): node.test = self.visit(node.test) node.body = self._visit_and_process_block(node.body) node.orelse = self._visit_and_process_block(node.orelse) return node def visit_With(self, node): node.items = self.visit_block(node.items) node.body = self._visit_and_process_block(node.body) return node def transform(node, ctx): return ListTransformer(ctx).visit(node)
tensorflow-master
tensorflow/python/autograph/converters/lists.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Adds guards against function calls with side effects. Only standalone calls are guarded. WARNING: This mechanism is incomplete. Particularly, it only guards the arguments passed to functions, and does not account for indirectly modified state. Example: y = tf.compat.v1.layers.dense(x) # Creates TF variable 'foo' loss = loss(y) opt.minimize(loss) # indirectly affects 'foo' z = tf.compat.v1.get_variable('foo') # Indirectly affects `loss` and 'foo' # Here, `loss` can be guarded. But `z` cannot. # TODO(mdan): We should probably define a safe mode where we guard everything. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import ast_util from tensorflow.python.autograph.pyct import qual_names from tensorflow.python.autograph.pyct import templates from tensorflow.python.autograph.pyct.static_analysis.annos import NodeAnno class SymbolNamer(object): """Describes the interface for SideEffectGuardTransformer's namer.""" def new_symbol(self, name_root, reserved_locals): """Generate a new unique function_name. Args: name_root: String, used as stem in the new name. reserved_locals: Set(string), additional local symbols that are reserved. Returns: String. """ raise NotImplementedError() class SideEffectGuardTransformer(converter.Base): """Adds control dependencies to functions with side effects.""" def _visit_and_reindent(self, nodes): new_nodes = [] current_dest = new_nodes alias_map = {} reindent_requested = False for n in nodes: n = self.visit(n) # NOTE: the order in which these statements execute is important; in # particular, watch out for ending up with cycles in the AST. if alias_map: n = ast_util.rename_symbols(n, alias_map) if isinstance(n, (list, tuple)): current_dest.extend(n) else: current_dest.append(n) if anno.hasanno(n, anno.Basic.INDENT_BLOCK_REMAINDER): reindent_requested = True new_dest, new_alias_map = anno.getanno( n, anno.Basic.INDENT_BLOCK_REMAINDER) anno.delanno(n, anno.Basic.INDENT_BLOCK_REMAINDER) new_alias_map.update(alias_map) alias_map = new_alias_map current_dest = new_dest if reindent_requested: no_controls_to_gate = False if not current_dest: no_controls_to_gate = True if len(current_dest) == 1: if ast_util.matches(current_dest[0], 'return'): no_controls_to_gate = True if ast_util.matches(current_dest[0], 'return ()'): no_controls_to_gate = True if ast_util.matches(current_dest[0], 'return []'): no_controls_to_gate = True if ast_util.matches(current_dest[0], 'return {}'): no_controls_to_gate = True if no_controls_to_gate: # TODO(mdan): There may still be something that could be done. raise ValueError( 'Unable to insert statement into the computation flow: it is not' ' followed by any computation which the statement could gate.') return new_nodes def visit_FunctionDef(self, node): node.body = self._visit_and_reindent(node.body) return node def visit_With(self, node): node.body = self._visit_and_reindent(node.body) return node def visit_If(self, node): node.body = self._visit_and_reindent(node.body) node.orelse = self._visit_and_reindent(node.orelse) return node def visit_While(self, node): node.body = self._visit_and_reindent(node.body) node.orelse = self._visit_and_reindent(node.orelse) return node # TODO(b/123995141) Remove once ExceptionHandlers are in the CFG def visit_ExceptHandler(self, node): return node def visit_Expr(self, node): self.generic_visit(node) if isinstance(node.value, gast.Call): # Patterns of single function calls, like: # opt.minimize(loss) # or: # tf.compat.v1.py_func(...) # First, attempt to gate future evaluation of args. If that's not # possible, gate all remaining statements (and that may fail too, see # _visit_and_reindent. args_scope = anno.getanno(node.value, NodeAnno.ARGS_SCOPE) live_out = anno.getanno(node, anno.Static.LIVE_VARS_OUT) # NOTE: We can't guard object attributes because they may not be writable. # In addition, avoid renaming well-known names. # TODO(mdan): Move these names into config. unguarded_names = (qual_names.QN('self'), qual_names.QN('ag__')) guarded_args = tuple(s for s in live_out if not s.is_composite() and s not in unguarded_names) # TODO(mdan): Include all arguments which depended on guarded_args too. # For example, the following will still cause a race: # tf.compat.v1.assign(a, a + 1) # b = a + 1 # tf.compat.v1.assign(a, a + 1) # Control deps here should include `b` # c = b + 1 # Or maybe we should just raise an "unsafe assign" error? if guarded_args: # The aliases may need new names to avoid incorrectly making them local. # TODO(mdan): This is brutal. It will even rename modules - any fix? need_alias = tuple( s for s in guarded_args if s not in args_scope.parent.modified) aliased_new_names = tuple( qual_names.QN( self.ctx.namer.new_symbol( s.ssf(), args_scope.parent.referenced)) for s in need_alias) alias_map = dict(zip(need_alias, aliased_new_names)) if len(guarded_args) == 1: s, = guarded_args aliased_guarded_args = alias_map.get(s, s) else: aliased_guarded_args = gast.Tuple( [alias_map.get(s, s).ast() for s in guarded_args], None) template = """ with ag__.utils.control_dependency_on_returns(call): aliased_guarded_args = ag__.utils.alias_tensors(guarded_args) """ control_deps_guard = templates.replace( template, call=node.value, aliased_guarded_args=aliased_guarded_args, guarded_args=guarded_args)[-1] else: alias_map = {} template = """ with ag__.utils.control_dependency_on_returns(call): pass """ control_deps_guard = templates.replace(template, call=node.value)[-1] control_deps_guard.body = [] node = control_deps_guard anno.setanno(node, anno.Basic.INDENT_BLOCK_REMAINDER, (node.body, alias_map)) return node def transform(node, ctx): return SideEffectGuardTransformer(ctx).visit(node)
tensorflow-master
tensorflow/python/autograph/converters/side_effect_guards.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for return_statements module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.converters import return_statements from tensorflow.python.autograph.core import converter_testing from tensorflow.python.framework import ops from tensorflow.python.platform import test class SingleReturnTest(converter_testing.TestCase): def assertTransformedEquivalent(self, test_fn, *inputs): ns = {'ops': ops} with self.converted(test_fn, return_statements, ns) as result: self.assertEqual(test_fn(*inputs), result.test_fn(*inputs)) def test_straightline(self): def test_fn(x): return x * x self.assertTransformedEquivalent(test_fn, 2) def test_superfluous_returns(self): def test_fn(): retval = 1 return retval retval = 2 # pylint:disable=unreachable return retval self.assertTransformedEquivalent(test_fn) def test_superfluous_returns_adjacent(self): def test_fn(): return 1 return 2 # pylint:disable=unreachable self.assertTransformedEquivalent(test_fn) def test_conditional(self): def test_fn(x): if x > 0: return x else: return x * x self.assertTransformedEquivalent(test_fn, 2) self.assertTransformedEquivalent(test_fn, -2) def test_contitional_missing_else(self): def test_fn(x): if x > 0: return x self.assertTransformedEquivalent(test_fn, 2) self.assertTransformedEquivalent(test_fn, -2) def test_conditional_missing_else_then_default(self): def test_fn(x): if x > 0: return x return x * x self.assertTransformedEquivalent(test_fn, 2) self.assertTransformedEquivalent(test_fn, -2) def test_conditional_else_only_then_default(self): def test_fn(x): if x < 0: x *= x else: return x return x self.assertTransformedEquivalent(test_fn, 2) self.assertTransformedEquivalent(test_fn, -2) def test_conditional_nested(self): def test_fn(x): if x > 0: if x < 5: return x else: return x * x else: return x * x * x self.assertTransformedEquivalent(test_fn, 2) self.assertTransformedEquivalent(test_fn, -2) self.assertTransformedEquivalent(test_fn, 5) def test_context_manager(self): def test_fn(x): with ops.name_scope(''): return x * x self.assertTransformedEquivalent(test_fn, 2) self.assertTransformedEquivalent(test_fn, -2) def test_context_manager_in_conditional(self): def test_fn(x): if x > 0: with ops.name_scope(''): return x * x else: return x self.assertTransformedEquivalent(test_fn, 2) self.assertTransformedEquivalent(test_fn, -2) def text_conditional_in_context_manager(self): def test_fn(x): with ops.name_scope(''): if x > 0: return x * x else: return x self.assertTransformedEquivalent(test_fn, 2) self.assertTransformedEquivalent(test_fn, -2) def test_no_return(self): def test_fn(x): x *= x self.assertTransformedEquivalent(test_fn, 2) def test_nested_function(self): def test_fn(x): def inner_fn(y): if y > 0: return y * y else: return y return inner_fn(x) self.assertTransformedEquivalent(test_fn, 2) self.assertTransformedEquivalent(test_fn, -2) def test_nested_function_in_control_flow(self): def test_fn(x): if x: def inner_fn(y): return y inner_fn(x) self.assertTransformedEquivalent(test_fn, 2) self.assertTransformedEquivalent(test_fn, -2) def test_for_loop(self): def test_fn(n): for _ in range(n): return 1 self.assertTransformedEquivalent(test_fn, 2) self.assertTransformedEquivalent(test_fn, 0) def test_while_loop(self): def test_fn(n): i = 0 s = 0 while i < n: i += 1 s += i if s > 4: return s return -1 self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 2) self.assertTransformedEquivalent(test_fn, 4) def test_null_return(self): def test_fn(n): if n > 4: return return self.assertTransformedEquivalent(test_fn, 4) self.assertTransformedEquivalent(test_fn, 5) def test_nested_multiple_withs(self): def test_fn(x): v = [] while x > 0: x -= 1 with ops.name_scope(''): if x % 2 == 0: return v with ops.name_scope(''): v.append(x) v.append(x) return v self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 1) self.assertTransformedEquivalent(test_fn, 3) self.assertTransformedEquivalent(test_fn, 4) def test_multiple_returns_in_nested_scope(self): def test_fn(a): v = [] for x in a: x -= 1 if x > 100: return v try: raise ValueError('intentional') except ValueError: # pylint:disable=bare-except return v v.append(x) return v self.assertTransformedEquivalent(test_fn, []) self.assertTransformedEquivalent(test_fn, [1]) self.assertTransformedEquivalent(test_fn, [2]) self.assertTransformedEquivalent(test_fn, [1, 2, 3]) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/return_statements_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for lists module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.converters import lists from tensorflow.python.autograph.core import converter_testing from tensorflow.python.autograph.lang import directives from tensorflow.python.autograph.lang import special_functions from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import parser from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import list_ops from tensorflow.python.platform import test tf = None # Will be replaced by a mock. class ListTest(converter_testing.TestCase): def test_empty_list(self): def test_fn(): return [] with self.converted(test_fn, lists, {}) as result: tl = result.test_fn() # Empty tensor lists cannot be evaluated or stacked. self.assertTrue(isinstance(tl, ops.Tensor)) self.assertEqual(tl.dtype, dtypes.variant) def test_initialized_list(self): def test_fn(): return [1, 2, 3] with self.converted(test_fn, lists, {}) as result: self.assertAllEqual(result.test_fn(), [1, 2, 3]) def test_list_append(self): def test_fn(): l = special_functions.tensor_list([1]) l.append(2) l.append(3) return l ns = {'special_functions': special_functions} with self.converted(test_fn, lists, ns) as result: with self.cached_session() as sess: tl = result.test_fn() r = list_ops.tensor_list_stack(tl, dtypes.int32) self.assertAllEqual(self.evaluate(r), [1, 2, 3]) def test_list_pop(self): def test_fn(): l = special_functions.tensor_list([1, 2, 3]) s = l.pop() return s, l ns = {'special_functions': special_functions} node, ctx = self.prepare(test_fn, ns) def_, = anno.getanno(node.body[0].targets[0], anno.Static.ORIG_DEFINITIONS) def_.directives[directives.set_element_type] = { 'dtype': parser.parse_expression('tf.int32'), 'shape': parser.parse_expression('()'), } node = lists.transform(node, ctx) with self.compiled(node, ns, dtypes.int32) as result: with self.cached_session() as sess: ts, tl = result.test_fn() r = list_ops.tensor_list_stack(tl, dtypes.int32) self.assertAllEqual(self.evaluate(r), [1, 2]) self.assertAllEqual(self.evaluate(ts), 3) def test_double_list_pop(self): def test_fn(l): s = l.pop().pop() return s with self.converted(test_fn, lists, {}) as result: test_input = [1, 2, [1, 2, 3]] # TODO(mdan): Pass a list of lists of tensor when we fully support that. # For now, we just pass a regular Python list of lists just to verify that # the two pop calls are sequenced properly. self.assertAllEqual(result.test_fn(test_input), 3) def test_list_stack(self): def test_fn(): l = [1, 2, 3] return tf.stack(l) node, ctx = self.prepare(test_fn, {}) def_, = anno.getanno(node.body[0].targets[0], anno.Static.ORIG_DEFINITIONS) def_.directives[directives.set_element_type] = { 'dtype': parser.parse_expression('tf.int32') } node = lists.transform(node, ctx) with self.compiled(node, {}, array_ops.stack, dtypes.int32) as result: with self.cached_session() as sess: self.assertAllEqual(self.evaluate(result.test_fn()), [1, 2, 3]) # TODO(mdan): Add a test with tf.stack with axis kwarg. if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/lists_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Canonicalizes functions with multiple returns to use just one.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import templates from tensorflow.python.autograph.pyct.static_analysis.annos import NodeAnno BODY_DEFINITELY_RETURNS = 'BODY_DEFINITELY_RETURNS' ORELSE_DEFINITELY_RETURNS = 'ORELSE_DEFINITELY_RETURNS' STMT_DEFINITELY_RETURNS = 'STMT_DEFINITELY_RETURNS' class _RewriteBlock(object): def __init__(self): self.definitely_returns = False class ConditionalReturnRewriter(converter.Base): """Rewrites a a pattern where it's unbovious that all paths return a value. This rewrite allows avoiding intermediate None return values. The following pattern: if cond: <block 1> return else: <block 2> <block 3> is converted to: if cond: <block 1> return else: <block 2> <block 3> and vice-versa (if the else returns, subsequent statements are moved under the if branch). """ def visit_Return(self, node): self.state[_RewriteBlock].definitely_returns = True return node def _postprocess_statement(self, node): # If the node definitely returns (e.g. it's a with statement with a # return stateent in it), then the current block also definitely returns. if anno.getanno(node, STMT_DEFINITELY_RETURNS, default=False): self.state[_RewriteBlock].definitely_returns = True # The special case: collapse a typical conditional return pattern into # a single conditional with possibly returns on both branches. This # reduces the use of None return values, which don't work with TF # conditionals. if (isinstance(node, gast.If) and anno.getanno(node, BODY_DEFINITELY_RETURNS, default=False)): return node, node.orelse elif (isinstance(node, gast.If) and anno.getanno(node, ORELSE_DEFINITELY_RETURNS, default=False)): return node, node.body return node, None def _visit_statement_block(self, node, nodes): self.state[_RewriteBlock].enter() new_nodes = self.visit_block(nodes, after_visit=self._postprocess_statement) block_definitely_returns = self.state[_RewriteBlock].definitely_returns self.state[_RewriteBlock].exit() return new_nodes, block_definitely_returns def visit_While(self, node): node.test = self.visit(node.test) node.body, _ = self._visit_statement_block(node, node.body) node.orelse, _ = self._visit_statement_block(node, node.orelse) return node def visit_For(self, node): node.iter = self.visit(node.iter) node.target = self.visit(node.target) node.body, _ = self._visit_statement_block(node, node.body) node.orelse, _ = self._visit_statement_block(node, node.orelse) return node def visit_With(self, node): node.items = self.visit_block(node.items) node.body, definitely_returns = self._visit_statement_block(node, node.body) if definitely_returns: anno.setanno(node, STMT_DEFINITELY_RETURNS, True) return node def visit_Try(self, node): # We could decide whether a 'try' DEFINITELY_RETURNS based on its components # It is not clear whether we want to do anything with this given # a 'try' is likely to throw an exception in some circumstances. node.body, _ = self._visit_statement_block(node, node.body) node.orelse, _ = self._visit_statement_block(node, node.orelse) node.finalbody, _ = self._visit_statement_block(node, node.finalbody) node.handlers = self.visit_block(node.handlers) return node def visit_ExceptHandler(self, node): # To determine whether `try` DEFINITELY_RETURNS we need to revisit this. node.body, _ = self._visit_statement_block(node, node.body) return node def visit_If(self, node): node.test = self.visit(node.test) node.body, body_definitely_returns = self._visit_statement_block( node, node.body) if body_definitely_returns: anno.setanno(node, BODY_DEFINITELY_RETURNS, True) node.orelse, orelse_definitely_returns = self._visit_statement_block( node, node.orelse) if orelse_definitely_returns: anno.setanno(node, ORELSE_DEFINITELY_RETURNS, True) if body_definitely_returns and orelse_definitely_returns: self.state[_RewriteBlock].definitely_returns = True return node def visit_FunctionDef(self, node): node.args = self.visit(node.args) node.body, _ = self._visit_statement_block(node, node.body) return node class _Block(object): def __init__(self): self.is_function = False self.return_used = False self.create_guard_next = False self.create_guard_now = False def __repr__(self): return 'used: {}'.format( self.return_used) class _Function(object): def __init__(self): self.do_return_var_name = None self.retval_var_name = None def __repr__(self): return 'return control: {}, return value: {}'.format( self.do_return_var_name, self.retval_var_name) class ReturnStatementsTransformer(converter.Base): """Lowers return statements into variables and conditionals. Specifically, the following pattern: <block 1> return val <block 2> is converted to: do_return = False retval = None <block 1> do_return = True retval = val if not do_return: <block 2> return retval The conversion adjusts loops as well: <block 1> while cond: <block 2> return retval is converted to: <block 1> while not do_return and cond: <block 2> do_return = True retval = val """ def __init__(self, ctx, default_to_null_return): super(ReturnStatementsTransformer, self).__init__(ctx) self.default_to_null_return = default_to_null_return def visit_Return(self, node): for block in reversed(self.state[_Block].stack): block.return_used = True block.create_guard_next = True if block.is_function: break retval = node.value if node.value else parser.parse_expression('None') template = """ do_return_var_name = True retval_var_name = retval """ node = templates.replace( template, do_return_var_name=self.state[_Function].do_return_var_name, retval_var_name=self.state[_Function].retval_var_name, retval=retval) return node def _postprocess_statement(self, node): if not self.state[_Block].return_used: return node, None state = self.state[_Block] if state.create_guard_now: template = """ if ag__.not_(do_return_var_name): original_node """ cond, = templates.replace( template, do_return_var_name=self.state[_Function].do_return_var_name, original_node=node) node, block = cond, cond.body else: node, block = node, None state.create_guard_now = state.create_guard_next state.create_guard_next = False return node, block def _visit_statement_block(self, node, nodes): self.state[_Block].enter() nodes = self.visit_block(nodes, after_visit=self._postprocess_statement) self.state[_Block].exit() return nodes def visit_While(self, node): node.test = self.visit(node.test) # Add the check for return to the loop condition. node.body = self._visit_statement_block(node, node.body) if self.state[_Block].return_used: node.test = templates.replace_as_expression( 'ag__.and_(lambda: ag__.not_(control_var), lambda: test)', test=node.test, control_var=self.state[_Function].do_return_var_name) node.orelse = self._visit_statement_block(node, node.orelse) return node def visit_For(self, node): node.iter = self.visit(node.iter) node.target = self.visit(node.target) # Add the check for return to the loop condition. node.body = self._visit_statement_block(node, node.body) if self.state[_Block].return_used: extra_test = anno.getanno(node, 'extra_test', default=None) if extra_test is not None: extra_test = templates.replace_as_expression( 'ag__.and_(lambda: ag__.not_(control_var), lambda: extra_test)', extra_test=extra_test, control_var=self.state[_Function].do_return_var_name) else: extra_test = templates.replace_as_expression( 'ag__.not_(control_var)', control_var=self.state[_Function].do_return_var_name) anno.setanno(node, 'extra_test', extra_test) node.orelse = self._visit_statement_block(node, node.orelse) return node def visit_With(self, node): node.items = self.visit_block(node.items) node.body = self._visit_statement_block(node, node.body) return node def visit_Try(self, node): node.body = self._visit_statement_block(node, node.body) node.orelse = self._visit_statement_block(node, node.orelse) node.finalbody = self._visit_statement_block(node, node.finalbody) node.handlers = self.visit_block(node.handlers) return node def visit_ExceptHandler(self, node): node.body = self._visit_statement_block(node, node.body) return node def visit_If(self, node): node.test = self.visit(node.test) node.body = self._visit_statement_block(node, node.body) node.orelse = self._visit_statement_block(node, node.orelse) return node def visit_FunctionDef(self, node): self.state[_Function].enter() self.state[_Block].enter() self.state[_Block].is_function = True scope = anno.getanno(node, NodeAnno.BODY_SCOPE) do_return_var_name = self.ctx.namer.new_symbol( 'do_return', scope.referenced) retval_var_name = self.ctx.namer.new_symbol('retval_', scope.referenced) self.state[_Function].do_return_var_name = do_return_var_name self.state[_Function].retval_var_name = retval_var_name converted_body = self._visit_statement_block(node, node.body) # Avoid placing statements before any eventual docstring. # TODO(mdan): Should a docstring even be included in the output? docstring = None if converted_body: if (isinstance(converted_body[0], gast.Expr) and isinstance(converted_body[0].value, gast.Str)): docstring = converted_body[0] converted_body = converted_body[1:] if self.state[_Block].return_used: if self.default_to_null_return: template = """ do_return_var_name = False retval_var_name = ag__.UndefinedReturnValue() body # TODO(b/134753123) Remove the do_return_var_name tuple. (do_return_var_name,) return ag__.retval(retval_var_name) """ else: # TODO(b/134753123) Fix loops that return when do_return is not set. template = """ body return retval_var_name """ node.body = templates.replace( template, body=converted_body, do_return_var_name=do_return_var_name, retval_var_name=retval_var_name) if docstring: node.body.insert(0, docstring) self.state[_Block].exit() self.state[_Function].exit() return node def transform(node, ctx, default_to_null_return=True): """Ensure a function has only a single return.""" # Note: Technically, these two could be merged into a single walk, but # keeping them separate helps with readability. node = ConditionalReturnRewriter(ctx).visit(node) transformer = ReturnStatementsTransformer( ctx, default_to_null_return=default_to_null_return) node = transformer.visit(node) return node
tensorflow-master
tensorflow/python/autograph/converters/return_statements.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Converter for logical expressions, e.g. `a and b -> tf.logical_and(a, b)`.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import templates # TODO(mdan): Properly extrack boolean ops according to lazy eval rules. # Note that this isn't completely safe either, because tensors may have control # dependencies. # Note that for loops that should be done after the loop was converted to # tf.while_loop so that the expanded conditionals are properly scoped. # Used to signal that an operand is safe for non-lazy evaluation. SAFE_BOOLEAN_OPERAND = 'SAFE_BOOLEAN_OPERAND' LOGICAL_OPERATORS = { gast.And: 'ag__.and_', gast.Not: 'ag__.not_', gast.Or: 'ag__.or_', } EQUALITY_OPERATORS = { gast.Eq: 'ag__.eq', gast.NotEq: 'ag__.not_eq', } class LogicalExpressionTransformer(converter.Base): """Converts logical expressions to corresponding TF calls.""" def _overload_of(self, operator): op_type = type(operator) if op_type in LOGICAL_OPERATORS: return LOGICAL_OPERATORS[op_type] if self.ctx.program.options.uses(converter.Feature.EQUALITY_OPERATORS): if op_type in EQUALITY_OPERATORS: return EQUALITY_OPERATORS[op_type] return None def _as_lambda(self, expr): return templates.replace_as_expression('lambda: expr', expr=expr) def _as_binary_function(self, func_name, arg1, arg2): return templates.replace_as_expression( 'func_name(arg1, arg2)', func_name=parser.parse_expression(func_name), arg1=arg1, arg2=arg2) def _as_binary_operation(self, op, arg1, arg2): template = templates.replace_as_expression( 'arg1 is arg2', arg1=arg1, arg2=arg2) template.ops[0] = op return template def _as_unary_function(self, func_name, arg): return templates.replace_as_expression( 'func_name(arg)', func_name=parser.parse_expression(func_name), arg=arg) def visit_Compare(self, node): node = self.generic_visit(node) if (not self.ctx.program.options.uses( converter.Feature.EQUALITY_OPERATORS)): return node ops_and_comps = list(zip(node.ops, node.comparators)) left = node.left # Repeated comparisons are converted to conjunctions: # a < b < c -> a < b and b < c op_tree = None while ops_and_comps: op, right = ops_and_comps.pop(0) overload = self._overload_of(op) if overload is not None: binary_comparison = self._as_binary_function(overload, left, right) else: binary_comparison = self._as_binary_operation(op, left, right) if op_tree is not None: op_tree = self._as_binary_function('ag__.and_', self._as_lambda(op_tree), self._as_lambda(binary_comparison)) else: op_tree = binary_comparison left = right assert op_tree is not None return op_tree def visit_UnaryOp(self, node): node = self.generic_visit(node) overload = self._overload_of(node.op) if overload is None: return node return self._as_unary_function(overload, node.operand) def visit_BoolOp(self, node): node = self.generic_visit(node) node_values = node.values right = node.values.pop() while node_values: left = node_values.pop() right = self._as_binary_function( self._overload_of(node.op), self._as_lambda(left), self._as_lambda(right)) return right def transform(node, ctx): transformer = LogicalExpressionTransformer(ctx) return transformer.visit(node)
tensorflow-master
tensorflow/python/autograph/converters/logical_expressions.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for asserts module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.converters import asserts from tensorflow.python.autograph.converters import side_effect_guards from tensorflow.python.autograph.core import converter_testing from tensorflow.python.framework import constant_op from tensorflow.python.framework import errors_impl from tensorflow.python.framework import test_util from tensorflow.python.ops import gen_control_flow_ops from tensorflow.python.platform import test class AssertsTest(converter_testing.TestCase): @test_util.run_deprecated_v1 def test_basic(self): def test_fn(a): assert a, 'test message' return tf.no_op() # pylint:disable=undefined-variable with self.converted(test_fn, (asserts, side_effect_guards), {}, gen_control_flow_ops.no_op) as result: with self.cached_session() as sess: op = result.test_fn(constant_op.constant(False)) with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, 'test message'): self.evaluate(op) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/asserts_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Modifies the signature to allow resolving the value of default arguments. Normally, function symbols are captured either in a function's globals or closure. This is not true for default arguments, which are evaluated when the function is defined: b = 1 c = 2 def f(a=b + 1): return a + c In the above example, the namespace of the function would include `c = 2` but not `b`. If we were to naively generate a new function: def new_f(a=b + 1): return a + c The generated code would fail to load unless we exposed a symbol `b`. Capturing the closure of such an expression is difficult. However, we can capture the default value of argument `a` with relative ease. This converter replaces all default argument expressions with a constant so that they don't cause loading to fail. This requires that the default values are reset after loading the transformed function: def new_f(a=None): return a + c # ... later, after new_f was loaded ... new_f.__defaults__ = f.__defaults__ """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.pyct import parser class _Function(object): pass class ArgDefaultsTransformer(converter.Base): """Transforms top level argument defaults.""" def visit_Lambda(self, node): self.state[_Function].enter() node.args = self.visit(node.args) # Only the top level function is modified - no need to visit the children. self.state[_Function].exit() return node def visit_FunctionDef(self, node): self.state[_Function].enter() node.args = self.visit(node.args) # Only the top level function is modified - no need to visit the children. self.state[_Function].exit() return node def visit_arguments(self, node): if self.state[_Function].level > 2: return node for i in range(len(node.defaults)): node.defaults[i] = parser.parse_expression('None') for i, d in enumerate(node.kw_defaults): if d is not None: node.kw_defaults[i] = parser.parse_expression('None') # Only the top level function is modified - no need to visit the children. return node def transform(node, ctx): """Transform function call to the compiled counterparts. Args: node: AST ctx: EntityContext Returns: A tuple (node, new_names): node: The transformed AST new_names: set(string), containing any newly-generated names """ return ArgDefaultsTransformer(ctx).visit(node)
tensorflow-master
tensorflow/python/autograph/converters/arg_defaults.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for function_scopes module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.converters import function_scopes from tensorflow.python.autograph.core import converter_testing from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.platform import test class FunctionBodyTransformerTest(converter_testing.TestCase): @test_util.run_deprecated_v1 def test_basic(self): def test_fn(l): """Docstring.""" a = 1 l += a return l with self.converted(test_fn, function_scopes, {}) as result: result_op = result.test_fn(constant_op.constant(1)) self.assertIn('test_fn/', result_op.op.name) self.assertEqual('Docstring.', result.test_fn.__doc__) @test_util.run_deprecated_v1 def test_multiline_docstring(self): tf = None def test_fn(): """First sentence. Second sentence. """ return tf.constant(1) with self.converted(test_fn, function_scopes, {}, constant_op.constant) as result: result_op = result.test_fn() self.assertIn('test_fn/', result_op.op.name) self.assertIn('First sentence.', result.test_fn.__doc__) self.assertIn('Second sentence.', result.test_fn.__doc__) @test_util.run_deprecated_v1 def test_nested_functions(self): def test_fn(l): def inner_fn(i): return i + 1 l += 1 return l, inner_fn(l) with self.converted(test_fn, function_scopes, {}, ops.name_scope) as result: first, second = result.test_fn(constant_op.constant(1)) self.assertIn('test_fn/', first.op.name) self.assertNotIn('inner_fn', first.op.name) self.assertIn('test_fn/inner_fn/', second.op.name) @test_util.run_deprecated_v1 def test_method(self): class TestClass(object): def test_fn(self, l): def inner_fn(i): return i + 1 l += 1 return l, inner_fn(l) ns = {'TestClass': TestClass} node, ctx = self.prepare(TestClass, ns) node = function_scopes.transform(node, ctx) with self.compiled(node, {}, ops.name_scope) as result: first, second = result.TestClass().test_fn(constant_op.constant(1)) self.assertIn('TestClass/test_fn/', first.op.name) self.assertNotIn('inner_fn', first.op.name) self.assertIn('TestClass/test_fn/inner_fn/', second.op.name) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/function_scopes_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Handles control flow statements: while, for, if.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import ast_util from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import templates from tensorflow.python.autograph.pyct.static_analysis import annos # TODO(mdan): Refactor functions to make them smaller. class ControlFlowTransformer(converter.Base): """Transforms control flow structures like loops an conditionals.""" def _create_cond_branch(self, body_name, aliased_orig_names, aliased_new_names, body, returns): if not returns: # TODO(b/110167197): Replace with a plain return. template = """ return 1 """ return_stmt = templates.replace(template) elif len(returns) == 1: template = """ return retval """ return_stmt = templates.replace(template, retval=returns[0]) else: template = """ return (retvals,) """ return_stmt = templates.replace(template, retvals=returns) if aliased_orig_names: template = """ def body_name(): aliased_new_names, = aliased_orig_names, body return_stmt """ return templates.replace( template, body_name=body_name, body=body, aliased_orig_names=aliased_orig_names, aliased_new_names=aliased_new_names, return_stmt=return_stmt) else: template = """ def body_name(): body return_stmt """ return templates.replace( template, body_name=body_name, body=body, return_stmt=return_stmt) def _create_cond_expr(self, results, test, body_name, orelse_name, state_getter_name, state_setter_name): if results is not None: template = """ results = ag__.if_stmt(test, body_name, orelse_name, state_getter_name, state_setter_name) """ return templates.replace( template, test=test, results=results, body_name=body_name, orelse_name=orelse_name, state_getter_name=state_getter_name, state_setter_name=state_setter_name) else: template = """ ag__.if_stmt(test, body_name, orelse_name, getter_name, setter_name) """ return templates.replace( template, test=test, body_name=body_name, orelse_name=orelse_name, getter_name=state_getter_name, setter_name=state_setter_name) def _fmt_symbols(self, symbol_set): if not symbol_set: return 'no variables' return ', '.join(map(str, symbol_set)) def _determine_aliased_symbols(self, scope, node_defined_in, block): if block: block_live_in = set(anno.getanno(block[0], anno.Static.LIVE_VARS_IN)) else: block_live_in = set() modified_live = scope.modified & node_defined_in & block_live_in # Composite symbols are handled elsewhere see _create_state_functions return {s for s in modified_live if not s.is_composite()} def _create_state_functions(self, composites, state_getter_name, state_setter_name): if composites: composite_tuple = tuple(composites) template = """ def state_getter_name(): return composite_tuple, def state_setter_name(vals): composite_tuple, = vals """ node = templates.replace( template, state_getter_name=state_getter_name, state_setter_name=state_setter_name, composite_tuple=composite_tuple) else: template = """ def state_getter_name(): return () def state_setter_name(_): pass """ node = templates.replace( template, state_getter_name=state_getter_name, state_setter_name=state_setter_name) return node def _create_undefined_assigns(self, undefined_symbols): assignments = [] for s in undefined_symbols: template = ''' var = ag__.Undefined(symbol_name) ''' assignments += templates.replace( template, var=s, symbol_name=gast.Str(s.ssf())) return assignments def visit_If(self, node): body_scope = anno.getanno(node, annos.NodeAnno.BODY_SCOPE) orelse_scope = anno.getanno(node, annos.NodeAnno.ORELSE_SCOPE) defined_in = anno.getanno(node, anno.Static.DEFINED_VARS_IN) live_out = anno.getanno(node, anno.Static.LIVE_VARS_OUT) # Note: this information needs to be extracted before the body conversion # that happens in the call to generic_visit below, because the conversion # generates nodes that lack static analysis annotations. need_alias_in_body = self._determine_aliased_symbols( body_scope, defined_in, node.body) need_alias_in_orelse = self._determine_aliased_symbols( orelse_scope, defined_in, node.orelse) node = self.generic_visit(node) modified_in_cond = body_scope.modified | orelse_scope.modified returned_from_cond = set() composites = set() for s in modified_in_cond: if s in live_out and not s.is_composite(): returned_from_cond.add(s) if s.is_composite(): # Special treatment for compound objects, always return them. # This allows special handling within the if_stmt itself. # For example, in TensorFlow we need to restore the state of composite # symbols to ensure that only effects from the executed branch are seen. composites.add(s) created_in_body = body_scope.modified & returned_from_cond - defined_in created_in_orelse = orelse_scope.modified & returned_from_cond - defined_in basic_created_in_body = tuple( s for s in created_in_body if not s.is_composite()) basic_created_in_orelse = tuple( s for s in created_in_orelse if not s.is_composite()) # These variables are defined only in a single branch. This is fine in # Python so we pass them through. Another backend, e.g. Tensorflow, may need # to handle these cases specially or throw an Error. possibly_undefined = (set(basic_created_in_body) ^ set(basic_created_in_orelse)) # Alias the closure variables inside the conditional functions, to allow # the functions access to the respective variables. # We will alias variables independently for body and orelse scope, # because different branches might write different variables. aliased_body_orig_names = tuple(need_alias_in_body) aliased_orelse_orig_names = tuple(need_alias_in_orelse) aliased_body_new_names = tuple( self.ctx.namer.new_symbol(s.ssf(), body_scope.referenced) for s in aliased_body_orig_names) aliased_orelse_new_names = tuple( self.ctx.namer.new_symbol(s.ssf(), orelse_scope.referenced) for s in aliased_orelse_orig_names) alias_body_map = dict(zip(aliased_body_orig_names, aliased_body_new_names)) alias_orelse_map = dict( zip(aliased_orelse_orig_names, aliased_orelse_new_names)) node_body = ast_util.rename_symbols(node.body, alias_body_map) node_orelse = ast_util.rename_symbols(node.orelse, alias_orelse_map) cond_var_name = self.ctx.namer.new_symbol('cond', body_scope.referenced) body_name = self.ctx.namer.new_symbol('if_true', body_scope.referenced) orelse_name = self.ctx.namer.new_symbol('if_false', orelse_scope.referenced) all_referenced = body_scope.referenced | orelse_scope.referenced state_getter_name = self.ctx.namer.new_symbol('get_state', all_referenced) state_setter_name = self.ctx.namer.new_symbol('set_state', all_referenced) returned_from_cond = tuple(returned_from_cond) if returned_from_cond: if len(returned_from_cond) == 1: cond_results = returned_from_cond[0] else: cond_results = gast.Tuple([s.ast() for s in returned_from_cond], None) returned_from_body = tuple( alias_body_map[s] if s in need_alias_in_body else s for s in returned_from_cond) returned_from_orelse = tuple( alias_orelse_map[s] if s in need_alias_in_orelse else s for s in returned_from_cond) else: # When the cond would return no value, we leave the cond called without # results. That in turn should trigger the side effect guards. The # branch functions will return a dummy value that ensures cond # actually has some return value as well. cond_results = None # TODO(mdan): Replace with None once side_effect_guards is retired. returned_from_body = (templates.replace_as_expression( 'ag__.match_staging_level(1, cond_var_name)', cond_var_name=cond_var_name),) returned_from_orelse = (templates.replace_as_expression( 'ag__.match_staging_level(1, cond_var_name)', cond_var_name=cond_var_name),) cond_assign = self.create_assignment(cond_var_name, node.test) body_def = self._create_cond_branch( body_name, aliased_orig_names=aliased_body_orig_names, aliased_new_names=aliased_body_new_names, body=node_body, returns=returned_from_body) orelse_def = self._create_cond_branch( orelse_name, aliased_orig_names=aliased_orelse_orig_names, aliased_new_names=aliased_orelse_new_names, body=node_orelse, returns=returned_from_orelse) undefined_assigns = self._create_undefined_assigns(possibly_undefined) composite_defs = self._create_state_functions( composites, state_getter_name, state_setter_name) cond_expr = self._create_cond_expr(cond_results, cond_var_name, body_name, orelse_name, state_getter_name, state_setter_name) if_ast = ( undefined_assigns + composite_defs + body_def + orelse_def + cond_assign + cond_expr) return if_ast def _get_basic_loop_vars(self, modified_symbols, live_in, live_out): # The loop variables corresponding to simple symbols (e.g. `x`). basic_loop_vars = [] for s in modified_symbols: if s.is_composite(): # TODO(mdan): Raise an error when this happens for a TF loop. continue # Variables not live into or out of the loop are considered local to the # loop. if s not in live_in and s not in live_out: continue basic_loop_vars.append(s) return frozenset(basic_loop_vars) def _get_composite_loop_vars(self, modified_symbols, live_in): # The loop variables corresponding to composite symbols (e.g. `self.x`). composite_loop_vars = [] for s in modified_symbols: if not s.is_composite(): continue # Mutations made to objects created inside the loop will appear as writes # to composite symbols. Because these mutations appear as modifications # made to composite symbols, we check whether the composite's parent is # actually live into the loop. # Example: # while cond: # x = Foo() # x.foo = 2 * x.foo # x.foo is live into the loop, but x is not. if not all(p in live_in for p in s.support_set): continue composite_loop_vars.append(s) return frozenset(composite_loop_vars) def _get_loop_vars(self, node, modified_symbols): body_scope = anno.getanno(node, annos.NodeAnno.BODY_SCOPE) defined_in = anno.getanno(node, anno.Static.DEFINED_VARS_IN) live_in = anno.getanno(node, anno.Static.LIVE_VARS_IN) live_out = anno.getanno(node, anno.Static.LIVE_VARS_OUT) reserved_symbols = body_scope.referenced basic_loop_vars = self._get_basic_loop_vars( modified_symbols, live_in, live_out) composite_loop_vars = self._get_composite_loop_vars( modified_symbols, live_in) # Variable that are used or defined inside the loop, but not defined # before entering the loop. Only simple variables must be defined. The # composite ones will be implicitly checked at runtime. undefined_lives = basic_loop_vars - defined_in return (basic_loop_vars, composite_loop_vars, reserved_symbols, undefined_lives) def _loop_var_constructs(self, basic_loop_vars): loop_vars = tuple(basic_loop_vars) loop_vars_ast_tuple = gast.Tuple([n.ast() for n in loop_vars], None) if len(loop_vars) == 1: loop_vars = loop_vars[0] return loop_vars, loop_vars_ast_tuple def visit_While(self, node): self.generic_visit(node) (basic_loop_vars, composite_loop_vars, reserved_symbols, possibly_undefs) = self._get_loop_vars( node, anno.getanno(node, annos.NodeAnno.BODY_SCOPE).modified) loop_vars, loop_vars_ast_tuple = self._loop_var_constructs( basic_loop_vars) state_getter_name = self.ctx.namer.new_symbol('get_state', reserved_symbols) state_setter_name = self.ctx.namer.new_symbol('set_state', reserved_symbols) state_functions = self._create_state_functions( composite_loop_vars, state_getter_name, state_setter_name) # TODO(mdan): Use a single template. # If the body and test functions took a single tuple for loop_vars, instead # of *loop_vars, then a single template could be used. if loop_vars: template = """ state_functions def body_name(loop_vars): body return loop_vars, def test_name(loop_vars): return test loop_vars_ast_tuple = ag__.while_stmt( test_name, body_name, state_getter_name, state_setter_name, (loop_vars,)) """ node = templates.replace( template, loop_vars=loop_vars, loop_vars_ast_tuple=loop_vars_ast_tuple, test_name=self.ctx.namer.new_symbol('loop_test', reserved_symbols), test=node.test, body_name=self.ctx.namer.new_symbol('loop_body', reserved_symbols), body=node.body, state_functions=state_functions, state_getter_name=state_getter_name, state_setter_name=state_setter_name) else: template = """ state_functions def body_name(): body return () def test_name(): return test ag__.while_stmt( test_name, body_name, state_getter_name, state_setter_name, ()) """ node = templates.replace( template, test_name=self.ctx.namer.new_symbol('loop_test', reserved_symbols), test=node.test, body_name=self.ctx.namer.new_symbol('loop_body', reserved_symbols), body=node.body, state_functions=state_functions, state_getter_name=state_getter_name, state_setter_name=state_setter_name) undefined_assigns = self._create_undefined_assigns(possibly_undefs) return undefined_assigns + node def visit_For(self, node): self.generic_visit(node) (basic_loop_vars, composite_loop_vars, reserved_symbols, possibly_undefs) = self._get_loop_vars( node, (anno.getanno(node, annos.NodeAnno.BODY_SCOPE).modified | anno.getanno(node, annos.NodeAnno.ITERATE_SCOPE).modified)) loop_vars, loop_vars_ast_tuple = self._loop_var_constructs( basic_loop_vars) body_name = self.ctx.namer.new_symbol('loop_body', reserved_symbols) state_getter_name = self.ctx.namer.new_symbol('get_state', reserved_symbols) state_setter_name = self.ctx.namer.new_symbol('set_state', reserved_symbols) state_functions = self._create_state_functions( composite_loop_vars, state_getter_name, state_setter_name) if anno.hasanno(node, 'extra_test'): extra_test = anno.getanno(node, 'extra_test') extra_test_name = self.ctx.namer.new_symbol( 'extra_test', reserved_symbols) template = """ def extra_test_name(loop_vars): return extra_test_expr """ extra_test_function = templates.replace( template, extra_test_name=extra_test_name, loop_vars=loop_vars, extra_test_expr=extra_test) else: extra_test_name = parser.parse_expression('None') extra_test_function = [] # Workaround for PEP-3113 # iterates_var holds a single variable with the iterates, which may be a # tuple. iterates_var_name = self.ctx.namer.new_symbol( 'iterates', reserved_symbols) template = """ iterates = iterates_var_name """ iterate_expansion = templates.replace( template, iterates=node.target, iterates_var_name=iterates_var_name) undefined_assigns = self._create_undefined_assigns(possibly_undefs) # TODO(mdan): Use a single template. # If the body and test functions took a single tuple for loop_vars, instead # of *loop_vars, then a single template could be used. if loop_vars: template = """ undefined_assigns state_functions def body_name(iterates_var_name, loop_vars): iterate_expansion body return loop_vars, extra_test_function loop_vars_ast_tuple = ag__.for_stmt( iter_, extra_test_name, body_name, state_getter_name, state_setter_name, (loop_vars,)) """ return templates.replace( template, undefined_assigns=undefined_assigns, loop_vars=loop_vars, loop_vars_ast_tuple=loop_vars_ast_tuple, iter_=node.iter, iterate_expansion=iterate_expansion, iterates_var_name=iterates_var_name, extra_test_name=extra_test_name, extra_test_function=extra_test_function, body_name=body_name, body=node.body, state_functions=state_functions, state_getter_name=state_getter_name, state_setter_name=state_setter_name) else: template = """ undefined_assigns state_functions def body_name(iterates_var_name): iterate_expansion body return () extra_test_function ag__.for_stmt( iter_, extra_test_name, body_name, state_getter_name, state_setter_name, ()) """ return templates.replace( template, undefined_assigns=undefined_assigns, iter_=node.iter, iterate_expansion=iterate_expansion, iterates_var_name=iterates_var_name, extra_test_name=extra_test_name, extra_test_function=extra_test_function, body_name=body_name, body=node.body, state_functions=state_functions, state_getter_name=state_getter_name, state_setter_name=state_setter_name) def transform(node, ctx): node = ControlFlowTransformer(ctx).visit(node) return node
tensorflow-master
tensorflow/python/autograph/converters/control_flow.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Handles function calls, by generating compiled function names and calls. Note: this transformer does not rename the top level object being converted; that is the caller's responsibility. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import ast_util from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import templates # TODO(mdan): Rename to FunctionCallsTransformer. class _Function(object): no_root = True class CallTreeTransformer(converter.Base): """Transforms the call tree by renaming transformed symbols.""" def visit_FunctionDef(self, node): self.state[_Function].enter() node.args = self.visit(node.args) node.body = self.visit_block(node.body) if self.state[_Function].level < 2: # Top-level functions lose their decorator because the conversion is # always just-in-time and by the time it happens the decorators are # already set to be applied. node.decorator_list = [] else: # Inner functions are converted already, so we insert a decorator to # prevent double conversion. Double conversion would work too, but this # saves the overhead. node.decorator_list.append( parser.parse_expression('ag__.do_not_convert_internal')) if node.returns: node.returns = self.visit(node.returns) self.state[_Function].exit() return node def visit_With(self, node): # Context manager calls (in node.items) are not converted. node.body = self.visit_block(node.body) return node def visit_Call(self, node): # TODO(mdan): Refactor converted_call as a 'Call' operator. # Calls to the internal 'ag__' module are never converted (though their # arguments might be). full_name = str(anno.getanno(node.func, anno.Basic.QN, default='')) if full_name.startswith('ag__.'): return self.generic_visit(node) if (full_name == 'print' and not self.ctx.program.options.uses(converter.Feature.BUILTIN_FUNCTIONS)): return self.generic_visit(node) if isinstance(node.func, gast.Attribute): func = gast.Str(node.func.attr) owner = node.func.value else: func = node.func owner = parser.parse_expression('None') starred_arg = None normal_args = [] for a in node.args: if isinstance(a, gast.Starred): assert starred_arg is None, 'Multiple *args should be impossible.' starred_arg = a else: a = self.visit(a) normal_args.append(a) if starred_arg is None: args = templates.replace_as_expression('(args,)', args=normal_args) else: args = templates.replace_as_expression( '(args,) + tuple(stararg)', stararg=starred_arg.value, args=normal_args) kwargs_arg = None normal_keywords = [] for k in node.keywords: if k.arg is None: assert kwargs_arg is None, 'Multiple **kwargs should be impossible.' kwargs_arg = k else: k = self.visit(k) normal_keywords.append(k) if kwargs_arg is None: if not normal_keywords: kwargs = parser.parse_expression('None') else: kwargs = ast_util.keywords_to_dict(normal_keywords) else: kwargs = templates.replace_as_expression( 'dict(kwargs, **keywords)', kwargs=kwargs_arg.value, keywords=ast_util.keywords_to_dict(normal_keywords)) template = """ ag__.converted_call(func, owner, options, args, kwargs) """ new_call = templates.replace_as_expression( template, func=func, owner=owner, options=self.ctx.program.options.to_ast( internal_convert_user_code=self.ctx.program.options.recursive), args=args, kwargs=kwargs) return new_call def visit_Print(self, node): node = self.generic_visit(node) args = node.values # Following is the case when calling print(a, b) if len(args) == 1 and isinstance(args[0], gast.Tuple): args = args[0].elts template = """ ag__.converted_call(func, None, options, args, {}) """ return templates.replace_as_expression( template, func='print', options=self.ctx.program.options.to_ast(), args=args) def transform(node, ctx): """Transform function call to the compiled counterparts. Args: node: AST ctx: EntityContext Returns: A tuple (node, new_names): node: The transformed AST new_names: set(string), containing any newly-generated names """ return CallTreeTransformer(ctx).visit(node)
tensorflow-master
tensorflow/python/autograph/converters/call_trees.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Code converters used by Autograph.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Naming conventions: # * each converter should specialize on a single idiom; be consistent with # the Python reference for naming # * all converters inherit core.converter.Base # * module names describe the idiom that the converter covers, plural # * the converter class is named consistent with the module, singular and # includes the word Transformer # # Example: # # lists.py # class ListTransformer(converter.Base)
tensorflow-master
tensorflow/python/autograph/converters/__init__.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Lowers break statements to conditionals.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import templates from tensorflow.python.autograph.pyct.static_analysis.annos import NodeAnno class _Break(object): def __init__(self): self.used = False self.control_var_name = None def __repr__(self): return 'used: %s, var: %s' % (self.used, self.control_var_name) class BreakTransformer(converter.Base): """Canonicalizes break statements into additional conditionals.""" def visit_Break(self, node): self.state[_Break].used = True var_name = self.state[_Break].control_var_name # TODO(mdan): This will fail when expanded inside a top-level else block. template = """ var_name = True continue """ return templates.replace(template, var_name=var_name) def _guard_if_present(self, block, var_name): """Prevents the block from executing if var_name is set.""" if not block: return block template = """ if ag__.not_(var_name): block """ node = templates.replace( template, var_name=var_name, block=block) return node def _process_body(self, nodes, break_var): self.state[_Break].enter() self.state[_Break].control_var_name = break_var nodes = self.visit_block(nodes) break_used = self.state[_Break].used self.state[_Break].exit() return nodes, break_used def visit_While(self, node): scope = anno.getanno(node, NodeAnno.BODY_SCOPE) break_var = self.ctx.namer.new_symbol('break_', scope.referenced) node.test = self.visit(node.test) node.body, break_used = self._process_body(node.body, break_var) # A break in the else clause applies to the containing scope. node.orelse = self.visit_block(node.orelse) if break_used: # Python's else clause only triggers if the loop exited cleanly (e.g. # break did not trigger). guarded_orelse = self._guard_if_present(node.orelse, break_var) template = """ var_name = False while ag__.and_(lambda: test, lambda: ag__.not_(var_name)): body else: orelse """ node = templates.replace( template, var_name=break_var, test=node.test, body=node.body, orelse=guarded_orelse) return node def visit_For(self, node): scope = anno.getanno(node, NodeAnno.BODY_SCOPE) break_var = self.ctx.namer.new_symbol('break_', scope.referenced) node.target = self.visit(node.target) node.iter = self.visit(node.iter) node.body, break_used = self._process_body(node.body, break_var) # A break in the else clause applies to the containing scope. node.orelse = self.visit_block(node.orelse) if break_used: # Python's else clause only triggers if the loop exited cleanly (e.g. # break did not trigger). guarded_orelse = self._guard_if_present(node.orelse, break_var) extra_test = templates.replace_as_expression( 'ag__.not_(var_name)', var_name=break_var) # The extra test is hidden in the AST, which will confuse the static # analysis. To mitigate that, we insert a no-op statement that ensures # the control variable is marked as used. # TODO(mdan): Use a marker instead, e.g. ag__.condition_loop_on(var_name) template = """ var_name = False for target in iter_: (var_name,) body else: orelse """ node = templates.replace( template, var_name=break_var, iter_=node.iter, target=node.target, body=node.body, orelse=guarded_orelse) anno.setanno(node[1], 'extra_test', extra_test) return node def transform(node, ctx): transformer = BreakTransformer(ctx) node = transformer.visit(node) return node
tensorflow-master
tensorflow/python/autograph/converters/break_statements.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Handles directives. This converter removes the directive functions from the code and moves the information they specify into AST annotations. It is a specialized form of static analysis, one that is specific to AutoGraph. Note that this requires that the actual directive functions are static - that is, they do not change at runtime. So if you do something like this: tf.autograph.set_loop_options = <new function> Then the directive will may no longer be recognized. Furthermore, if the converted function is cached, such an action action may be irreversible. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import inspect import gast from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.lang import directives from tensorflow.python.autograph.pyct import anno from tensorflow.python.util import tf_inspect ENCLOSING_LOOP = 'enclosing_loop' STATIC_VALUE = 'static_value' """Used for AST annotations, see visit_Name.""" def _map_args(call_node, function): """Maps AST call nodes to the actual function's arguments. Args: call_node: ast.Call function: Callable[..., Any], the actual function matching call_node Returns: Dict[Text, ast.AST], mapping each of the function's argument names to the respective AST node. Raises: ValueError: if the default arguments are not correctly set """ args = call_node.args kwds = {kwd.arg: kwd.value for kwd in call_node.keywords} call_args = tf_inspect.getcallargs(function, *args, **kwds) # Keyword arguments not specified in kwds will be mapped to their defaults, # which are Python values. Since we don't currently have a way to transform # those into AST references, we simply remove them. By convention, directives # use UNSPECIFIED as default value for for optional arguments. No other # defaults should be present. unexpected_defaults = [] for k in call_args: if (k not in kwds and call_args[k] not in args and call_args[k] is not directives.UNSPECIFIED): unexpected_defaults.append(k) if unexpected_defaults: raise ValueError('Unexpected keyword argument values, %s, for function %s' % (zip(unexpected_defaults, [call_args[k] for k in unexpected_defaults]), function)) return {k: v for k, v in call_args.items() if v is not directives.UNSPECIFIED} class DirectivesTransformer(converter.Base): """Parses compiler directives and converts them into AST annotations.""" def _process_symbol_directive(self, call_node, directive): if len(call_node.args) < 1: raise ValueError('"%s" requires a positional first argument' ' as the target' % directive.__name__) target = call_node.args[0] defs = anno.getanno(target, anno.Static.ORIG_DEFINITIONS) for def_ in defs: def_.directives[directive] = _map_args(call_node, directive) return call_node def _process_statement_directive(self, call_node, directive): if self.local_scope_level < 2: raise ValueError( '"%s" must be used inside a statement' % directive.__name__) target = self.get_local(ENCLOSING_LOOP) node_anno = anno.getanno(target, converter.AgAnno.DIRECTIVES, {}) node_anno[directive] = _map_args(call_node, directive) anno.setanno(target, converter.AgAnno.DIRECTIVES, node_anno) return call_node def visit_Name(self, node): node = self.generic_visit(node) if isinstance(node.ctx, gast.Load): defs = anno.getanno(node, anno.Static.DEFINITIONS, ()) is_defined = bool(defs) if not is_defined and node.id in self.ctx.info.namespace: anno.setanno(node, STATIC_VALUE, self.ctx.info.namespace[node.id]) return node def visit_Attribute(self, node): node = self.generic_visit(node) parent_val = anno.getanno(node.value, STATIC_VALUE, default=None) if parent_val is not None and inspect.ismodule(parent_val): if hasattr(parent_val, node.attr): anno.setanno(node, STATIC_VALUE, getattr(parent_val, node.attr)) return node def visit_Expr(self, node): node = self.generic_visit(node) if isinstance(node.value, gast.Call): call_node = node.value static_val = anno.getanno(call_node.func, STATIC_VALUE, default=None) if static_val is not None: # Note: directive calls are not output in the generated code, hence # the removal from the code by returning None. if static_val is directives.set_element_type: self._process_symbol_directive(call_node, static_val) return None elif static_val is directives.set_loop_options: self._process_statement_directive(call_node, static_val) return None return node # TODO(mdan): This will be insufficient for other control flow. # That means that if we ever have a directive that affects things other than # loops, we'll need support for parallel scopes, or have multiple converters. def _track_and_visit_loop(self, node): self.enter_local_scope() self.set_local(ENCLOSING_LOOP, node) node = self.generic_visit(node) self.exit_local_scope() return node def visit_While(self, node): return self._track_and_visit_loop(node) def visit_For(self, node): return self._track_and_visit_loop(node) def transform(node, ctx): return DirectivesTransformer(ctx).visit(node)
tensorflow-master
tensorflow/python/autograph/converters/directives.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Wraps the body of a converted function with auxiliary constructs.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.pyct import templates class FunctionBodyTransformer(converter.Base): """Wraps function bodies around autograph-specific boilerplate.""" def _name_for_current_scope(self): innermost = self.enclosing_entities[-1] if len(self.enclosing_entities) > 1: parent = self.enclosing_entities[-2] if isinstance(parent, gast.ClassDef): # Methods also take the name of their class. name = '%s/%s' % (parent.name, innermost.name) else: name = innermost.name else: name = innermost.name # Sanitize the name. # See https://www.tensorflow.org/api_docs/python/tf/Graph#name_scope # TensorFlow doesn't like leading underscores at the top level. while name[0] == '_': name = name[1:] return name def visit_FunctionDef(self, node): node = self.generic_visit(node) final_body = [] indented_body = node.body if node.body: first_statement = node.body[0] # Skip the docstring, if any. if (isinstance(first_statement, gast.Expr) and isinstance(first_statement.value, gast.Str)): indented_body = indented_body[1:] final_body.append(first_statement) template = """ with ag__.function_scope(scope_name): body """ scoped_body = templates.replace( template, scope_name=gast.Str(self._name_for_current_scope()), body=indented_body) final_body.extend(scoped_body) node.body = final_body return node def transform(node, ctx): return FunctionBodyTransformer(ctx).visit(node)
tensorflow-master
tensorflow/python/autograph/converters/function_scopes.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for list_comprehensions module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.converters import list_comprehensions from tensorflow.python.autograph.core import converter_testing from tensorflow.python.platform import test class ListCompTest(converter_testing.TestCase): def assertTransformedEquivalent(self, test_fn, *inputs): with self.converted(test_fn, list_comprehensions, {}) as result: self.assertEqual(test_fn(*inputs), result.test_fn(*inputs)) def test_basic(self): def test_fn(l): s = [e * e for e in l] return s self.assertTransformedEquivalent(test_fn, []) self.assertTransformedEquivalent(test_fn, [1, 2, 3]) def test_multiple_generators(self): def test_fn(l): s = [e * e for sublist in l for e in sublist] return s self.assertTransformedEquivalent(test_fn, []) self.assertTransformedEquivalent(test_fn, [[1], [2], [3]]) def test_cond(self): def test_fn(l): s = [e * e for e in l if e > 1] return s self.assertTransformedEquivalent(test_fn, []) self.assertTransformedEquivalent(test_fn, [1, 2, 3]) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/list_comprehensions_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for control_flow module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numpy as np from tensorflow.python.autograph.converters import control_flow from tensorflow.python.autograph.core import converter_testing from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import test_util from tensorflow.python.platform import test class ControlFlowTest(converter_testing.TestCase): def assertTransformedResult(self, test_fn, inputs, expected, symbols=None): if not isinstance(inputs, tuple): inputs = (inputs,) if not symbols: symbols = {} with self.converted(test_fn, control_flow, symbols, constant_op.constant) as result: self.assertAllEqual(self.evaluate(result.test_fn(*inputs)), expected) @test_util.run_deprecated_v1 def test_while_basic(self): def test_fn(n): i = 0 s = 0 while i < n: s += i i += 1 return s, i, n self.assertTransformedResult(test_fn, constant_op.constant(5), (10, 5, 5)) @test_util.run_deprecated_v1 def test_while_nested(self): def test_fn(n): i = 0 j = 0 s = 0 while i < n: while j < i: j += 3 u = i + j # 'u' is not defined within the inner loop s += u i += 1 j = 0 return s, i, j, n self.assertTransformedResult(test_fn, constant_op.constant(5), (25, 5, 0, 5)) @test_util.run_deprecated_v1 def test_while_single_output(self): def test_fn(n): while n > 0: n -= 1 return n self.assertTransformedResult(test_fn, constant_op.constant(5), 0) def test_while_composite_state(self): class TestClass(object): def __init__(self): self.x = constant_op.constant(3) def test_fn(n): tc = TestClass() while n > 0: tc.x += 1 n -= 1 return n self.assertTransformedResult( test_fn, constant_op.constant(5), 0, symbols={'TestClass': TestClass}) def test_while_composite_state_initialized_in_loop(self): class TestClass(object): pass def test_fn(n, x): tc = TestClass() while n < 5: if n == 0: tc.x = x else: tc.x = tc.x + 1 n += 1 return tc.x self.assertTransformedResult( test_fn, (0, constant_op.constant(10)), 14, symbols={'TestClass': TestClass}) with self.converted( test_fn, control_flow, {'TestClass': TestClass}) as result: # TODO(b/128519776): Better error message. with self.assertRaisesRegex( AttributeError, '\'TestClass\' object has no attribute \'x\''): result.test_fn(constant_op.constant(0), constant_op.constant(5)) def test_while_nested_composite_state(self): class TestClass(object): def __init__(self): self.x = constant_op.constant(3) def test_fn(n): tc = TestClass() while n > 0: if n < 2: tc.x += 1 n -= 1 return n self.assertTransformedResult( test_fn, constant_op.constant(5), 0, symbols={'TestClass': TestClass}) def test_while_local_composite(self): class TestClass(object): def __init__(self): self.x = constant_op.constant(3) def test_fn(n): while n > 0: tc = TestClass() tc.x = tc.x n -= 1 return n self.assertTransformedResult( test_fn, constant_op.constant(5), 0, symbols={'TestClass': TestClass}) # TODO(b/127642077): Add tests for x.y.z = 2*x.y.z and x.y[z] = 2*x.y[z]. def test_while_local_composite_complex_nestable(self): # This class is ok to be in a tf.while_loop's state. class TestClass(collections.namedtuple('TestClass', ('x'))): pass def test_fn(n): tc = TestClass([constant_op.constant(0)]) while n > 0: tc = TestClass([constant_op.constant(3)]) tc.x[0] = tc.x[0] + 1 n -= 1 return tc.x[0] ns = {'TestClass': TestClass, 'constant_op': constant_op} self.assertTransformedResult( test_fn, constant_op.constant(5), 4, symbols=ns) def test_while_local_composite_complex_illegal(self): class TestClass(object): def __init__(self): self.x = [constant_op.constant(3)] def test_fn(n): while n > 0: tc = TestClass() tc.x[0] = tc.x[0] + 1 n -= 1 return tc.x[0] with self.converted( test_fn, control_flow, {'TestClass': TestClass}) as result: # The tested function would require `tc` to become part of the while loop # state, but TensorFlow doesn't support classes at the moment. with self.assertRaisesRegexp( ValueError, 'must be defined before the loop:.*tc.*'): result.test_fn(constant_op.constant(5)) @test_util.run_deprecated_v1 def test_while_dispatches_by_cond_only(self): class TensorIncompatibleNumeric(object): """Works in arithmetic expression, but errors out with TF ops.""" def __init__(self, val): self.val = val def __add__(self, other): return TensorIncompatibleNumeric(self.val + other) def test_fn(n, s): while n > 0: n -= 1 s += n return s self.assertTransformedResult(test_fn, (constant_op.constant(5), 0), 10) with self.converted(test_fn, control_flow, {}) as result: # n alone controls the staging. When the loop is not staged, Python # knows how to add the two objects. But when staged, tf.while_loop will # not know how to deal with the TensorIncompatibleNumeric object. self.assertEqual(result.test_fn(5, TensorIncompatibleNumeric(0)).val, 10) with self.assertRaises(TypeError): result.test_fn(constant_op.constant(5), TensorIncompatibleNumeric(0)) @test_util.run_deprecated_v1 def test_if_basic(self): def test_fn(n): a = 0 b = 0 if n > 0: a = -n else: b = 2 * n return a, b self.assertTransformedResult(test_fn, constant_op.constant(1), (-1, 0)) self.assertTransformedResult(test_fn, constant_op.constant(-1), (0, -2)) def test_if_sparse_tensor(self): def test_fn(cond, a): if cond: a = -a return a st = sparse_tensor.SparseTensor( indices=((0,),), values=(0,), dense_shape=(1,)) self.assertTransformedResult(test_fn, (st, constant_op.constant(1)), -1) self.assertTransformedResult(test_fn, (None, constant_op.constant(1)), 1) @test_util.run_deprecated_v1 def test_if_complex_outputs(self): class TestClass(object): def __init__(self, a, b): self.a = a self.b = b def test_fn(n, obj): obj.a = 0 obj.b = 0 if n > 0: obj.a = -n else: obj.b = 2 * n return obj with self.converted(test_fn, control_flow, {}) as result: res_obj = result.test_fn(constant_op.constant(1), TestClass(0, 0)) self.assertEqual(self.evaluate((res_obj.a, res_obj.b)), (-1, 0)) res_obj = result.test_fn(constant_op.constant(-1), TestClass(0, 0)) self.assertEqual(self.evaluate((res_obj.a, res_obj.b)), (0, -2)) @test_util.run_deprecated_v1 def test_if_single_output(self): def test_fn(n): if n > 0: n = -n return n self.assertTransformedResult(test_fn, constant_op.constant(1), -1) @test_util.run_deprecated_v1 def test_if_semi(self): def test_fn(n): if n > 0: n = 3 return n self.assertTransformedResult(test_fn, constant_op.constant(2), 3) self.assertTransformedResult(test_fn, constant_op.constant(-3), -3) @test_util.run_deprecated_v1 def test_if_local_var(self): def test_fn(n): if n > 0: b = 4 n = b + 1 return n self.assertTransformedResult(test_fn, constant_op.constant(1), 5) self.assertTransformedResult(test_fn, constant_op.constant(-1), -1) @test_util.run_deprecated_v1 def test_if_no_outputs(self): def test_fn(n): if n > 0: b = 4 # pylint:disable=unused-variable return n # Without side effect guards, the if statement will stage a cond, # but that will be pruned at execution. self.assertTransformedResult(test_fn, constant_op.constant(1), 1) self.assertTransformedResult(test_fn, constant_op.constant(-1), -1) @test_util.run_deprecated_v1 def test_if_unbalanced_multiple_composites(self): class Foo(object): def __init__(self): self.b = 2 self.c = 3 def test_fn(x, condition): z = 5 if condition: x.b = 7 x.c = 11 z = 13 return x.b, x.c, z self.assertTransformedResult(test_fn, (Foo(), constant_op.constant(True)), (7, 11, 13)) self.assertTransformedResult(test_fn, (Foo(), constant_op.constant(False)), (2, 3, 5)) @test_util.run_deprecated_v1 def test_if_unbalanced_composite(self): class Foo(object): def __init__(self): self.b = 2 def test_fn(x, condition): z = 5 if condition: x.b = 7 z = 13 return x.b, z self.assertTransformedResult(test_fn, (Foo(), constant_op.constant(True)), (7, 13)) self.assertTransformedResult(test_fn, (Foo(), constant_op.constant(False)), (2, 5)) @test_util.run_deprecated_v1 def test_simple_for(self): def test_fn(l): s1 = 0 s2 = 0 for e in l: s1 += e s2 += e * e return s1, s2 self.assertTransformedResult(test_fn, constant_op.constant([1, 3]), (4, 10)) empty_vector = constant_op.constant([], shape=(0,), dtype=dtypes.int32) self.assertTransformedResult(test_fn, empty_vector, (0, 0)) @test_util.run_deprecated_v1 def test_for_single_output(self): def test_fn(l): s = 0 for e in l: s += e return s self.assertTransformedResult(test_fn, constant_op.constant([1, 3]), 4) empty_vector = constant_op.constant([], shape=(0,), dtype=dtypes.int32) self.assertTransformedResult(test_fn, empty_vector, 0) def test_for_iterated_expression(self): eval_count = [0] def count_evals(x): eval_count[0] += 1 return x def test_fn(n): s = 0 for e in count_evals(range(n)): s += e return s ns = {'count_evals': count_evals} node, ctx = self.prepare(test_fn, ns) node = control_flow.transform(node, ctx) with self.compiled(node, ns) as result: self.assertEqual(result.test_fn(5), 10) self.assertEqual(eval_count[0], 1) def test_for_composite_state_initialized_in_loop(self): class TestClass(object): pass def test_fn(n, x): tc = TestClass() for i in n: if i == 0: tc.x = x else: tc.x = tc.x + i return tc.x self.assertTransformedResult( test_fn, (range(5), constant_op.constant(10)), 20, symbols={'TestClass': TestClass}) with self.converted( test_fn, control_flow, {'TestClass': TestClass}) as result: # TODO(b/128519776): Better error message. with self.assertRaisesRegex( AttributeError, '\'TestClass\' object has no attribute \'x\''): result.test_fn( constant_op.constant(list(range(5))), constant_op.constant(5)) @test_util.run_deprecated_v1 def test_for_tuple_unpacking(self): def test_fn(x_list): z = tf.constant(0) # pylint:disable=undefined-variable for i, x in enumerate(x_list): z = z + x + i return z self.assertTransformedResult(test_fn, [3, 3], 7) def test_for_with_comprehension_in_body(self): def test_fn(l, n): s = constant_op.constant(list(range(n))) for _ in l: s += constant_op.constant([a for a in range(n)]) return s self.assertTransformedResult( test_fn, (constant_op.constant([1, 2, 3]), 5), np.array(range(5)) * 4, symbols={'constant_op': constant_op}) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/control_flow_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for directives module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.converters import directives as directives_converter from tensorflow.python.autograph.core import converter_testing from tensorflow.python.autograph.core.converter import AgAnno from tensorflow.python.autograph.lang import directives from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import parser from tensorflow.python.platform import test class DirectivesTest(converter_testing.TestCase): def test_local_target(self): def test_fn(): l = [] string_var = 0 directives.set_element_type(l, 'a', string_var) node, ctx = self.prepare(test_fn, {'directives': directives}) node = directives_converter.transform(node, ctx) def_, = anno.getanno(node.body[0].targets[0], anno.Static.DEFINITIONS) d = def_.directives[directives.set_element_type] self.assertEqual(d['dtype'].s, 'a') self.assertEqual(d['shape'].id, 'string_var') def test_argument_target(self): def test_fn(a): directives.set_element_type(a, 1, shape=2) node, ctx = self.prepare(test_fn, {'directives': directives}) node = directives_converter.transform(node, ctx) def_, = anno.getanno(node.args.args[0], anno.Static.DEFINITIONS) d = def_.directives[directives.set_element_type] self.assertEqual(d['dtype'].n, 1) self.assertEqual(d['shape'].n, 2) def test_loop_target(self): def test_fn(): a = True while True: directives.set_loop_options(parallel_iterations=10, back_prop=a) node, ctx = self.prepare(test_fn, {'directives': directives}) node = directives_converter.transform(node, ctx) d = anno.getanno(node.body[1], AgAnno.DIRECTIVES) d = d[directives.set_loop_options] self.assertEqual(d['parallel_iterations'].n, 10) self.assertEqual(d['back_prop'].id, 'a') self.assertNotIn('swap_memory', d) def test_loop_target_with_no_loop(self): def test_fn(): directives.set_loop_options() node, ctx = self.prepare(test_fn, {'directives': directives}) with self.assertRaisesRegexp(ValueError, 'must be used inside a statement'): node = directives_converter.transform(node, ctx) def test_invalid_default(self): def invalid_directive(valid_arg, invalid_default=object()): del valid_arg del invalid_default return def call_invalid_directive(): invalid_directive(1) node, _ = parser.parse_entity(call_invalid_directive, ()) # Find the call to the invalid directive node = node.body[0].value with self.assertRaisesRegexp(ValueError, 'Unexpected keyword.*'): directives_converter._map_args(node, invalid_directive) def test_value_verification_does_not_trigger_properties(self): class TestClass(object): @property def b(self): raise ValueError('This should never be evaluated') tc = TestClass() def test_fn(): return tc.b + 1 node, ctx = self.prepare(test_fn, {'tc': tc}) node = directives_converter.transform(node, ctx) self.assertIsNotNone(node) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/directives_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for side_effect_guards module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.converters import side_effect_guards from tensorflow.python.autograph.core import converter_testing from tensorflow.python.framework import constant_op from tensorflow.python.framework import errors_impl from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import variable_scope from tensorflow.python.platform import test tf = None # Will be replaced by a mock. class SideEffectGuardsTest(converter_testing.TestCase): @test_util.run_deprecated_v1 def test_side_effect_on_return_only_variable(self): def test_fn(a): tf.assign(a, a + 1) return a node, ctx = self.prepare(test_fn, {}) node = side_effect_guards.transform(node, ctx) self.assertEqual(len(node.body), 1) with self.compiled(node, {}, state_ops.assign) as result: with self.cached_session() as sess: v = variable_scope.get_variable('test', initializer=2) self.evaluate(v.initializer) self.evaluate(result.test_fn(v)) # TODO(mdan): Add support for this use case. # Right now the variable `a` is not conditioned on the `assign` because # there's no way to add control dependencies to a variable object. self.assertEqual(2, self.evaluate(v)) def test_side_effect_on_used_variable(self): def test_fn(a): tf.assign(a, a + 1) return a + 1 node, ctx = self.prepare(test_fn, {}) node = side_effect_guards.transform(node, ctx) self.assertEqual(len(node.body), 1) with self.compiled(node, {}, state_ops.assign) as result: with self.cached_session() as sess: v = variable_scope.get_variable('test', initializer=2) self.evaluate(v.initializer) self.evaluate(result.test_fn(v)) # TODO(mdan): Ensure the result of test_fn(v) is also deterministic. # Right now it's 3 or 4 based on whether the read is synchronized. self.assertEqual(3, self.evaluate(v)) @test_util.run_deprecated_v1 def test_side_effect_on_tensor(self): def test_fn(a): tf.Assert(a > 0, ['expected in throw']) return a node, ctx = self.prepare(test_fn, {}) node = side_effect_guards.transform(node, ctx) self.assertEqual(len(node.body), 1) with self.compiled(node, {}, control_flow_ops.Assert) as result: with self.cached_session() as sess: with self.assertRaisesRegexp(errors_impl.InvalidArgumentError, 'expected in throw'): sess.run(result.test_fn(constant_op.constant(-1))) def test_multiline_block(self): def test_fn(a): tf.assign_add(a, 1) b = a + 1 tf.assign_add(a, 1) b += 1 return b node, ctx = self.prepare(test_fn, {}) node = side_effect_guards.transform(node, ctx) self.assertEqual(len(node.body), 1) with self.compiled(node, {}, state_ops.assign_add) as result: with self.cached_session() as sess: v = variable_scope.get_variable('test', initializer=2) self.evaluate(v.initializer) self.evaluate(result.test_fn(v)) # TODO(mdan): Ensure the result of test_fn(v) is also deterministic. self.assertEqual(4, self.evaluate(v)) def test_multiline_nested_block(self): def test_fn(a): with tf.name_scope('foo'): tf.assign(a, a + 1) b = a + 1 return b node, ctx = self.prepare(test_fn, {}) node = side_effect_guards.transform(node, ctx) self.assertEqual(len(node.body[0].body), 1) with self.compiled(node, {}, state_ops.assign, ops.name_scope) as result: with self.cached_session() as sess: v = variable_scope.get_variable('test', initializer=2) self.evaluate(v.initializer) self.evaluate(result.test_fn(v)) # TODO(mdan): Ensure the result of test_fn(v) is also deterministic. self.assertEqual(3, self.evaluate(v)) def test_multiline_block_unsafe(self): def test_fn(a): tf.assign(a, a + 1) b = a + 1 tf.assign_add(a, 1) c = b + 1 return c node, ctx = self.prepare(test_fn, {}) node = side_effect_guards.transform(node, ctx) self.assertEqual(len(node.body), 1) with self.compiled(node, {}, state_ops.assign, state_ops.assign_add) as result: with self.cached_session() as sess: v = variable_scope.get_variable('test', initializer=2) self.evaluate(v.initializer) self.evaluate(result.test_fn(v)) # TODO(mdan): Ensure the result of test_fn(v) is also deterministic. self.assertEqual(4, self.evaluate(v)) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/side_effect_guards_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for break_statements module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.converters import break_statements from tensorflow.python.autograph.core import converter_testing from tensorflow.python.framework import constant_op from tensorflow.python.platform import test class BreakCanonicalizationTest(converter_testing.TestCase): def assertTransformedEquivalent(self, test_fn, *inputs): with self.converted(test_fn, break_statements, {}, constant_op.constant) as result: self.assertEqual(test_fn(*inputs), result.test_fn(*inputs)) def test_while_loop(self): def test_fn(x): v = [] while x > 0: x -= 1 if x % 2 == 0: break v.append(x) return v self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 1) self.assertTransformedEquivalent(test_fn, 4) def test_for_loop(self): def test_fn(a): v = [] for x in a: x -= 1 if x % 2 == 0: break v.append(x) return v with self.converted(test_fn, break_statements, {}, constant_op.constant) as result: # The break is incompletely canonicalized. The loop will not interrupt, # but the section following the break will be skipped. self.assertEqual([3], result.test_fn([5, 4])) def test_nested(self): def test_fn(x): v = [] u = [] w = [] while x > 0: x -= 1 if x % 2 == 0: if x % 3 != 0: u.append(x) else: w.append(x) break v.append(x) return v, u, w self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 3) self.assertTransformedEquivalent(test_fn, 11) def test_nested_loops(self): def test_fn(x): v = [] u = [] while x > 0: x -= 1 y = x while y > 0: y -= 1 if y % 2 == 0: break u.append(y) if x == 0: break v.append(x) return v, u self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 2) self.assertTransformedEquivalent(test_fn, 3) self.assertTransformedEquivalent(test_fn, 5) def test_loop_orelse(self): def test_fn(x): v = [] u = [] while x > 0: x -= 1 y = x while y > 1: break else: u.append(y) break v.append(x) return v, u self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 2) self.assertTransformedEquivalent(test_fn, 3) def test_multiple_correlated_breaks_with_side_effects(self): def test_fn(cond1): lst = [] while True: if cond1: lst.append(1) else: break if lst[-1] > 0: # lst always has an element here break return lst self.assertTransformedEquivalent(test_fn, True) self.assertTransformedEquivalent(test_fn, False) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/break_statements_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slices module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.converters import slices from tensorflow.python.autograph.core import converter_testing from tensorflow.python.autograph.lang import directives from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import parser from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.ops import list_ops from tensorflow.python.platform import test class SliceTest(converter_testing.TestCase): def test_index_access(self): def test_fn(l): return l[1] node, ctx = self.prepare(test_fn, {}) def_, = anno.getanno(node.args.args[0], anno.Static.DEFINITIONS) def_.directives[directives.set_element_type] = { 'dtype': parser.parse_expression('tf.int32') } node = slices.transform(node, ctx) with self.compiled(node, {}, dtypes.int32) as result: with self.cached_session() as sess: tl = list_ops.tensor_list_from_tensor( [1, 2], element_shape=constant_op.constant([], dtype=dtypes.int32)) y = result.test_fn(tl) self.assertEqual(2, self.evaluate(y)) def test_index_access_multiple_definitions(self): def test_fn(l): if l: l = [] return l[1] node, ctx = self.prepare(test_fn, {}) def_, = anno.getanno(node.args.args[0], anno.Static.DEFINITIONS) def_.directives[directives.set_element_type] = { 'dtype': parser.parse_expression('tf.int32') } def_, = anno.getanno(node.body[0].body[0].targets[0], anno.Static.DEFINITIONS) def_.directives[directives.set_element_type] = { 'dtype': parser.parse_expression('tf.float32') } with self.assertRaises(ValueError): slices.transform(node, ctx) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/slices_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for call_trees module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.converters import call_trees from tensorflow.python.autograph.core import converter_testing from tensorflow.python.platform import test class CallTreesTest(converter_testing.TestCase): def test_normal_function(self): def test_fn(f): return f() + 3 with self.converted(test_fn, call_trees, {}) as result: self.assertEqual( result.test_fn(None), converter_testing.RESULT_OF_MOCK_CONVERTED_CALL + 3) self.assertListEqual(self.dynamic_calls, [((), None)]) def test_function_with_expression_in_argument(self): def test_fn(f, g): return f(g() + 7) + 3 with self.converted(test_fn, call_trees, {}) as result: self.assertEqual( result.test_fn(None, None), converter_testing.RESULT_OF_MOCK_CONVERTED_CALL + 3) self.assertListEqual(self.dynamic_calls, [ ((), None), ((converter_testing.RESULT_OF_MOCK_CONVERTED_CALL + 7,), None), ]) def test_function_with_call_in_argument(self): def test_fn(f, g): return f(g()) + 3 with self.converted(test_fn, call_trees, {}) as result: self.assertEqual( result.test_fn(None, None), converter_testing.RESULT_OF_MOCK_CONVERTED_CALL + 3) self.assertListEqual(self.dynamic_calls, [ ((), None), ((converter_testing.RESULT_OF_MOCK_CONVERTED_CALL,), None), ]) def test_function_with_kwarg(self): def test_fn(f, a, b): return f(a, c=b) + 3 with self.converted(test_fn, call_trees, {}) as result: self.assertEqual( result.test_fn(None, 1, 2), converter_testing.RESULT_OF_MOCK_CONVERTED_CALL + 3) self.assertListEqual(self.dynamic_calls, [((1,), {'c': 2})]) def test_function_with_kwargs_starargs(self): def test_fn(f, a, *args, **kwargs): return f(a, *args, **kwargs) + 5 with self.converted(test_fn, call_trees, {}) as result: self.assertEqual( result.test_fn(None, 1, *[2, 3], **{ 'b': 4, 'c': 5 }), converter_testing.RESULT_OF_MOCK_CONVERTED_CALL + 5) self.assertListEqual(self.dynamic_calls, [((1, 2, 3), {'b': 4, 'c': 5})]) def test_function_with_kwargs_starargs_only(self): def f(*unused_args): # Will not be called. pass def test_fn(): args = [1, 2, 3] return f(*args) + 11 with self.converted(test_fn, call_trees, {'f': f}) as result: self.assertEqual(result.test_fn(), converter_testing.RESULT_OF_MOCK_CONVERTED_CALL + 11) self.assertListEqual(self.dynamic_calls, [((1, 2, 3), None)]) def test_function_with_kwargs_keywords(self): def test_fn(f, a, b, **kwargs): return f(a, b=b, **kwargs) + 5 with self.converted(test_fn, call_trees, {}) as result: self.assertEqual( result.test_fn(None, 1, 2, **{'c': 3}), converter_testing.RESULT_OF_MOCK_CONVERTED_CALL + 5) self.assertListEqual(self.dynamic_calls, [((1,), {'b': 2, 'c': 3})]) def test_class_method(self): class TestClass(object): def test_method(self, a): return self.other_method(a) + 1 tc = TestClass() with self.converted(TestClass.test_method, call_trees, {}) as result: self.assertEqual(converter_testing.RESULT_OF_MOCK_CONVERTED_CALL + 1, result.test_method(tc, 1)) self.assertListEqual(self.dynamic_calls, [((1,), None)]) def test_object_method(self): class TestClass(object): def test_method(self, a): return self.other_method(a) + 1 tc = TestClass() with self.converted(tc.test_method, call_trees, {}) as result: self.assertEqual(converter_testing.RESULT_OF_MOCK_CONVERTED_CALL + 1, result.test_method(tc, 1)) self.assertListEqual(self.dynamic_calls, [((1,), None)]) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/call_trees_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Canonicalizes continue statements by de-sugaring into a control boolean.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import templates from tensorflow.python.autograph.pyct.static_analysis.annos import NodeAnno class _Continue(object): def __init__(self): self.used = False self.control_var_name = None def __repr__(self): return '<_Continue(used: {}, var: {})>'.format(self.used, self.control_var_name) class _Block(object): """Tracks information about lexical blocks as they are visited in the AST. Mainly, this object tracks the creation of block guards that replace `continue` statements (e.g. `if not continue_:`). Attributes: create_guard_current: bool, whether to create a guard for the current statement. create_guard_next: bool, whether to create a guard for the next statement. is_loop_type: bool, whether this block is the body of a loop. """ def __init__(self): self.is_loop_type = False self.create_guard_current = False self.create_guard_next = False class ContinueCanonicalizationTransformer(converter.Base): """Canonicalizes continue statements into additional conditionals.""" def visit_Continue(self, node): self.state[_Continue].used = True for block in reversed(self.state[_Block].stack): # See ContinueCanonicalizationTest.test_multiple_continues for an example # it's necessary to create guards for all enclosing affected blocks, not # just that of the current block. block.create_guard_next = True if block.is_loop_type: # continue only affects the innermost loop break template = """ var_name = True """ return templates.replace( template, var_name=self.state[_Continue].control_var_name) def _postprocess_statement(self, node): if self.state[_Continue].used: block = self.state[_Block] should_wrap_current = block.create_guard_current # After processing propagate whether to guard the next statement block.create_guard_current = block.create_guard_next block.create_guard_next = False if should_wrap_current: template = """ if ag__.not_(var_name): original_node """ cond, = templates.replace( template, var_name=self.state[_Continue].control_var_name, original_node=node) return cond, cond.body return node, None def _visit_loop_body(self, node, nodes): self.state[_Continue].enter() self.state[_Block].enter() self.state[_Block].is_loop_type = True scope = anno.getanno(node, NodeAnno.BODY_SCOPE) continue_var = self.ctx.namer.new_symbol('continue_', scope.referenced) self.state[_Continue].control_var_name = continue_var nodes = self.visit_block(nodes, after_visit=self._postprocess_statement) if self.state[_Continue].used: template = """ var_name = False """ control_var_init = templates.replace(template, var_name=continue_var) nodes = control_var_init + nodes self.state[_Block].exit() self.state[_Continue].exit() return nodes def _visit_non_loop_body(self, nodes): self.state[_Block].enter() nodes = self.visit_block(nodes, after_visit=self._postprocess_statement) self.state[_Block].exit() return nodes def visit_While(self, node): node.test = self.visit(node.test) node.body = self._visit_loop_body(node, node.body) # A continue in the else clause applies to the containing scope. node.orelse = self._visit_non_loop_body(node.orelse) return node def visit_For(self, node): node.target = self.generic_visit(node.target) node.iter = self.generic_visit(node.iter) node.body = self._visit_loop_body(node, node.body) # A continue in the else clause applies to the containing scope. node.orelse = self._visit_non_loop_body(node.orelse) return node def visit_If(self, node): node.body = self._visit_non_loop_body(node.body) node.orelse = self._visit_non_loop_body(node.orelse) return node def visit_With(self, node): node.items = self.visit_block(node.items) node.body = self._visit_non_loop_body(node.body) return node def visit_Try(self, node): node.body = self._visit_non_loop_body(node.body) node.orelse = self._visit_non_loop_body(node.orelse) # In Python 3.8 and later continue is allowed in finally blocks node.finalbody = self._visit_non_loop_body(node.finalbody) node.handlers = self.visit_block(node.handlers) return node def visit_ExceptHandler(self, node): node.body = self._visit_non_loop_body(node.body) return node def transform(node, ctx): transformer = ContinueCanonicalizationTransformer(ctx) node = transformer.visit(node) return node
tensorflow-master
tensorflow/python/autograph/converters/continue_statements.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for conditional_expressions module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.converters import conditional_expressions from tensorflow.python.autograph.core import converter_testing from tensorflow.python.platform import test class ConditionalExpressionsTest(converter_testing.TestCase): def assertTransformedEquivalent(self, test_fn, *inputs): ns = {} with self.converted(test_fn, conditional_expressions, ns) as result: self.assertEqual(test_fn(*inputs), result.test_fn(*inputs)) def test_basic(self): def test_fn(x): return 1 if x else 0 self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 3) def test_nested_orelse(self): def test_fn(x): y = x * x if x > 0 else x if x else 1 return y self.assertTransformedEquivalent(test_fn, -2) self.assertTransformedEquivalent(test_fn, 0) self.assertTransformedEquivalent(test_fn, 2) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/conditional_expressions_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Converter for slice operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.lang import directives from tensorflow.python.autograph.pyct import templates class SliceTransformer(converter.Base): """Converts slicing operations to their TF counterpart. Currently, relying on the default slice operator that Tensor uses is insufficient, because TensorArray and tensor lists use dedicated index read and write functions. """ def _process_single_assignment(self, target, value): if not isinstance(target, gast.Subscript): return None if not isinstance(target.slice, gast.Index): return None template = """ target = ag__.set_item(target, key, item) """ return templates.replace( template, target=target.value, key=target.slice.value, item=value) def visit_Assign(self, node): node = self.generic_visit(node) # TODO(mdan): Support unpackings and multiple assignments. if len(node.targets) != 1: raise NotImplementedError('multiple assignment') replacement = self._process_single_assignment(node.targets[0], node.value) if replacement is not None: return replacement return node def visit_Subscript(self, node): node = self.generic_visit(node) if not isinstance(node.slice, gast.Index): return node if not isinstance(node.ctx, gast.Load): # Index writes are handled at a higher level, one at which the rvalue is # also available. return node dtype = self.get_definition_directive( node.value, directives.set_element_type, 'dtype', default=templates.replace_as_expression('None')) template = """ ag__.get_item( target, key, opts=ag__.GetItemOpts(element_dtype=dtype)) """ return templates.replace_as_expression( template, target=node.value, key=node.slice.value, dtype=dtype) def transform(node, ctx): return SliceTransformer(ctx).visit(node)
tensorflow-master
tensorflow/python/autograph/converters/slices.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Converts the ternary conditional operator.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.pyct import templates class ConditionalExpressionTransformer(converter.Base): """Converts contitional expressions to functional form.""" def visit_IfExp(self, node): return templates.replace_as_expression( '''ag__.if_stmt(test, lambda: true_expr, lambda: false_expr, lambda: (), lambda _: None)''', test=node.test, true_expr=node.body, false_expr=node.orelse) def transform(node, ctx): node = ConditionalExpressionTransformer(ctx).visit(node) return node
tensorflow-master
tensorflow/python/autograph/converters/conditional_expressions.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Converts assert statements to their corresponding TF calls.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.core import converter from tensorflow.python.autograph.pyct import templates class AssertTransformer(converter.Base): """Transforms Assert nodes to Call so they can be handled as functions.""" def visit_Assert(self, node): self.generic_visit(node) # Note: The lone tf.Assert call will be wrapped with control_dependencies # by side_effect_guards. template = """ ag__.assert_stmt(test, lambda: msg) """ if node.msg is None: return templates.replace( template, test=node.test, msg=gast.Str('Assertion error')) elif isinstance(node.msg, gast.Str): return templates.replace(template, test=node.test, msg=node.msg) else: raise NotImplementedError('can only convert string messages for now.') def transform(node, ctx): return AssertTransformer(ctx).visit(node)
tensorflow-master
tensorflow/python/autograph/converters/asserts.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for arg_defaults module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.converters import arg_defaults from tensorflow.python.autograph.core import converter_testing from tensorflow.python.autograph.pyct import compiler from tensorflow.python.platform import test class ArgDefaultsTransformerTest(converter_testing.TestCase): def assertTransformedFirstLineIs(self, node, expected): self.assertEqual(compiler.ast_to_source(node).split('\n')[0], expected) def test_no_args(self): def test_fn(): pass node, ctx = self.prepare(test_fn, {}) node = arg_defaults.transform(node, ctx) self.assertTransformedFirstLineIs(node, 'def test_fn():') def test_no_defaults(self): def test_fn(a, b, *c, **e): return a, b, c, e node, ctx = self.prepare(test_fn, {}) node = arg_defaults.transform(node, ctx) self.assertTransformedFirstLineIs(node, 'def test_fn(a, b, *c, **e):') # TODO(mdan): Add kwonly-arg tests when PY2 is no longer supported. def test_arg_defaults(self): def test_fn(a, b=1, c=2): return a, b, c node, ctx = self.prepare(test_fn, {}) node = arg_defaults.transform(node, ctx) self.assertTransformedFirstLineIs(node, 'def test_fn(a, b=None, c=None):') def test_arg_defaults_with_vararg(self): def test_fn(a, b=1, *c): # pylint: disable=keyword-arg-before-vararg return a, b, c node, ctx = self.prepare(test_fn, {}) node = arg_defaults.transform(node, ctx) self.assertTransformedFirstLineIs(node, 'def test_fn(a, b=None, *c):') def test_arg_defaults_ignores_inner_lambda(self): def test_fn(): return (lambda x=7: x)() node, ctx = self.prepare(test_fn, {}) node = arg_defaults.transform(node, ctx) with self.converted(test_fn, arg_defaults, {}) as result: self.assertEqual(test_fn(), result.test_fn()) def test_arg_defaults_ignores_inner_function(self): def test_fn(): def inner_fn(a=3): return a return inner_fn() node, ctx = self.prepare(test_fn, {}) node = arg_defaults.transform(node, ctx) with self.converted(test_fn, arg_defaults, {}) as result: self.assertEqual(test_fn(), result.test_fn()) def test_arg_defaults_ignores_inner_function_returned(self): def test_fn(): def inner_fn(a=3): return a return inner_fn node, ctx = self.prepare(test_fn, {}) node = arg_defaults.transform(node, ctx) with self.converted(test_fn, arg_defaults, {}) as result: self.assertEqual(test_fn()(), result.test_fn()()) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/converters/arg_defaults_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for misc module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.utils import misc from tensorflow.python.framework import test_util from tensorflow.python.framework.constant_op import constant from tensorflow.python.ops.variables import Variable from tensorflow.python.platform import test class MiscTest(test.TestCase): def test_capitalize_initial(self): self.assertEqual('', misc.capitalize_initial('')) self.assertEqual('A', misc.capitalize_initial('A')) self.assertEqual('Ab', misc.capitalize_initial('Ab')) self.assertEqual('AbC', misc.capitalize_initial('AbC')) self.assertEqual('A', misc.capitalize_initial('a')) self.assertEqual('Ab', misc.capitalize_initial('ab')) self.assertEqual('AbC', misc.capitalize_initial('abC')) @test_util.run_deprecated_v1 def test_alias_single_tensor(self): a = constant(1) new_a = misc.alias_tensors(a) self.assertFalse(new_a is a) with self.cached_session() as sess: self.assertEqual(1, self.evaluate(new_a)) @test_util.run_deprecated_v1 def test_alias_tensors(self): a = constant(1) v = Variable(2) s = 'a' l = [1, 2, 3] new_a, new_v, new_s, new_l = misc.alias_tensors(a, v, s, l) self.assertFalse(new_a is a) self.assertTrue(new_v is v) self.assertTrue(new_s is s) self.assertTrue(new_l is l) with self.cached_session() as sess: self.assertEqual(1, self.evaluate(new_a)) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/utils/misc_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for context_managers module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.utils import context_managers from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.ops import tensor_array_ops from tensorflow.python.platform import test class ContextManagersTest(test.TestCase): def test_control_dependency_on_returns(self): # Just dry run them. with context_managers.control_dependency_on_returns(None): pass with context_managers.control_dependency_on_returns( constant_op.constant(1)): pass with context_managers.control_dependency_on_returns( tensor_array_ops.TensorArray(dtypes.int32, size=1)): pass with context_managers.control_dependency_on_returns( [constant_op.constant(1), constant_op.constant(2)]): pass if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/utils/context_managers_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Miscellaneous utilities that don't fit anywhere else.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops def alias_tensors(*args): """Wraps any Tensor arguments with an identity op. Any other argument, including Variables, is returned unchanged. Args: *args: Any arguments. Must contain at least one element. Returns: Same as *args, with Tensor instances replaced as described. Raises: ValueError: If args doesn't meet the requirements. """ def alias_if_tensor(a): return array_ops.identity(a) if isinstance(a, ops.Tensor) else a # TODO(mdan): Recurse into containers? # TODO(mdan): Anything we can do about variables? Fake a scope reuse? if len(args) > 1: return (alias_if_tensor(a) for a in args) elif len(args) == 1: return alias_if_tensor(args[0]) raise ValueError('at least one argument required') def capitalize_initial(s): """Capitalizes the initial of a string only.""" if s: return s[0].upper() + s[1:] return s
tensorflow-master
tensorflow/python/autograph/utils/misc.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for wrap_py_func module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.utils import py_func from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.platform import test class PyFuncTest(test.TestCase): def test_wrap_py_func_simple(self): def test_fn(a, b, c): return a + b + c with self.cached_session() as sess: result = py_func.wrap_py_func(test_fn, dtypes.int32, (1, constant_op.constant(1), 1)) self.assertEqual(3, self.evaluate(result)) result = py_func.wrap_py_func(test_fn, dtypes.int32, (1, 1, 1)) self.assertEqual(3, self.evaluate(result)) result = py_func.wrap_py_func( test_fn, dtypes.int32, (constant_op.constant(1), 1, constant_op.constant(1))) self.assertEqual(3, self.evaluate(result)) def test_wrap_py_func_complex_args(self): class TestClass(object): def __init__(self): self.foo = 5 def test_fn(a, b): return a * b.foo with self.cached_session() as sess: result = py_func.wrap_py_func(test_fn, dtypes.int32, (7, TestClass())) self.assertEqual(35, self.evaluate(result)) result = py_func.wrap_py_func(test_fn, dtypes.int32, (constant_op.constant(7), TestClass())) self.assertEqual(35, self.evaluate(result)) def test_wrap_py_func_kwargs(self): class TestClass(object): def __init__(self, foo): self.foo = foo def test_fn(a, b, c, d): return a * b.foo + c * d.foo with self.cached_session() as sess: result = py_func.wrap_py_func(test_fn, dtypes.int32, (7, TestClass(5)), { 'c': 11, 'd': TestClass(13) }) self.assertEqual(178, self.evaluate(result)) result = py_func.wrap_py_func(test_fn, dtypes.int32, (constant_op.constant(7), TestClass(5)), { 'c': constant_op.constant(11), 'd': TestClass(13) }) self.assertEqual(178, self.evaluate(result)) def test_wrap_py_func_dummy_return(self): side_counter = [0] def test_fn(_): side_counter[0] += 1 with self.cached_session() as sess: result = py_func.wrap_py_func(test_fn, None, (5,), use_dummy_return=True) self.assertEqual(1, self.evaluate(result)) self.assertEqual([1], side_counter) result = py_func.wrap_py_func( test_fn, None, (constant_op.constant(5),), use_dummy_return=True) self.assertEqual(1, self.evaluate(result)) self.assertEqual([2], side_counter) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/utils/py_func_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """A typed list in Python.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import ops from tensorflow.python.ops import list_ops from tensorflow.python.ops import tensor_array_ops def dynamic_list_append(target, element): """Converts a list append call inline.""" if isinstance(target, tensor_array_ops.TensorArray): return target.write(target.size(), element) # TODO(mdan): What's the right way to check this? # TODO(mdan): We may not need this branch. # It may be possible to use TensorList alone if the loop body will not # require wrapping it, although we'd have to think about an autoboxing # mechanism for lists received as parameter. if isinstance(target, ops.Tensor): return list_ops.tensor_list_push_back(target, element) # Python targets (including TensorList): fallback to their original append. target.append(element) return target class TensorList(object): """Tensor list wrapper API-compatible with Python built-in list.""" def __init__(self, shape, dtype): self.dtype = dtype self.shape = shape self.clear() def append(self, value): self.list_ = list_ops.tensor_list_push_back(self.list_, value) def pop(self): self.list_, value = list_ops.tensor_list_pop_back(self.list_, self.dtype) return value def clear(self): self.list_ = list_ops.empty_tensor_list(self.shape, self.dtype) def count(self): return list_ops.tensor_list_length(self.list_) def __getitem__(self, key): return list_ops.tensor_list_get_item(self.list_, key, self.dtype) def __setitem__(self, key, value): self.list_ = list_ops.tensor_list_set_item(self.list_, key, value)
tensorflow-master
tensorflow/python/autograph/utils/tensor_list.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for Autograph lists.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.utils import tensor_list as tl from tensorflow.python.eager import context from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.framework.constant_op import constant from tensorflow.python.ops import list_ops from tensorflow.python.ops import tensor_array_ops from tensorflow.python.platform import test class TensorListTest(test.TestCase): def _shape(self, shape_tuple): return constant(shape_tuple, dtypes.int32) @test_util.run_v1_only("b/117943489") def test_dynamic_list_append(self): l = [] l = tl.dynamic_list_append(l, 1) self.assertListEqual(l, [1]) l = list_ops.empty_tensor_list(self._shape(()), dtypes.int32) l = tl.dynamic_list_append(l, 1) s = list_ops.tensor_list_stack(l, element_dtype=dtypes.int32) self.assertAllEqual(s, [1]) l = tensor_array_ops.TensorArray(dtypes.int32, size=0, dynamic_size=True) l = tl.dynamic_list_append(l, 1) s = l.stack() self.assertAllEqual(s, [1]) l = tl.TensorList(self._shape(()), dtypes.int32) l = tl.dynamic_list_append(l, 1) self.assertAllEqual(l[0], 1) def test_list_append_python(self): with context.eager_mode(): a = constant(3.0) l = tl.TensorList(a.shape, a.dtype) l.append(a) self.assertEqual(l.count().numpy(), 1) l.append(a) self.assertEqual(l.count().numpy(), 2) _ = l.pop() self.assertEqual(l.count().numpy(), 1) a2 = l.pop() self.assertEqual(l.count().numpy(), 0) self.assertEqual(a.numpy(), a2.numpy()) def test_list_index_python(self): with context.eager_mode(): a = constant(3.0) b = constant(2.0) l = tl.TensorList(a.shape, a.dtype) l.append(a) self.assertEqual(l[0].numpy(), a.numpy()) l[0] = ops.convert_to_tensor(b) self.assertEqual(l[0].numpy(), b.numpy()) @test_util.run_deprecated_v1 def test_list_append_tf(self): a = constant(3.0) l = tl.TensorList(a.shape, a.dtype) l.append(a) c1 = l.count() l.append(a) c2 = l.count() _ = l.pop() c3 = l.count() a2 = l.pop() c4 = l.count() c1, c2, c3, c4, a, a2 = self.evaluate([c1, c2, c3, c4, a, a2]) self.assertEqual(c1, 1) self.assertEqual(c2, 2) self.assertEqual(c3, 1) self.assertEqual(c4, 0) self.assertEqual(a, a2) def test_list_index_tf(self): a = constant(3.0) b = constant(2.0) l = tl.TensorList(a.shape, a.dtype) l.append(a) l0 = l[0] l[0] = b l1 = l[0] l0, l1, a, b = self.evaluate([l0, l1, a, b]) self.assertEqual(l0, a) self.assertEqual(l1, b) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/utils/tensor_list_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """This module defines tensor utilities not found in TensorFlow. The reason these utilities are not defined in TensorFlow is because they may not be not fully robust, although they work in the vast majority of cases. So we define them here in order for their behavior to be consistently verified. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import dtypes from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_util from tensorflow.python.ops import tensor_array_ops def is_dense_tensor(t): # TODO(mdan): Resolve this inconsistency. return (tensor_util.is_tensor(t) and not isinstance(t, sparse_tensor.SparseTensor)) def is_tensor_array(t): return isinstance(t, tensor_array_ops.TensorArray) def is_tensor_list(t): # TODO(mdan): This is just a heuristic. # With TF lacking support for templated types, this is unfortunately the # closest we can get right now. A dedicated op ought to be possible to # construct. return (tensor_util.is_tensor(t) and t.dtype == dtypes.variant and not t.shape.ndims)
tensorflow-master
tensorflow/python/autograph/utils/tensors.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Pyfunc creation utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import namedtuple from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_util from tensorflow.python.ops import script_ops class MatchDType(namedtuple('MatchDType', ('arg_number',))): """Allows matching the dtype of an argument. Used in conjunction with function calls. For example, MatchDType(0) will match the DType of the first argument. """ pass def wrap_py_func(f, return_dtypes, args, kwargs=None, use_dummy_return=False): """Helper that wraps a callable to py_func. The helper passes tensor arguments through the py_func interface. Non-tensor arguments are allowed, and will be passed to f directly. Note that non-tensor arguments are captured by f will not update every time the wrapper is called (this is consistent with its argument list, which only includes the tensor arguments). In general, it's safest not to reuse this wrapper. Args: f: Callable return_dtypes: None, individual of tuple/list of DType or MatchDType, the data type for each of f's return value(s). Set to None if f has no return values or use_dummy_return is True. Use MatchDType to define a dtype identical to that of `i`th argument (argument 0 is the first); an argument must of Tensor type if it is to be used with MatchDType. args: Positional arguments for f, as list or tuple. kwargs: Keyword arguments for f, as dict with string keys. May be None. use_dummy_return: If True, the function will return a dummy value of 1 and discard its actual return value. Returns: The return values of f converted to tensor. Raises: ValueError: if any of the arguments are incorrect. """ if return_dtypes and use_dummy_return: raise ValueError('if use_dummy_return is True, return_dtypes must be empty') tensor_args = [] tensor_args_idx = {} # Of the positional arguments, only grab the tensor ones to be passed through # the py_func. n_args = len(args) arg_is_tensor = tuple(map(tensor_util.is_tensor, args)) for i in range(n_args): if arg_is_tensor[i]: tensor_args_idx[i] = len(tensor_args) tensor_args.append(args[i]) # We essentially take the tensor kwargs, if any, and add them to the list of # positional arguments. The kwargs are then reconstructed inside the py_func. # # For example, if # # args = [Tensor(1), 'foo'] # kwargs = {'a': Tensor(2), 'b': 'bar'} # # Then # # tensor_args = (Tensor(1), Tensor(2)) # kwarg_keys = ('a', 'b') if kwargs: kwarg_keys = tuple(kwargs.keys()) kwarg_is_tensor = {k: tensor_util.is_tensor(kwargs[k]) for k in kwarg_keys} for k in kwarg_keys: if kwarg_is_tensor[k]: tensor_args_idx[k] = len(tensor_args) tensor_args.append(kwargs[k]) else: kwarg_keys = () # Set up return dtypes. def match_arg_dtype(arg_number): arg = args[arg_number] if not arg_is_tensor[arg_number]: raise ValueError( 'argument %d was used with MatchDType and must be a tf.Tensor, but ' 'was %s instead' % (arg_number, type(arg))) return arg.dtype if return_dtypes: if isinstance(return_dtypes, MatchDType): return_dtypes = match_arg_dtype(return_dtypes.arg_number) elif isinstance(return_dtypes, (list, tuple)): return_dtypes = tuple( match_arg_dtype(a.arg_number) if isinstance(a, MatchDType) else a for a in return_dtypes) else: assert isinstance(return_dtypes, dtypes.DType) def f_wrapper(*tensor_args): f_args = tuple(tensor_args[tensor_args_idx[i]] if arg_is_tensor[i] else a for i, a in enumerate(args)) f_kwargs = { k: tensor_args[tensor_args_idx[k]] if kwarg_is_tensor[k] else kwargs[k] for i, k in enumerate(kwarg_keys) } retval = f(*f_args, **f_kwargs) return 1 if use_dummy_return else retval if use_dummy_return: return_dtypes = dtypes.int32 return script_ops.eager_py_func(f_wrapper, tensor_args, return_dtypes)
tensorflow-master
tensorflow/python/autograph/utils/py_func.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utility module that contains APIs usable in the generated code.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.utils.context_managers import control_dependency_on_returns from tensorflow.python.autograph.utils.misc import alias_tensors from tensorflow.python.autograph.utils.py_func import wrap_py_func from tensorflow.python.autograph.utils.tensor_list import dynamic_list_append from tensorflow.python.autograph.utils.testing import fake_tf from tensorflow.python.autograph.utils.type_check import is_tensor
tensorflow-master
tensorflow/python/autograph/utils/__init__.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensors module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.utils import tensors from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.ops import list_ops from tensorflow.python.ops import tensor_array_ops from tensorflow.python.platform import test class TensorsTest(test.TestCase): def _simple_tensor_array(self): return tensor_array_ops.TensorArray(dtypes.int32, size=3) def _simple_tensor_list(self): return list_ops.empty_tensor_list( element_shape=constant_op.constant([1]), element_dtype=dtypes.int32) def _simple_list_of_tensors(self): return [constant_op.constant(1), constant_op.constant(2)] def test_is_tensor_array(self): self.assertTrue(tensors.is_tensor_array(self._simple_tensor_array())) self.assertFalse(tensors.is_tensor_array(self._simple_tensor_list())) self.assertFalse(tensors.is_tensor_array(constant_op.constant(1))) self.assertFalse(tensors.is_tensor_array(self._simple_list_of_tensors())) self.assertFalse(tensors.is_tensor_array(None)) def test_is_tensor_list(self): self.assertFalse(tensors.is_tensor_list(self._simple_tensor_array())) self.assertTrue(tensors.is_tensor_list(self._simple_tensor_list())) self.assertFalse(tensors.is_tensor_list(constant_op.constant(1))) self.assertFalse(tensors.is_tensor_list(self._simple_list_of_tensors())) self.assertFalse(tensors.is_tensor_list(None)) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/utils/tensors_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Various context managers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import contextlib from tensorflow.python.framework import ops from tensorflow.python.ops import tensor_array_ops def control_dependency_on_returns(return_value): """Create a TF control dependency on the return values of a function. If the function had no return value, a no-op context is returned. Args: return_value: The return value to set as control dependency. Returns: A context manager. """ def control_dependency_handle(t): if isinstance(t, tensor_array_ops.TensorArray): return t.flow return t if return_value is None: return contextlib.contextmanager(lambda: (yield))() # TODO(mdan): Filter to tensor objects. if not isinstance(return_value, (list, tuple)): return_value = (return_value,) return_value = tuple(control_dependency_handle(t) for t in return_value) return ops.control_dependencies(return_value)
tensorflow-master
tensorflow/python/autograph/utils/context_managers.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities used in autograph-generated code.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import tensor_util def is_tensor(*args): """Check if any arguments are tensors. Args: *args: Python objects that may or may not be tensors. Returns: True if any *args are TensorFlow types, False if none are. """ return any(tensor_util.is_tensor(a) for a in args)
tensorflow-master
tensorflow/python/autograph/utils/type_check.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Testing utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import imp from tensorflow.python.framework import ops from tensorflow.python.ops import gen_math_ops from tensorflow.python.ops import math_ops def fake_tf(): """Creates a fake module that looks like TensorFlow, for testing.""" mod = imp.new_module('tensorflow') mod_contents = {} mod_contents.update(gen_math_ops.__dict__) mod_contents.update(math_ops.__dict__) mod_contents.update(ops.__dict__) mod_contents.update(mod.__dict__) mod.__dict__.update(mod_contents) return mod
tensorflow-master
tensorflow/python/autograph/utils/testing.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Logging and debugging utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import traceback # TODO(mdan): Use a custom logger class. from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util.tf_export import tf_export VERBOSITY_VAR_NAME = 'AUTOGRAPH_VERBOSITY' DEFAULT_VERBOSITY = 0 verbosity_level = None # vlog-like. Takes precedence over the env variable. echo_log_to_stdout = False # In interactive Python, logging echo is enabled by default. if hasattr(sys, 'ps1') or hasattr(sys, 'ps2'): echo_log_to_stdout = True @tf_export('autograph.set_verbosity') def set_verbosity(level, alsologtostdout=False): """Sets the AutoGraph verbosity level. _Debug logging in AutoGraph_ More verbose logging is useful to enable when filing bug reports or doing more in-depth debugging. There are two controls that control the logging verbosity: * The `set_verbosity` function * The `AUTOGRAPH_VERBOSITY` environment variable `set_verbosity` takes precedence over the environment variable. For example: ```python import os import tensorflow as tf os.environ['AUTOGRAPH_VERBOSITY'] = 5 # Verbosity is now 5 tf.autograph.set_verbosity(0) # Verbosity is now 0 os.environ['AUTOGRAPH_VERBOSITY'] = 1 # No effect, because set_verbosity was already called. ``` Logs entries are output to [absl](https://abseil.io)'s default output, with `INFO` level. Logs can be mirrored to stdout by using the `alsologtostdout` argument. Mirroring is enabled by default when Python runs in interactive mode. Args: level: int, the verbosity level; larger values specify increased verbosity; 0 means no logging. When reporting bugs, it is recommended to set this value to a larges number, like 10. alsologtostdout: bool, whether to also output log messages to `sys.stdout`. """ global verbosity_level global echo_log_to_stdout verbosity_level = level echo_log_to_stdout = alsologtostdout @tf_export('autograph.trace') def trace(*args): """Traces argument information at compilation time. `trace` is useful when debugging, and it always executes during the tracing phase, that is, when the TF graph is constructed. _Example usage_ ```python import tensorflow as tf for i in tf.range(10): tf.autograph.trace(i) # Output: <Tensor ...> ``` Args: *args: Arguments to print to `sys.stdout`. """ print(*args) def get_verbosity(): global verbosity_level if verbosity_level is not None: return verbosity_level return int(os.getenv(VERBOSITY_VAR_NAME, DEFAULT_VERBOSITY)) def has_verbosity(level): return get_verbosity() >= level def _output_to_stdout(msg, *args, **kwargs): print(msg % args) if kwargs.get('exc_info', False): traceback.print_exc() def error(level, msg, *args, **kwargs): if has_verbosity(level): logging.error(msg, *args, **kwargs) if echo_log_to_stdout: _output_to_stdout('ERROR: ' + msg, *args, **kwargs) def log(level, msg, *args, **kwargs): if has_verbosity(level): logging.info(msg, *args, **kwargs) if echo_log_to_stdout: _output_to_stdout(msg, *args, **kwargs) def warn(msg, *args, **kwargs): logging.warn(msg, *args, **kwargs) if echo_log_to_stdout: _output_to_stdout('WARNING: ' + msg, *args, **kwargs)
tensorflow-master
tensorflow/python/autograph/utils/ag_logging.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for type_check.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy from tensorflow.python.autograph.utils import type_check from tensorflow.python.framework import constant_op from tensorflow.python.framework import test_util from tensorflow.python.platform import test class TypeCheckTest(test.TestCase): @test_util.run_deprecated_v1 def test_checks(self): self.assertTrue(type_check.is_tensor(constant_op.constant([1, 2, 3]))) self.assertTrue( type_check.is_tensor(test_util.variables.Variable([1, 2, 3]))) self.assertTrue( type_check.is_tensor( test_util.array_ops.placeholder(test_util.dtypes.float32))) self.assertFalse(type_check.is_tensor(3)) self.assertFalse(type_check.is_tensor(numpy.eye(3))) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/utils/type_check_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for special_functions module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.autograph.lang import special_functions from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_util from tensorflow.python.ops import list_ops from tensorflow.python.platform import test class SpecialFunctionsTest(test.TestCase): def test_match_staging_level(self): some_tensor = constant_op.constant(0) tensor_one = special_functions.match_staging_level(1, some_tensor) python_one = special_functions.match_staging_level(1, 1) with self.cached_session() as sess: self.assertTrue(tensor_util.is_tensor(tensor_one)) self.assertAllEqual(self.evaluate(tensor_one), 1) self.assertEqual(python_one, 1) def test_tensor_list_empty_list(self): l = special_functions.tensor_list([], element_dtype=dtypes.int32, element_shape=()) sl = list_ops.tensor_list_stack(l, element_dtype=dtypes.int32) with self.cached_session() as sess: self.assertAllEqual(self.evaluate(sl), []) l = special_functions.tensor_list((), element_dtype=dtypes.int32, element_shape=()) sl = list_ops.tensor_list_stack(l, element_dtype=dtypes.int32) with self.cached_session() as sess: self.assertAllEqual(self.evaluate(sl), []) def test_tensor_list_tensor(self): l = special_functions.tensor_list( constant_op.constant([], dtype=dtypes.int32)) sl = list_ops.tensor_list_stack(l, element_dtype=dtypes.int32) with self.cached_session() as sess: self.assertAllEqual(self.evaluate(sl), []) def test_tensor_list_unsupported_initializer(self): with self.assertRaisesRegexp(ValueError, 'unknown type'): special_functions.tensor_list(np.array([1, 2, 3])) def test_tensor_list_empty_list_no_type(self): with self.assertRaisesRegexp( ValueError, 'element_dtype and element_shape are required'): special_functions.tensor_list([]) def test_tensor_list_from_elements(self): elements = [constant_op.constant([1, 2]), constant_op.constant([3, 4])] l = special_functions.tensor_list(elements) sl = list_ops.tensor_list_stack(l, element_dtype=dtypes.int32) with self.cached_session() as sess: self.assertAllEqual(self.evaluate(sl), [[1, 2], [3, 4]]) def test_tensor_list_array_from_elements(self): elements = [constant_op.constant([1, 2]), constant_op.constant([3, 4])] l = special_functions.tensor_list(elements, use_tensor_array=True) sl = l.stack() with self.cached_session() as sess: self.assertAllEqual(self.evaluate(sl), [[1, 2], [3, 4]]) def test_stack(self): self.assertEqual(special_functions.stack(1, strict=False), 1) self.assertListEqual( special_functions.stack([1, 2, 3], strict=False), [1, 2, 3]) # TODO(mdan): This should probably forward to tf.stack. self.assertTrue( isinstance( special_functions.stack( [constant_op.constant(1), constant_op.constant(2)], strict=False), list)) with self.assertRaises(ValueError): special_functions.stack([1, 2, 3]) t = constant_op.constant([1.0, 2.0]) l = list_ops.tensor_list_from_tensor( t, element_shape=constant_op.constant([], dtype=dtypes.int32)) self.assertTrue( tensor_util.is_tensor( special_functions.stack(l, element_dtype=dtypes.float32))) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/lang/special_functions_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Directives are special no-op functions that serve as compilation markers. They provide static information like type hints, compilation and TensorFlow overrides. These serve as annotations in the compiled code, allowing the user some control over the compilation process. They have no functional role at runtime. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.util.tf_export import tf_export UNSPECIFIED = object() def set_element_type(entity, dtype, shape=UNSPECIFIED): """Indicates that the entity is expected hold items of specified type/shape. The staged TensorFlow ops will reflect and assert this data type. Ignored otherwise. Args: entity: The entity to annotate. dtype: TensorFlow dtype value to assert for entity. shape: Optional shape to assert for entity. """ del entity del dtype del shape @tf_export('autograph.experimental.set_loop_options') def set_loop_options( parallel_iterations=UNSPECIFIED, back_prop=UNSPECIFIED, swap_memory=UNSPECIFIED, maximum_iterations=UNSPECIFIED): """Specifies additional arguments to be passed to the enclosing while_loop. The parameters apply to and only to the immediately enclosing loop. It only has effect if the loop is staged as a TF while_loop; otherwise the parameters have no effect. Usage example: @tf.function(autograph=True) def dynamic_rnn(..., parallel_iterations=32): num_steps = ... for t in tf.range(num_steps): tf.autograph.experimental.set_loop_options( parallel_iterations=parallel_iterations) ... Args: parallel_iterations: See tf.while_loop. back_prop: See tf.while_loop. swap_memory: See tf.while_loop. maximum_iterations: See tf.while_loop. """ del parallel_iterations del back_prop del swap_memory del maximum_iterations
tensorflow-master
tensorflow/python/autograph/lang/directives.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Special functions that only make sense for AutoGraph. These functions are meant to ensure feature parity between Python and AutoGraph, so that the exact same code works in both modes. In general, AutoGraph will replace these calls. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.operators import data_structures from tensorflow.python.framework import constant_op from tensorflow.python.framework import tensor_util def _validate_list_constructor(elements, element_dtype, element_shape): """Validates the inputs of tensor_list.""" if element_dtype is not None and element_shape is not None: return if tensor_util.is_tensor(elements): return if isinstance(elements, (list, tuple)): if elements: return else: raise ValueError( 'element_dtype and element_shape are required when elements are' ' empty') raise ValueError( 'unknown type for elements: {}; only Tensor, list and tuple are' ' allowed'.format(type(elements))) def match_staging_level(value, like_value): """Casts a value to be staged at the same level as another.""" if tensor_util.is_tensor(like_value): return constant_op.constant(value) return value def tensor_list(elements, element_dtype=None, element_shape=None, use_tensor_array=False): """Creates an tensor list and populates it with the given elements. This function provides a more uniform access to tensor lists and tensor arrays, and allows optional initialization. Note: this function is a simplified wrapper. If you need greater control, it is recommended to use the underlying implementation directly. Args: elements: Iterable[tf.Tensor, ...], the elements to initially fill the list with element_dtype: Optional[tf.DType], data type for the elements in the list; required if the list is empty element_shape: Optional[tf.TensorShape], shape for the elements in the list; required if the list is empty use_tensor_array: bool, whether to use the more compatible but restrictive tf.TensorArray implementation Returns: Union[tf.Tensor, tf.TensorArray], the new list. Raises: ValueError: for invalid arguments """ _validate_list_constructor(elements, element_dtype, element_shape) if use_tensor_array: return data_structures.tf_tensor_array_new(elements, element_dtype, element_shape) else: return data_structures.tf_tensor_list_new(elements, element_dtype, element_shape) def stack(list_or_tensor, element_dtype=None, strict=True): """Stacks the input, if it admits the notion of stacking. For example, a list of tensors can be stacked into a larger tensor. This function is similar to tf.stack, but it accepts non-lists and lists of non-tensors as arguments. In the latter case, the function does nothing. Args: list_or_tensor: Any element_dtype: tf.DType, optional dtypedtype for the elements in the list. Required if the input is stackable, and the list is untyped. strict: bool, if True an error is raised if the input is not stackable. Otherwise the function is a no-op. Returns: Any, if the input is stackable, the result will be a tf.Tensor. Otherwise, if strict=False, the result will be list_or_tensor. Raises: ValueError: if strict=True and the input is not stackable. """ if strict: def raise_error(x): raise ValueError('%s must be stackable when strict=True' % x) original_call = raise_error else: original_call = lambda x: x return data_structures.list_stack( list_or_tensor, data_structures.ListStackOpts( element_dtype=element_dtype, original_call=original_call))
tensorflow-master
tensorflow/python/autograph/lang/special_functions.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Control flow graph (CFG) structure for Python AST representation. The CFG is a digraph with edges representing valid control flow. Each node is associated with exactly one AST node, but not all AST nodes may have a corresponding CFG counterpart. Once built, the CFG itself is immutable, but the values it holds need not be; they are usually annotated with information extracted by walking the graph. """ # TODO(mdan): The notion of 'statements' below is inaccurate. # They should rather be called 'block statements', because they include # statements that may have a body, e.g. if and while. from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import weakref from enum import Enum # pylint:disable=g-bad-import-order import gast # pylint:enable=g-bad-import-order from tensorflow.python.autograph.pyct import compiler class Node(object): """A node in the CFG. Although new instances of this class are mutable, the objects that a user finds in the CFG are typically not. The nodes represent edges in the CFG graph, and maintain pointers to allow efficient walking in both forward and reverse order. The following property holds for all nodes: "child in node.next" iff "node in child.prev". Attributes: next: FrozenSet[Node, ...], the nodes that follow this node, in control flow order prev: FrozenSet[Node, ...], the nodes that precede this node, in reverse control flow order ast_node: ast.AST, the AST node corresponding to this CFG node """ def __init__(self, next_, prev, ast_node): self.next = next_ self.prev = prev self.ast_node = ast_node def freeze(self): self.next = frozenset(self.next) # Assumption: All CFG nodes have identical life spans, because the graph # owns them. Nodes should never be used outside the context of an existing # graph. self.prev = weakref.WeakSet(self.prev) def __repr__(self): if isinstance(self.ast_node, gast.FunctionDef): return 'def %s' % self.ast_node.name elif isinstance(self.ast_node, gast.withitem): return compiler.ast_to_source(self.ast_node.context_expr).strip() return compiler.ast_to_source(self.ast_node).strip() class Graph( collections.namedtuple( 'Graph', ['entry', 'exit', 'error', 'index', 'stmt_prev', 'stmt_next'])): """A Control Flow Graph. The CFG maintains an index to allow looking up a CFG node by the AST node to which it is associated. The index can also be enumerated in top-down, depth first order. Walking the graph in forward or reverse order is supported by double parent-child links. Note: the error nodes are not wired to their corresponding finally guards, because these are shared, and wiring them would create a reverse path from normal control flow into the error nodes, which we want to avoid. The graph also maintains edges corresponding to higher level statements like for-else loops. A node is considered successor of a statement if there is an edge from a node that is lexically a child of that statement to a node that is not. Statement predecessors are analogously defined. Attributes: entry: Node, the entry node exit: FrozenSet[Node, ...], the exit nodes error: FrozenSet[Node, ...], nodes that exit due to an explicitly raised error (errors propagated from function calls are not accounted) index: Dict[ast.Node, Node], mapping AST nodes to the respective CFG node stmt_prev: Dict[ast.Node, FrozenSet[Node, ...]], mapping statement AST nodes to their predecessor CFG nodes stmt_next: Dict[ast.Node, FrozenSet[Node, ...]], mapping statement AST nodes to their successor CFG nodes """ def __repr__(self): return self.as_dot() def as_dot(self): """Print CFG in DOT format.""" result = 'digraph CFG {\n' for node in self.index.values(): result += ' %s [label="%s"];\n' % (id(node), node) for node in self.index.values(): for next_ in node.next: result += ' %s -> %s;\n' % (id(node), id(next_)) result += '}' return result class _WalkMode(Enum): FORWARD = 1 REVERSE = 2 # TODO(mdan): Rename to DataFlowAnalyzer. # TODO(mdan): Consider specializations that use gen/kill/transfer abstractions. class GraphVisitor(object): """Base class for a CFG visitors. This implementation is not thread safe. The visitor has some facilities to simplify dataflow analyses. In particular, it allows revisiting the nodes at the decision of the subclass. This can be used to visit the graph until the state reaches a fixed point. For more details on dataflow analysis, see https://www.seas.harvard.edu/courses/cs252/2011sp/slides/Lec02-Dataflow.pdf Note: the literature generally suggests visiting successor nodes only when the state of the current node changed, regardless of whether that successor has ever been visited. This implementation visits every successor at least once. Attributes: graph: Graph in_: Dict[Node, Any], stores node-keyed state during a visit out: Dict[Node, Any], stores node-keyed state during a visit """ def __init__(self, graph): self.graph = graph self.reset() def init_state(self, node): """State initialization function. Optional to overload. An in/out state slot will be created for each node in the graph. Subclasses must overload this to control what that is initialized to. Args: node: Node """ raise NotImplementedError('Subclasses must implement this.') # TODO(mdan): Rename to flow? def visit_node(self, node): """Visitor function. Args: node: Node Returns: bool, whether the node should be revisited; subclasses can visit every reachable node exactly once by always returning False """ raise NotImplementedError('Subclasses must implement this.') def reset(self): self.in_ = { node: self.init_state(node) for node in self.graph.index.values() } self.out = { node: self.init_state(node) for node in self.graph.index.values() } def _visit_internal(self, mode): """Visits the CFG, depth-first.""" assert mode in (_WalkMode.FORWARD, _WalkMode.REVERSE) if mode == _WalkMode.FORWARD: open_ = [self.graph.entry] elif mode == _WalkMode.REVERSE: open_ = list(self.graph.exit) closed = set() while open_: node = open_.pop(0) closed.add(node) should_revisit = self.visit_node(node) if mode == _WalkMode.FORWARD: children = node.next elif mode == _WalkMode.REVERSE: children = node.prev for next_ in children: if should_revisit or next_ not in closed: open_.append(next_) def visit_forward(self): self._visit_internal(_WalkMode.FORWARD) def visit_reverse(self): self._visit_internal(_WalkMode.REVERSE) class GraphBuilder(object): """Builder that constructs a CFG from a given AST. This GraphBuilder facilitates constructing the DAG that forms the CFG when nodes are supplied in lexical order (i.e., top-down, depth first). Under these conditions, it supports building patterns found in typical structured programs. This builder ignores the flow generated by exceptions, which are assumed to always be catastrophic and present purely for diagnostic purposes (e.g. to print debug information). Statements like raise and try/catch sections are allowed and will generate control flow edges, but ordinaty statements are assumed not to raise exceptions. Finally sections are also correctly interleaved between break/continue/return nodes and their subsequent statements. Important concepts: * nodes - nodes refer refer to CFG nodes; AST nodes are qualified explicitly * leaf set - since the graph is constructed gradually, a leaf set maintains the CFG nodes that will precede the node that the builder expects to receive next; when an ordinary node is added, it is connected to the existing leaves and it in turn becomes the new leaf * jump nodes - nodes that should generate edges other than what ordinary nodes would; these correspond to break, continue and return statements * sections - logical delimiters for subgraphs that require special edges; there are various types of nodes, each admitting various types of jump nodes; sections are identified by their corresponding AST node """ # TODO(mdan): Perhaps detail this in a markdown doc. # TODO(mdan): Add exception support. def __init__(self, parent_ast_node): self.reset() self.parent = parent_ast_node def reset(self): """Resets the state of this factory.""" self.head = None self.errors = set() self.node_index = {} # TODO(mdan): Too many primitives. Use classes. self.leaves = set() # Note: This mechanism requires that nodes are added in lexical order (top # to bottom, depth first). self.active_stmts = set() self.owners = {} # type: Set[any] self.forward_edges = set() # type: Tuple[Node, Node] # (from, to) self.finally_sections = {} # Dict values represent (entry, exits) self.finally_section_subgraphs = { } # type: Dict[ast.AST, Tuple[Node, Set[Node]]] # Whether the guard section can be reached from the statement that precedes # it. self.finally_section_has_direct_flow = {} # Finally sections that await their first node. self.pending_finally_sections = set() # Exit jumps keyed by the section they affect. self.exits = {} # The entry of loop sections, keyed by the section. self.section_entry = {} # Continue jumps keyed by the section they affect. self.continues = {} # The entry of conditional sections, keyed by the section. self.cond_entry = {} # Lists of leaf nodes corresponding to each branch in the section. self.cond_leaves = {} def _connect_nodes(self, first, second): """Connects nodes to signify that control flows from first to second. Args: first: Union[Set[Node, ...], Node] second: Node """ if isinstance(first, Node): first.next.add(second) second.prev.add(first) self.forward_edges.add((first, second)) else: for node in first: self._connect_nodes(node, second) def _add_new_node(self, ast_node): """Grows the graph by adding a CFG node following the current leaves.""" if ast_node is self.node_index: raise ValueError('%s added twice' % ast_node) # Assumption: All CFG nodes have identical life spans, because the graph # owns them. Nodes should never be used outside the context of an existing # graph. node = Node(next_=set(), prev=weakref.WeakSet(), ast_node=ast_node) self.node_index[ast_node] = node self.owners[node] = frozenset(self.active_stmts) if self.head is None: self.head = node for leaf in self.leaves: self._connect_nodes(leaf, node) # If any finally section awaits its first node, populate it. for section_id in self.pending_finally_sections: self.finally_section_subgraphs[section_id][0] = node self.pending_finally_sections = set() return node def begin_statement(self, stmt): """Marks the beginning of a statement. Args: stmt: Hashable, a key by which the statement can be identified in the CFG's stmt_prev and stmt_next attributes """ self.active_stmts.add(stmt) def end_statement(self, stmt): """Marks the end of a statement. Args: stmt: Hashable, a key by which the statement can be identified in the CFG's stmt_prev and stmt_next attributes; must match a key previously passed to begin_statement. """ self.active_stmts.remove(stmt) def add_ordinary_node(self, ast_node): """Grows the graph by adding an ordinary CFG node. Ordinary nodes are followed by the next node, in lexical order, that is, they become the new leaf set. Args: ast_node: ast.AST Returns: Node """ node = self._add_new_node(ast_node) self.leaves = set((node,)) return node def _add_jump_node(self, ast_node, guards): """Grows the graph by adding a jump node. Jump nodes are added to the current leaf set, and the leaf set becomes empty. If the jump node is the last in a cond section, then it may be added back to the leaf set by a separate mechanism. Args: ast_node: ast.AST guards: Tuple[ast.AST, ...], the finally sections active for this node Returns: Node """ node = self._add_new_node(ast_node) self.leaves = set() # The guards themselves may not yet be complete, and will be wired later. self.finally_sections[node] = guards return node def _connect_jump_to_finally_sections(self, node): """Connects a jump node to the finally sections protecting it.""" cursor = set((node,)) if node not in self.finally_sections: return cursor for guard_section_id in self.finally_sections[node]: guard_begin, guard_ends = self.finally_section_subgraphs[guard_section_id] self._connect_nodes(cursor, guard_begin) cursor = guard_ends del self.finally_sections[node] # TODO(mdan): Should garbage-collect finally_section_subgraphs. return cursor def add_exit_node(self, ast_node, section_id, guards): """Grows the graph by adding an exit node. This node becomes an exit for the current section. Args: ast_node: ast.AST section_id: Hashable, the node for which ast_node should be considered to be an exit node guards: Tuple[ast.AST, ...], the finally sections that guard ast_node """ node = self._add_jump_node(ast_node, guards) self.exits[section_id].add(node) def add_continue_node(self, ast_node, section_id, guards): """Grows the graph by adding a reentry node. This node causes control flow to go back to the loop section's entry. Args: ast_node: ast.AST section_id: Hashable, the node for which ast_node should be considered to be an exit node guards: Tuple[ast.AST, ...], the finally sections that guard ast_node """ node = self._add_jump_node(ast_node, guards) self.continues[section_id].add(node) def add_error_node(self, ast_node, guards): """Grows the graph by adding an error node. This node becomes an exit for the entire graph. Args: ast_node: ast.AST guards: Tuple[ast.AST, ...], the finally sections that guard ast_node """ node = self._add_jump_node(ast_node, guards) self.errors.add(node) self.leaves = set() def enter_section(self, section_id): """Enters a regular section. Regular sections admit exit jumps, which end the section. Args: section_id: Hashable, the same node that will be used in calls to the ast_node arg passed to add_exit_node """ assert section_id not in self.exits self.exits[section_id] = set() def exit_section(self, section_id): """Exits a regular section.""" # Exits are jump nodes, which may be protected. for exit_ in self.exits[section_id]: self.leaves |= self._connect_jump_to_finally_sections(exit_) del self.exits[section_id] def enter_loop_section(self, section_id, entry_node): """Enters a loop section. Loop sections define an entry node. The end of the section always flows back to the entry node. These admit continue jump nodes which also flow to the entry node. Args: section_id: Hashable, the same node that will be used in calls to the ast_node arg passed to add_continue_node entry_node: ast.AST, the entry node into the loop (e.g. the test node for while loops) """ assert section_id not in self.section_entry assert section_id not in self.continues self.continues[section_id] = set() node = self.add_ordinary_node(entry_node) self.section_entry[section_id] = node def exit_loop_section(self, section_id): """Exits a loop section.""" self._connect_nodes(self.leaves, self.section_entry[section_id]) # continues are jump nodes, which may be protected. for reentry in self.continues[section_id]: guard_ends = self._connect_jump_to_finally_sections(reentry) self._connect_nodes(guard_ends, self.section_entry[section_id]) # Loop nodes always loop back. self.leaves = set((self.section_entry[section_id],)) del self.continues[section_id] del self.section_entry[section_id] def enter_cond_section(self, section_id): """Enters a conditional section. Conditional sections define an entry node, and one or more branches. Args: section_id: Hashable, the same node that will be used in calls to the section_id arg passed to new_cond_branch """ assert section_id not in self.cond_entry assert section_id not in self.cond_leaves self.cond_leaves[section_id] = [] def new_cond_branch(self, section_id): """Begins a new branch in a cond section.""" assert section_id in self.cond_leaves if section_id in self.cond_entry: # Subsequent splits move back to the split point, and memorize the # current leaves. self.cond_leaves[section_id].append(self.leaves) self.leaves = self.cond_entry[section_id] else: # If this is the first time we split a section, just remember the split # point. self.cond_entry[section_id] = self.leaves def exit_cond_section(self, section_id): """Exits a conditional section.""" for split in self.cond_leaves[section_id]: self.leaves |= split del self.cond_entry[section_id] del self.cond_leaves[section_id] def enter_finally_section(self, section_id): """Enters a finally section.""" # TODO(mdan): This, not the caller, should track the active sections. self.finally_section_subgraphs[section_id] = [None, None] if self.leaves: self.finally_section_has_direct_flow[section_id] = True else: self.finally_section_has_direct_flow[section_id] = False self.pending_finally_sections.add(section_id) def exit_finally_section(self, section_id): """Exits a finally section.""" assert section_id not in self.pending_finally_sections, 'Empty finally?' self.finally_section_subgraphs[section_id][1] = self.leaves # If the guard can only be reached by a jump, then it will not flow # into the statement that follows it. if not self.finally_section_has_direct_flow[section_id]: self.leaves = set() del self.finally_section_has_direct_flow[section_id] def build(self): """Returns the CFG accumulated so far and resets the builder. Returns: Graph """ # Freeze the nodes. for node in self.node_index.values(): node.freeze() # Build the statement edges. stmt_next = {} stmt_prev = {} for node in self.node_index.values(): for stmt in self.owners[node]: if stmt not in stmt_prev: stmt_prev[stmt] = set() if stmt not in stmt_next: stmt_next[stmt] = set() for first, second in self.forward_edges: stmts_exited = self.owners[first] - self.owners[second] for stmt in stmts_exited: stmt_next[stmt].add(second) stmts_entered = self.owners[second] - self.owners[first] for stmt in stmts_entered: stmt_prev[stmt].add(first) for stmt in stmt_next: stmt_next[stmt] = frozenset(stmt_next[stmt]) for stmt in stmt_prev: stmt_prev[stmt] = frozenset(stmt_prev[stmt]) # Construct the final graph object. result = Graph( entry=self.head, exit=self.leaves, error=self.errors, index=self.node_index, stmt_prev=stmt_prev, stmt_next=stmt_next) # Reset the state. self.reset() return result class AstToCfg(gast.NodeVisitor): """Converts an AST to CFGs. A separate CFG will be constructed for each function. """ def __init__(self): super(AstToCfg, self).__init__() self.builder_stack = [] self.builder = None self.cfgs = {} self.lexical_scopes = [] def _enter_lexical_scope(self, node): self.lexical_scopes.append(node) def _exit_lexical_scope(self, node): leaving_node = self.lexical_scopes.pop() assert node == leaving_node def _get_enclosing_finally_scopes(self, stop_at): included = [] for node in reversed(self.lexical_scopes): if isinstance(node, gast.Try) and node.finalbody: included.append(node) if isinstance(node, stop_at): return node, included return None, included def _process_basic_statement(self, node): self.generic_visit(node) self.builder.add_ordinary_node(node) def _process_exit_statement(self, node, *exits_nodes_of_type): # Note: this is safe because we process functions separately. try_node, guards = self._get_enclosing_finally_scopes( tuple(exits_nodes_of_type)) if try_node is None: raise ValueError( '%s that is not enclosed by any of %s' % (node, exits_nodes_of_type)) self.builder.add_exit_node(node, try_node, guards) def _process_continue_statement(self, node, *loops_to_nodes_of_type): # Note: this is safe because we process functions separately. try_node, guards = self._get_enclosing_finally_scopes( tuple(loops_to_nodes_of_type)) if try_node is None: raise ValueError('%s that is not enclosed by any of %s' % (node, loops_to_nodes_of_type)) self.builder.add_continue_node(node, try_node, guards) def visit_FunctionDef(self, node): # We also keep the FunctionDef node in the CFG. This allows us to determine # things like reaching definitions via closure. Note that the function body # will be stored in a separate graph, because function definitions are not # the same as function calls. if self.builder is not None: self.builder.add_ordinary_node(node) self.builder_stack.append(self.builder) self.builder = GraphBuilder(node) self._enter_lexical_scope(node) self.builder.enter_section(node) self._process_basic_statement(node.args) for stmt in node.body: self.visit(stmt) self.builder.exit_section(node) self._exit_lexical_scope(node) self.cfgs[node] = self.builder.build() self.builder = self.builder_stack.pop() def visit_Return(self, node): self._process_exit_statement(node, gast.FunctionDef) def visit_Expr(self, node): self._process_basic_statement(node) def visit_Assign(self, node): self._process_basic_statement(node) def visit_AnnAssign(self, node): self._process_basic_statement(node) def visit_AugAssign(self, node): self._process_basic_statement(node) def visit_Pass(self, node): self._process_basic_statement(node) def visit_Global(self, node): self._process_basic_statement(node) def visit_Nonlocal(self, node): self._process_basic_statement(node) def visit_Print(self, node): self._process_basic_statement(node) def visit_Raise(self, node): try_node, guards = self._get_enclosing_finally_scopes((gast.FunctionDef,)) if try_node is None: raise ValueError('%s that is not enclosed by any FunctionDef' % node) self.builder.add_error_node(node, guards) def visit_Assert(self, node): # Ignoring the effect of exceptions. self._process_basic_statement(node) def visit_Delete(self, node): self._process_basic_statement(node) def visit_If(self, node): # No need to track ifs as lexical scopes, for now. # Lexical scopes are generally tracked in order to be able to resolve the # targets of jump statements like break/continue/etc. Since there is no # statement that can interrupt a conditional, we don't need to track their # lexical scope. That may change in the future. self.builder.begin_statement(node) self.builder.enter_cond_section(node) self._process_basic_statement(node.test) self.builder.new_cond_branch(node) for stmt in node.body: self.visit(stmt) self.builder.new_cond_branch(node) for stmt in node.orelse: self.visit(stmt) self.builder.exit_cond_section(node) self.builder.end_statement(node) def visit_While(self, node): self.builder.begin_statement(node) self._enter_lexical_scope(node) self.builder.enter_section(node) self.builder.enter_loop_section(node, node.test) for stmt in node.body: self.visit(stmt) self.builder.exit_loop_section(node) # Note: although the orelse is technically part of the loop node, # the statements inside it don't affect the loop itself. For example, a # break in the loop's orelse will not affect the loop itself. self._exit_lexical_scope(node) for stmt in node.orelse: self.visit(stmt) self.builder.exit_section(node) self.builder.end_statement(node) def visit_For(self, node): self.builder.begin_statement(node) self._enter_lexical_scope(node) self.builder.enter_section(node) # Note: Strictly speaking, this should be node.target + node.iter. # However, the activity analysis accounts for this inconsistency, # so dataflow analysis produces the correct values. self.builder.enter_loop_section(node, node.iter) for stmt in node.body: self.visit(stmt) self.builder.exit_loop_section(node) # Note: although the orelse is technically part of the loop node, # they don't count as loop bodies. For example, a break in the loop's # orelse will affect the parent loop, not the current one. self._exit_lexical_scope(node) for stmt in node.orelse: self.visit(stmt) self.builder.exit_section(node) self.builder.end_statement(node) def visit_Break(self, node): self._process_exit_statement(node, gast.While, gast.For) def visit_Continue(self, node): self._process_continue_statement(node, gast.While, gast.For) def visit_ExceptHandler(self, node): self.builder.begin_statement(node) if node.type is not None: self.visit(node.type) if node.name is not None: self.visit(node.name) for stmt in node.body: self.visit(stmt) self.builder.end_statement(node) def visit_Try(self, node): self.builder.begin_statement(node) self._enter_lexical_scope(node) # Note: the current simplification is that the try block fully executes # regardless of whether an exception triggers or not. This is consistent # with blocks free of try/except, which also don't account for the # possibility of an exception being raised mid-block. for stmt in node.body: self.visit(stmt) # The orelse is an optional continuation of the body. if node.orelse: block_representative = node.orelse[0] self.builder.enter_cond_section(block_representative) self.builder.new_cond_branch(block_representative) for stmt in node.orelse: self.visit(stmt) self.builder.new_cond_branch(block_representative) self.builder.exit_cond_section(block_representative) self._exit_lexical_scope(node) if node.handlers: # Using node would be inconsistent. Using the first handler node is also # inconsistent, but less so. block_representative = node.handlers[0] self.builder.enter_cond_section(block_representative) for block in node.handlers: self.builder.new_cond_branch(block_representative) self.visit(block) self.builder.new_cond_branch(block_representative) self.builder.exit_cond_section(block_representative) if node.finalbody: self.builder.enter_finally_section(node) for stmt in node.finalbody: self.visit(stmt) self.builder.exit_finally_section(node) self.builder.end_statement(node) def visit_With(self, node): # TODO(mdan): Mark the context manager's exit call as exit guard. for item in node.items: self._process_basic_statement(item) for stmt in node.body: self.visit(stmt) def build(node): visitor = AstToCfg() visitor.visit(node) return visitor.cfgs
tensorflow-master
tensorflow/python/autograph/pyct/cfg.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for templates module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import origin_info from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import transformer from tensorflow.python.platform import test class TransformerTest(test.TestCase): def _simple_context(self): entity_info = transformer.EntityInfo( source_code=None, source_file=None, future_features=(), namespace=None) return transformer.Context(entity_info) def test_entity_scope_tracking(self): class TestTransformer(transformer.Base): # The choice of note to assign to is arbitrary. Using Assign because it's # easy to find in the tree. def visit_Assign(self, node): anno.setanno(node, 'enclosing_entities', self.enclosing_entities) return self.generic_visit(node) # This will show up in the lambda function. def visit_BinOp(self, node): anno.setanno(node, 'enclosing_entities', self.enclosing_entities) return self.generic_visit(node) tr = TestTransformer(self._simple_context()) def test_function(): a = 0 class TestClass(object): def test_method(self): b = 0 def inner_function(x): c = 0 d = lambda y: (x + y) return c, d return b, inner_function return a, TestClass node, _ = parser.parse_entity(test_function, future_features=()) node = tr.visit(node) test_function_node = node test_class = test_function_node.body[1] test_method = test_class.body[0] inner_function = test_method.body[1] lambda_node = inner_function.body[1].value a = test_function_node.body[0] b = test_method.body[0] c = inner_function.body[0] lambda_expr = lambda_node.body self.assertEqual( (test_function_node,), anno.getanno(a, 'enclosing_entities')) self.assertEqual((test_function_node, test_class, test_method), anno.getanno(b, 'enclosing_entities')) self.assertEqual( (test_function_node, test_class, test_method, inner_function), anno.getanno(c, 'enclosing_entities')) self.assertEqual((test_function_node, test_class, test_method, inner_function, lambda_node), anno.getanno(lambda_expr, 'enclosing_entities')) def assertSameAnno(self, first, second, key): self.assertIs(anno.getanno(first, key), anno.getanno(second, key)) def assertDifferentAnno(self, first, second, key): self.assertIsNot(anno.getanno(first, key), anno.getanno(second, key)) def test_state_tracking(self): class LoopState(object): pass class CondState(object): pass class TestTransformer(transformer.Base): def visit(self, node): anno.setanno(node, 'loop_state', self.state[LoopState].value) anno.setanno(node, 'cond_state', self.state[CondState].value) return super(TestTransformer, self).visit(node) def visit_While(self, node): self.state[LoopState].enter() node = self.generic_visit(node) self.state[LoopState].exit() return node def visit_If(self, node): self.state[CondState].enter() node = self.generic_visit(node) self.state[CondState].exit() return node tr = TestTransformer(self._simple_context()) def test_function(a): a = 1 while a: _ = 'a' if a > 2: _ = 'b' while True: raise '1' if a > 3: _ = 'c' while True: raise '1' node, _ = parser.parse_entity(test_function, future_features=()) node = tr.visit(node) fn_body = node.body outer_while_body = fn_body[1].body self.assertSameAnno(fn_body[0], outer_while_body[0], 'cond_state') self.assertDifferentAnno(fn_body[0], outer_while_body[0], 'loop_state') first_if_body = outer_while_body[1].body self.assertDifferentAnno(outer_while_body[0], first_if_body[0], 'cond_state') self.assertSameAnno(outer_while_body[0], first_if_body[0], 'loop_state') first_inner_while_body = first_if_body[1].body self.assertSameAnno(first_if_body[0], first_inner_while_body[0], 'cond_state') self.assertDifferentAnno(first_if_body[0], first_inner_while_body[0], 'loop_state') second_if_body = outer_while_body[2].body self.assertDifferentAnno(first_if_body[0], second_if_body[0], 'cond_state') self.assertSameAnno(first_if_body[0], second_if_body[0], 'loop_state') second_inner_while_body = second_if_body[1].body self.assertDifferentAnno(first_inner_while_body[0], second_inner_while_body[0], 'cond_state') self.assertDifferentAnno(first_inner_while_body[0], second_inner_while_body[0], 'loop_state') def test_local_scope_info_stack(self): class TestTransformer(transformer.Base): # Extract all string constants from the block. def visit_Str(self, node): self.set_local('string', self.get_local('string', default='') + node.s) return self.generic_visit(node) def _annotate_result(self, node): self.enter_local_scope() node = self.generic_visit(node) anno.setanno(node, 'test', self.get_local('string')) self.exit_local_scope() return node def visit_While(self, node): return self._annotate_result(node) def visit_For(self, node): return self._annotate_result(node) tr = TestTransformer(self._simple_context()) def test_function(a): """Docstring.""" assert a == 'This should not be counted' for i in range(3): _ = 'a' if i > 2: return 'b' else: _ = 'c' while True: raise '1' return 'nor this' node, _ = parser.parse_entity(test_function, future_features=()) node = tr.visit(node) for_node = node.body[2] while_node = for_node.body[1].orelse[1] self.assertFalse(anno.hasanno(for_node, 'string')) self.assertEqual('abc', anno.getanno(for_node, 'test')) self.assertFalse(anno.hasanno(while_node, 'string')) self.assertEqual('1', anno.getanno(while_node, 'test')) def test_local_scope_info_stack_checks_integrity(self): class TestTransformer(transformer.Base): def visit_If(self, node): self.enter_local_scope() return self.generic_visit(node) def visit_For(self, node): node = self.generic_visit(node) self.exit_local_scope() return node tr = TestTransformer(self._simple_context()) def no_exit(a): if a > 0: print(a) return None node, _ = parser.parse_entity(no_exit, future_features=()) with self.assertRaises(AssertionError): tr.visit(node) def no_entry(a): for _ in a: print(a) node, _ = parser.parse_entity(no_entry, future_features=()) with self.assertRaises(AssertionError): tr.visit(node) def test_visit_block_postprocessing(self): class TestTransformer(transformer.Base): def _process_body_item(self, node): if isinstance(node, gast.Assign) and (node.value.id == 'y'): if_node = gast.If(gast.Name('x', gast.Load(), None), [node], []) return if_node, if_node.body return node, None def visit_FunctionDef(self, node): node.body = self.visit_block( node.body, after_visit=self._process_body_item) return node def test_function(x, y): z = x z = y return z tr = TestTransformer(self._simple_context()) node, _ = parser.parse_entity(test_function, future_features=()) node = tr.visit(node) self.assertEqual(len(node.body), 2) self.assertTrue(isinstance(node.body[0], gast.Assign)) self.assertTrue(isinstance(node.body[1], gast.If)) self.assertTrue(isinstance(node.body[1].body[0], gast.Assign)) self.assertTrue(isinstance(node.body[1].body[1], gast.Return)) def test_robust_error_on_list_visit(self): class BrokenTransformer(transformer.Base): def visit_If(self, node): # This is broken because visit expects a single node, not a list, and # the body of an if is a list. # Importantly, the default error handling in visit also expects a single # node. Therefore, mistakes like this need to trigger a type error # before the visit called here installs its error handler. # That type error can then be caught by the enclosing call to visit, # and correctly blame the If node. self.visit(node.body) return node def test_function(x): if x > 0: return x tr = BrokenTransformer(self._simple_context()) node, _ = parser.parse_entity(test_function, future_features=()) with self.assertRaises(ValueError) as cm: node = tr.visit(node) obtained_message = str(cm.exception) expected_message = r'expected "ast.AST", got "\<(type|class) \'list\'\>"' self.assertRegexpMatches(obtained_message, expected_message) def test_robust_error_on_ast_corruption(self): # A child class should not be able to be so broken that it causes the error # handling in `transformer.Base` to raise an exception. Why not? Because # then the original error location is dropped, and an error handler higher # up in the call stack gives misleading information. # Here we test that the error handling in `visit` completes, and blames the # correct original exception, even if the AST gets corrupted. class NotANode(object): pass class BrokenTransformer(transformer.Base): def visit_If(self, node): node.body = NotANode() raise ValueError('I blew up') def test_function(x): if x > 0: return x tr = BrokenTransformer(self._simple_context()) node, _ = parser.parse_entity(test_function, future_features=()) with self.assertRaises(ValueError) as cm: node = tr.visit(node) obtained_message = str(cm.exception) # The message should reference the exception actually raised, not anything # from the exception handler. expected_substring = 'I blew up' self.assertTrue(expected_substring in obtained_message, obtained_message) def test_origin_info_propagated_to_new_nodes(self): class TestTransformer(transformer.Base): def visit_If(self, node): return gast.Pass() tr = TestTransformer(self._simple_context()) def test_fn(): x = 1 if x > 0: x = 1 return x node, source = parser.parse_entity(test_fn, future_features=()) origin_info.resolve(node, source, 'test_file', 100, 0) node = tr.visit(node) created_pass_node = node.body[1] # Takes the line number of the if statement. self.assertEqual( anno.getanno(created_pass_node, anno.Basic.ORIGIN).loc.lineno, 102) def test_origin_info_preserved_in_moved_nodes(self): class TestTransformer(transformer.Base): def visit_If(self, node): return node.body tr = TestTransformer(self._simple_context()) def test_fn(): x = 1 if x > 0: x = 1 x += 3 return x node, source = parser.parse_entity(test_fn, future_features=()) origin_info.resolve(node, source, 'test_file', 100, 0) node = tr.visit(node) assign_node = node.body[1] aug_assign_node = node.body[2] # Keep their original line numbers. self.assertEqual( anno.getanno(assign_node, anno.Basic.ORIGIN).loc.lineno, 103) self.assertEqual( anno.getanno(aug_assign_node, anno.Basic.ORIGIN).loc.lineno, 104) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/transformer_test.py
# Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for errors module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import re from tensorflow.python.autograph.pyct import errors from tensorflow.python.platform import test class ErrorMetadataBaseTest(test.TestCase): def test_create_exception_default_constructor(self): class CustomError(Exception): pass em = errors.ErrorMetadataBase( callsite_tb=(), cause_metadata=None, cause_message='test message', source_map={}) exc = em.create_exception(CustomError) self.assertIsInstance(exc, CustomError) self.assertIn('test message', str(exc)) def test_create_exception_custom_constructor(self): class CustomError(Exception): def __init__(self): super(CustomError, self).__init__('test_message') em = errors.ErrorMetadataBase( callsite_tb=(), cause_metadata=None, cause_message='test message', source_map={}) exc = em.create_exception(CustomError) self.assertIsNone(exc) def test_get_message_when_frame_info_code_is_none(self): callsite_tb = [ ('/path/one.py', 11, 'test_fn_1', None), ('/path/two.py', 171, 'test_fn_2', 'test code'), ] cause_message = 'Test message' em = errors.ErrorMetadataBase( callsite_tb=callsite_tb, cause_metadata=None, cause_message=cause_message, source_map={}) self.assertRegex( em.get_message(), re.compile('test_fn_1.*test_fn_2.*Test message', re.DOTALL)) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/errors_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for compiler module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import textwrap import gast from tensorflow.python.autograph.pyct import compiler from tensorflow.python.autograph.pyct import parser from tensorflow.python.platform import test from tensorflow.python.util import tf_inspect class CompilerTest(test.TestCase): def test_parser_compile_identity(self): def test_fn(x): a = True b = '' if a: b = x + 1 return b node, _ = parser.parse_entity(test_fn, future_features=()) module, _, _ = compiler.ast_to_object(node) self.assertEqual( textwrap.dedent(tf_inspect.getsource(test_fn)), tf_inspect.getsource(module.test_fn)) def test_ast_to_source(self): node = gast.If( test=gast.Num(1), body=[ gast.Assign( targets=[gast.Name('a', gast.Store(), None)], value=gast.Name('b', gast.Load(), None)) ], orelse=[ gast.Assign( targets=[gast.Name('a', gast.Store(), None)], value=gast.Str('c')) ]) source = compiler.ast_to_source(node, indentation=' ') self.assertEqual( textwrap.dedent(""" if 1: a = b else: a = 'c' """).strip(), source.strip()) def test_ast_to_object(self): node = gast.FunctionDef( name='f', args=gast.arguments( args=[gast.Name('a', gast.Param(), None)], vararg=None, kwonlyargs=[], kwarg=None, defaults=[], kw_defaults=[]), body=[ gast.Return( gast.BinOp( op=gast.Add(), left=gast.Name('a', gast.Load(), None), right=gast.Num(1))) ], decorator_list=[], returns=None) module, source, _ = compiler.ast_to_object(node) expected_source = """ def f(a): return a + 1 """ self.assertEqual( textwrap.dedent(expected_source).strip(), source.strip()) self.assertEqual(2, module.f(1)) with open(module.__file__, 'r') as temp_output: self.assertEqual( textwrap.dedent(expected_source).strip(), temp_output.read().strip()) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/compiler_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Converting AST to code and Python entities. Adapted from Tangent. """ # TODO(mdan): Consolidate with parser and rename to parsing.py from __future__ import absolute_import from __future__ import division from __future__ import print_function # TODO(mdan): Use six for compatibility here. import atexit import imp import os import tempfile import astor import gast from tensorflow.python.autograph.pyct import origin_info from tensorflow.python.autograph.utils import ag_logging def ast_to_source(node, indentation=' '): """Return the source code of given AST. Args: node: The code to compile, as an AST object. indentation: The string to use for indentation. Returns: code: The source code generated from the AST object source_mapping: A mapping between the user and AutoGraph generated code. """ if not isinstance(node, (list, tuple)): node = (node,) generator = astor.code_gen.SourceGenerator(indentation, False, astor.string_repr.pretty_string) for n in node: if isinstance(n, gast.AST): n = gast.gast_to_ast(n) generator.visit(n) generator.result.append('\n') # In some versions of Python, literals may appear as actual values. This # ensures everything is string. code = ''.join(map(str, generator.result)) # Strip leading blank lines. code_lines = code.split('\n') trimmed_code_lines = [] for l in code_lines: if l.rstrip() or trimmed_code_lines: trimmed_code_lines.append(l) code = '\n'.join(trimmed_code_lines) # Work around the reference cycle generated by astor. # See https://github.com/berkerpeksag/astor/blob/55dd323f7d8d696610c703c0296763c567685c31/astor/code_gen.py#L162 # pylint:disable=line-too-long # Reference cycles are quite disliked by TensorFlow's tests. if hasattr(generator, 'write'): generator.write = None del generator return code def source_to_entity(source, delete_on_exit): with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f: module_name = os.path.basename(f.name[:-3]) f.write(source) # TODO(mdan): Try flush() and delete=False instead. if delete_on_exit and ag_logging.get_verbosity() < 3: atexit.register(lambda: os.remove(f.name)) return imp.load_source(module_name, f.name), f.name # TODO(mdan): Rename: ast_to_entity def ast_to_object(nodes, indentation=' ', include_source_map=False, delete_on_exit=True): """Return the Python objects represented by given AST. Compiling the AST code this way ensures that the source code is readable by e.g. `pdb` or `inspect`. Args: nodes: Union[ast.AST, Iterable[ast.AST]], the code to compile, as an AST object. indentation: Text, the string to use for indentation. include_source_map: bool, whether return a source map. delete_on_exit: bool, whether to delete the temporary file used for compilation on exit. Returns: Tuple[module, Text, Dict[LineLocation, OriginInfo]], containing: the module containing the unparsed nodes, the source code corresponding to nodes, and the source map. Is include_source_map is False, the source map will be None. """ if not isinstance(nodes, (list, tuple)): nodes = (nodes,) source = ast_to_source(nodes, indentation=indentation) module, _ = source_to_entity(source, delete_on_exit) if include_source_map: source_map = origin_info.create_source_map(nodes, source, module.__file__) else: source_map = None # TODO(mdan): Return a structured object. return module, source, source_map
tensorflow-master
tensorflow/python/autograph/pyct/compiler.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for cfg module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.pyct import cfg from tensorflow.python.autograph.pyct import parser from tensorflow.python.platform import test class CountingVisitor(cfg.GraphVisitor): def __init__(self, graph): super(CountingVisitor, self).__init__(graph) self.counts = {} def init_state(self, _): return None def visit_node(self, node): self.counts[node.ast_node] = self.counts.get(node.ast_node, 0) + 1 return False # visit only once class GraphVisitorTest(test.TestCase): def _build_cfg(self, fn): node, _ = parser.parse_entity(fn, future_features=()) cfgs = cfg.build(node) return cfgs, node def test_basic_coverage_forward(self): def test_fn(a): while a > 0: a = 1 break return a # pylint:disable=unreachable a = 2 graphs, node = self._build_cfg(test_fn) graph, = graphs.values() visitor = CountingVisitor(graph) visitor.visit_forward() self.assertEqual(visitor.counts[node.args], 1) self.assertEqual(visitor.counts[node.body[0].test], 1) self.assertEqual(visitor.counts[node.body[0].body[0]], 1) self.assertEqual(visitor.counts[node.body[0].body[1]], 1) # The return node should be unreachable in forward direction. self.assertNotIn(node.body[0].body[2], visitor.counts) self.assertEqual(visitor.counts[node.body[1]], 1) def test_basic_coverage_reverse(self): def test_fn(a): while a > 0: a = 1 break return a # pylint:disable=unreachable a = 2 graphs, node = self._build_cfg(test_fn) graph, = graphs.values() visitor = CountingVisitor(graph) visitor.visit_reverse() self.assertEqual(visitor.counts[node.args], 1) self.assertEqual(visitor.counts[node.body[0].test], 1) self.assertEqual(visitor.counts[node.body[0].body[0]], 1) self.assertEqual(visitor.counts[node.body[0].body[1]], 1) self.assertTrue(visitor.counts[node.body[0].body[2]], 1) self.assertEqual(visitor.counts[node.body[1]], 1) class AstToCfgTest(test.TestCase): def _build_cfg(self, fn): node, _ = parser.parse_entity(fn, future_features=()) cfgs = cfg.build(node) return cfgs def _repr_set(self, node_set): return frozenset(repr(n) for n in node_set) def _as_set(self, elements): if elements is None: return frozenset() elif isinstance(elements, str): return frozenset((elements,)) else: return frozenset(elements) def assertGraphMatches(self, graph, edges): """Tests whether the CFG contains the specified edges.""" for prev, node_repr, next_ in edges: matched = False for cfg_node in graph.index.values(): if repr(cfg_node) == node_repr: if (self._as_set(prev) == frozenset(map(repr, cfg_node.prev)) and self._as_set(next_) == frozenset(map(repr, cfg_node.next))): matched = True break if not matched: self.fail( 'match failed for node "%s" in graph:\n%s' % (node_repr, graph)) def assertStatementEdges(self, graph, edges): """Tests whether the CFG contains the specified statement edges.""" for prev_node_reprs, node_repr, next_node_reprs in edges: matched = False partial_matches = [] self.assertSetEqual( frozenset(graph.stmt_next.keys()), frozenset(graph.stmt_prev.keys())) for stmt_ast_node in graph.stmt_next: ast_repr = '%s:%s' % (stmt_ast_node.__class__.__name__, stmt_ast_node.lineno) if ast_repr == node_repr: actual_next = frozenset(map(repr, graph.stmt_next[stmt_ast_node])) actual_prev = frozenset(map(repr, graph.stmt_prev[stmt_ast_node])) partial_matches.append((actual_prev, node_repr, actual_next)) if (self._as_set(prev_node_reprs) == actual_prev and self._as_set(next_node_reprs) == actual_next): matched = True break if not matched: self.fail('edges mismatch for %s: %s' % (node_repr, partial_matches)) def test_straightline(self): def test_fn(a): a += 1 a = 2 a = 3 return graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (None, 'a', 'a += 1'), ('a += 1', 'a = 2', 'a = 3'), ('a = 2', 'a = 3', 'return'), ('a = 3', 'return', None), ), ) def test_straightline_no_return(self): def test_fn(a, b): a = b + 1 a += max(a) graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (None, 'a, b', 'a = b + 1'), ('a = b + 1', 'a += max(a)', None), ), ) def test_unreachable_code(self): def test_fn(a): return a += 1 # pylint:disable=unreachable graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (None, 'a', 'return'), ('a', 'return', None), (None, 'a += 1', None), ), ) def test_if_straightline(self): def test_fn(a): if a > 0: a = 1 else: a += -1 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (None, 'a', '(a > 0)'), ('(a > 0)', 'a = 1', None), ('(a > 0)', 'a += -1', None), ), ) self.assertStatementEdges( graph, (('a', 'If:2', None),), ) def test_branch_nested(self): def test_fn(a): if a > 0: if a > 1: a = 1 else: a = 2 else: if a > 2: a = 3 else: a = 4 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (None, 'a', '(a > 0)'), ('a', '(a > 0)', ('(a > 1)', '(a > 2)')), ('(a > 0)', '(a > 1)', ('a = 1', 'a = 2')), ('(a > 1)', 'a = 1', None), ('(a > 1)', 'a = 2', None), ('(a > 0)', '(a > 2)', ('a = 3', 'a = 4')), ('(a > 2)', 'a = 3', None), ('(a > 2)', 'a = 4', None), ), ) self.assertStatementEdges( graph, ( ('a', 'If:2', None), ('(a > 0)', 'If:3', None), ('(a > 0)', 'If:8', None), ), ) def test_branch_straightline_semi(self): def test_fn(a): if a > 0: a = 1 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (None, 'a', '(a > 0)'), ('a', '(a > 0)', 'a = 1'), ('(a > 0)', 'a = 1', None), ), ) self.assertStatementEdges( graph, (('a', 'If:2', None),), ) def test_branch_return(self): def test_fn(a): if a > 0: return else: a = 1 a = 2 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', '(a > 0)', ('return', 'a = 1')), ('(a > 0)', 'a = 1', 'a = 2'), ('(a > 0)', 'return', None), ('a = 1', 'a = 2', None), ), ) self.assertStatementEdges( graph, (('a', 'If:2', 'a = 2'),), ) def test_branch_return_minimal(self): def test_fn(a): if a > 0: return graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', '(a > 0)', 'return'), ('(a > 0)', 'return', None), ), ) self.assertStatementEdges( graph, (('a', 'If:2', None),), ) def test_while_straightline(self): def test_fn(a): while a > 0: a = 1 a = 2 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'a = 1'), '(a > 0)', ('a = 1', 'a = 2')), ('(a > 0)', 'a = 1', '(a > 0)'), ('(a > 0)', 'a = 2', None), ), ) self.assertStatementEdges( graph, (('a', 'While:2', 'a = 2'),), ) def test_while_else_straightline(self): def test_fn(a): while a > 0: a = 1 else: # pylint:disable=useless-else-on-loop a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'a = 1'), '(a > 0)', ('a = 1', 'a = 2')), ('(a > 0)', 'a = 1', '(a > 0)'), ('(a > 0)', 'a = 2', 'a = 3'), ('a = 2', 'a = 3', None), ), ) self.assertStatementEdges( graph, (('a', 'While:2', 'a = 3'),), ) def test_while_else_continue(self): def test_fn(a): while a > 0: if a > 1: continue else: a = 0 a = 1 else: # pylint:disable=useless-else-on-loop a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'continue', 'a = 1'), '(a > 0)', ('(a > 1)', 'a = 2')), ('(a > 0)', '(a > 1)', ('continue', 'a = 0')), ('(a > 1)', 'continue', '(a > 0)'), ('a = 0', 'a = 1', '(a > 0)'), ('(a > 0)', 'a = 2', 'a = 3'), ('a = 2', 'a = 3', None), ), ) self.assertStatementEdges( graph, ( ('a', 'While:2', 'a = 3'), ('(a > 0)', 'If:3', ('a = 1', '(a > 0)')), ), ) def test_while_else_break(self): def test_fn(a): while a > 0: if a > 1: break a = 1 else: a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'a = 1'), '(a > 0)', ('(a > 1)', 'a = 2')), ('(a > 0)', '(a > 1)', ('break', 'a = 1')), ('(a > 1)', 'break', 'a = 3'), ('(a > 1)', 'a = 1', '(a > 0)'), ('(a > 0)', 'a = 2', 'a = 3'), (('break', 'a = 2'), 'a = 3', None), ), ) self.assertStatementEdges( graph, ( ('a', 'While:2', 'a = 3'), ('(a > 0)', 'If:3', ('a = 1', 'a = 3')), ), ) def test_while_else_return(self): def test_fn(a): while a > 0: if a > 1: return a = 1 else: # pylint:disable=useless-else-on-loop a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'a = 1'), '(a > 0)', ('(a > 1)', 'a = 2')), ('(a > 0)', '(a > 1)', ('return', 'a = 1')), ('(a > 1)', 'return', None), ('(a > 1)', 'a = 1', '(a > 0)'), ('(a > 0)', 'a = 2', 'a = 3'), ('a = 2', 'a = 3', None), ), ) self.assertStatementEdges( graph, ( ('a', 'While:2', 'a = 3'), ('(a > 0)', 'If:3', 'a = 1'), ), ) def test_while_nested_straightline(self): def test_fn(a): while a > 0: while a > 1: a = 1 a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'a = 2'), '(a > 0)', ('(a > 1)', 'a = 3')), (('(a > 0)', 'a = 1'), '(a > 1)', ('a = 1', 'a = 2')), ('(a > 1)', 'a = 1', '(a > 1)'), ('(a > 1)', 'a = 2', '(a > 0)'), ('(a > 0)', 'a = 3', None), ), ) self.assertStatementEdges( graph, ( ('a', 'While:2', 'a = 3'), ('(a > 0)', 'While:3', 'a = 2'), ), ) def test_while_nested_continue(self): def test_fn(a): while a > 0: while a > 1: if a > 3: continue a = 1 a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'a = 2'), '(a > 0)', ('(a > 1)', 'a = 3')), (('(a > 0)', 'continue', 'a = 1'), '(a > 1)', ('(a > 3)', 'a = 2')), ('(a > 1)', '(a > 3)', ('continue', 'a = 1')), ('(a > 3)', 'continue', '(a > 1)'), ('(a > 3)', 'a = 1', '(a > 1)'), ('(a > 1)', 'a = 2', '(a > 0)'), ('(a > 0)', 'a = 3', None), ), ) self.assertStatementEdges( graph, ( ('a', 'While:2', 'a = 3'), ('(a > 0)', 'While:3', 'a = 2'), ('(a > 1)', 'If:4', ('a = 1', '(a > 1)')), ), ) def test_while_nested_break(self): def test_fn(a): while a > 0: while a > 1: if a > 2: break a = 1 a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches(graph, ( (('a', 'a = 2'), '(a > 0)', ('(a > 1)', 'a = 3')), (('(a > 0)', 'a = 1'), '(a > 1)', ('(a > 2)', 'a = 2')), ('(a > 1)', '(a > 2)', ('break', 'a = 1')), ('(a > 2)', 'break', 'a = 2'), ('(a > 2)', 'a = 1', '(a > 1)'), (('(a > 1)', 'break'), 'a = 2', '(a > 0)'), ('(a > 0)', 'a = 3', None), )) self.assertStatementEdges( graph, ( ('a', 'While:2', 'a = 3'), ('(a > 0)', 'While:3', 'a = 2'), ('(a > 1)', 'If:4', ('a = 1', 'a = 2')), ), ) def test_for_straightline(self): def test_fn(a): for a in range(0, a): a = 1 a = 2 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'a = 1'), 'range(0, a)', ('a = 1', 'a = 2')), ('range(0, a)', 'a = 1', 'range(0, a)'), ('range(0, a)', 'a = 2', None), ), ) self.assertStatementEdges( graph, (('a', 'For:2', 'a = 2'),), ) def test_for_else_straightline(self): def test_fn(a): for a in range(0, a): a = 1 else: # pylint:disable=useless-else-on-loop a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'a = 1'), 'range(0, a)', ('a = 1', 'a = 2')), ('range(0, a)', 'a = 1', 'range(0, a)'), ('range(0, a)', 'a = 2', 'a = 3'), ('a = 2', 'a = 3', None), ), ) self.assertStatementEdges( graph, (('a', 'For:2', 'a = 3'),), ) def test_for_else_continue(self): def test_fn(a): for a in range(0, a): if a > 1: continue else: a = 0 a = 1 else: # pylint:disable=useless-else-on-loop a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'continue', 'a = 1'), 'range(0, a)', ('(a > 1)', 'a = 2')), ('range(0, a)', '(a > 1)', ('continue', 'a = 0')), ('(a > 1)', 'continue', 'range(0, a)'), ('(a > 1)', 'a = 0', 'a = 1'), ('a = 0', 'a = 1', 'range(0, a)'), ('range(0, a)', 'a = 2', 'a = 3'), ('a = 2', 'a = 3', None), ), ) self.assertStatementEdges( graph, ( ('a', 'For:2', 'a = 3'), ('range(0, a)', 'If:3', ('a = 1', 'range(0, a)')), ), ) def test_for_else_break(self): def test_fn(a): for a in range(0, a): if a > 1: break a = 1 else: a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'a = 1'), 'range(0, a)', ('(a > 1)', 'a = 2')), ('range(0, a)', '(a > 1)', ('break', 'a = 1')), ('(a > 1)', 'break', 'a = 3'), ('(a > 1)', 'a = 1', 'range(0, a)'), ('range(0, a)', 'a = 2', 'a = 3'), (('break', 'a = 2'), 'a = 3', None), ), ) self.assertStatementEdges( graph, ( ('a', 'For:2', 'a = 3'), ('range(0, a)', 'If:3', ('a = 1', 'a = 3')), ), ) def test_for_else_return(self): def test_fn(a): for a in range(0, a): if a > 1: return a = 1 else: # pylint:disable=useless-else-on-loop a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'a = 1'), 'range(0, a)', ('(a > 1)', 'a = 2')), ('range(0, a)', '(a > 1)', ('return', 'a = 1')), ('(a > 1)', 'return', None), ('(a > 1)', 'a = 1', 'range(0, a)'), ('range(0, a)', 'a = 2', 'a = 3'), ('a = 2', 'a = 3', None), ), ) self.assertStatementEdges( graph, ( ('a', 'For:2', 'a = 3'), ('range(0, a)', 'If:3', 'a = 1'), ), ) def test_for_nested_straightline(self): def test_fn(a): for a in range(0, a): for b in range(1, a): b += 1 a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'a = 2'), 'range(0, a)', ('range(1, a)', 'a = 3')), (('range(0, a)', 'b += 1'), 'range(1, a)', ('b += 1', 'a = 2')), ('range(1, a)', 'b += 1', 'range(1, a)'), ('range(1, a)', 'a = 2', 'range(0, a)'), ('range(0, a)', 'a = 3', None), ), ) self.assertStatementEdges( graph, ( ('a', 'For:2', 'a = 3'), ('range(0, a)', 'For:3', 'a = 2'), ), ) def test_for_nested_continue(self): def test_fn(a): for a in range(0, a): for b in range(1, a): if a > 3: continue b += 1 a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'a = 2'), 'range(0, a)', ('range(1, a)', 'a = 3')), (('range(0, a)', 'continue', 'b += 1'), 'range(1, a)', ('(a > 3)', 'a = 2')), ('range(1, a)', '(a > 3)', ('continue', 'b += 1')), ('(a > 3)', 'continue', 'range(1, a)'), ('(a > 3)', 'b += 1', 'range(1, a)'), ('range(1, a)', 'a = 2', 'range(0, a)'), ('range(0, a)', 'a = 3', None), ), ) self.assertStatementEdges( graph, ( ('a', 'For:2', 'a = 3'), ('range(0, a)', 'For:3', 'a = 2'), ('range(1, a)', 'If:4', ('b += 1', 'range(1, a)')), ), ) def test_for_nested_break(self): def test_fn(a): for a in range(0, a): for b in range(1, a): if a > 2: break b += 1 a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'a = 2'), 'range(0, a)', ('range(1, a)', 'a = 3')), (('range(0, a)', 'b += 1'), 'range(1, a)', ('(a > 2)', 'a = 2')), ('range(1, a)', '(a > 2)', ('break', 'b += 1')), ('(a > 2)', 'break', 'a = 2'), ('(a > 2)', 'b += 1', 'range(1, a)'), (('range(1, a)', 'break'), 'a = 2', 'range(0, a)'), ('range(0, a)', 'a = 3', None), ), ) self.assertStatementEdges( graph, ( ('a', 'For:2', 'a = 3'), ('range(0, a)', 'For:3', 'a = 2'), ('range(1, a)', 'If:4', ('b += 1', 'a = 2')), ), ) def test_complex(self): def test_fn(a): b = 0 while a > 0: for b in range(0, a): if a > 2: break if a > 3: if a > 4: continue else: max(a) break b += 1 else: # for b in range(0, a): return a a = 2 for a in range(1, a): return b a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('b = 0', 'a = 2'), '(a > 0)', ('range(0, a)', 'range(1, a)')), ( ('(a > 0)', 'continue', 'b += 1'), 'range(0, a)', ('(a > 2)', 'return a'), ), ('range(0, a)', '(a > 2)', ('(a > 3)', 'break')), ('(a > 2)', 'break', 'a = 2'), ('(a > 2)', '(a > 3)', ('(a > 4)', 'b += 1')), ('(a > 3)', '(a > 4)', ('continue', 'max(a)')), ('(a > 4)', 'max(a)', 'break'), ('max(a)', 'break', 'a = 2'), ('(a > 4)', 'continue', 'range(0, a)'), ('(a > 3)', 'b += 1', 'range(0, a)'), ('range(0, a)', 'return a', None), ('break', 'a = 2', '(a > 0)'), ('(a > 0)', 'range(1, a)', ('return b', 'a = 3')), ('range(1, a)', 'return b', None), ('range(1, a)', 'a = 3', None), ), ) self.assertStatementEdges( graph, ( ('b = 0', 'While:3', 'range(1, a)'), ('(a > 0)', 'For:4', 'a = 2'), ('range(0, a)', 'If:5', ('(a > 3)', 'a = 2')), ('(a > 2)', 'If:7', ('b += 1', 'a = 2', 'range(0, a)')), ('(a > 3)', 'If:8', ('a = 2', 'range(0, a)')), ('(a > 0)', 'For:17', 'a = 3'), ), ) def test_finally_straightline(self): def test_fn(a): try: a += 1 finally: a = 2 a = 3 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', 'a += 1', 'a = 2'), ('a += 1', 'a = 2', 'a = 3'), ('a = 2', 'a = 3', None), ), ) def test_return_finally(self): def test_fn(a): try: return a finally: a = 1 a = 2 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', 'return a', 'a = 1'), ('return a', 'a = 1', None), (None, 'a = 2', None), ), ) def test_break_finally(self): def test_fn(a): while a > 0: try: break finally: a = 1 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', '(a > 0)', 'break'), ('(a > 0)', 'break', 'a = 1'), ('break', 'a = 1', None), ), ) def test_continue_finally(self): def test_fn(a): while a > 0: try: continue finally: a = 1 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( (('a', 'a = 1'), '(a > 0)', 'continue'), ('(a > 0)', 'continue', 'a = 1'), ('continue', 'a = 1', '(a > 0)'), ), ) def test_with_straightline(self): def test_fn(a): with max(a) as b: a = 0 return b graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', 'max(a)', 'a = 0'), ('max(a)', 'a = 0', 'return b'), ('a = 0', 'return b', None), ), ) def test_lambda_basic(self): def test_fn(a): a = lambda b: a + b return a graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', 'a = lambda b: a + b', 'return a'), ('a = lambda b: a + b', 'return a', None), ), ) def test_pass(self): def test_fn(a): # pylint:disable=unused-argument pass graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', 'pass', None), ), ) def test_try_finally(self): def test_fn(a): try: a = 1 finally: a = 2 return a graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', 'a = 1', 'a = 2'), ('a = 1', 'a = 2', 'return a'), ('a = 2', 'return a', None), ), ) self.assertStatementEdges( graph, ( ('a', 'Try:2', 'return a'), ), ) def test_try_except_single_bare(self): def test_fn(a): try: a = 1 a = 2 except: # pylint:disable=bare-except a = 3 return a graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', 'a = 1', 'a = 2'), ('a = 2', 'a = 3', 'return a'), (('a = 2', 'a = 3'), 'return a', None), ), ) self.assertStatementEdges( graph, ( ('a', 'Try:2', 'return a'), ('a = 2', 'ExceptHandler:5', 'return a'), ), ) def test_try_except_single(self): def test_fn(a): try: a = 1 a = 2 except Exception1: # pylint:disable=undefined-variable a = 3 return a graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', 'a = 1', 'a = 2'), ('a = 2', 'a = 3', 'return a'), (('a = 2', 'a = 3'), 'return a', None), ), ) self.assertStatementEdges( graph, ( ('a', 'Try:2', 'return a'), ('a = 2', 'ExceptHandler:5', 'return a'), ), ) def test_try_except_single_aliased(self): def test_fn(a): try: a = 1 except Exception1 as e: # pylint:disable=undefined-variable,unused-variable a = 2 return a graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', 'a = 1', ('a = 2', 'return a')), (('a = 1', 'a = 2'), 'return a', None), ), ) self.assertStatementEdges( graph, ( ('a', 'Try:2', 'return a'), ('a = 1', 'ExceptHandler:4', 'return a'), ), ) def test_try_except_single_tuple_aliased(self): def test_fn(a): try: a = 1 except (Exception1, Exception2) as e: # pylint:disable=undefined-variable,unused-variable a = 2 return a graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', 'a = 1', ('a = 2', 'return a')), (('a = 1', 'a = 2'), 'return a', None), ), ) self.assertStatementEdges( graph, ( ('a', 'Try:2', 'return a'), ('a = 1', 'ExceptHandler:4', 'return a'), ), ) def test_try_except_multiple(self): def test_fn(a): try: a = 1 except Exception1: # pylint:disable=undefined-variable a = 2 except Exception2: # pylint:disable=undefined-variable a = 3 return a graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', 'a = 1', ('a = 2', 'a = 3', 'return a')), (('a = 1', 'a = 2', 'a = 3'), 'return a', None), ), ) self.assertStatementEdges( graph, ( ('a', 'Try:2', 'return a'), ('a = 1', 'ExceptHandler:4', 'return a'), ('a = 1', 'ExceptHandler:6', 'return a'), ), ) def test_try_except_finally(self): def test_fn(a): try: a = 1 except Exception1: # pylint:disable=undefined-variable a = 2 except Exception2: # pylint:disable=undefined-variable a = 3 finally: a = 4 return a graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', 'a = 1', ('a = 2', 'a = 3', 'a = 4')), (('a = 1', 'a = 2', 'a = 3'), 'a = 4', 'return a'), ('a = 4', 'return a', None), ), ) self.assertStatementEdges( graph, ( ('a', 'Try:2', 'return a'), ('a = 1', 'ExceptHandler:4', 'a = 4'), ('a = 1', 'ExceptHandler:6', 'a = 4'), ), ) def test_try_in_if(self): def test_fn(a): try: if a > 0: a = 1 else: a = 2 except Exception1: # pylint:disable=undefined-variable a = 3 a = 4 graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', '(a > 0)', ('a = 1', 'a = 2')), ('(a > 0)', 'a = 1', ('a = 3', 'a = 4')), ('(a > 0)', 'a = 2', ('a = 3', 'a = 4')), (('a = 1', 'a = 2'), 'a = 3', 'a = 4'), (('a = 1', 'a = 2', 'a = 3'), 'a = 4', None), ), ) self.assertStatementEdges( graph, ( ('a', 'Try:2', 'a = 4'), ('a', 'If:3', ('a = 3', 'a = 4')), (('a = 1', 'a = 2'), 'ExceptHandler:7', 'a = 4'), ), ) def test_try_in_if_all_branches_exit(self): def test_fn(a, b): try: if a > 0: raise b else: return 0 except b: return 1 graph, = self._build_cfg(test_fn).values() # TODO(mdan): raise and return should have an edge to the except blocks. self.assertGraphMatches( graph, ( ('a, b', '(a > 0)', ('raise b', 'return 0')), ('(a > 0)', 'raise b', None), ('(a > 0)', 'return 0', None), (None, 'return 1', None), ), ) self.assertStatementEdges( graph, ( ('a, b', 'Try:2', None), ('a, b', 'If:3', None), (None, 'ExceptHandler:7', None), ), ) def test_list_comprehension(self): def test_fn(a): c = [b for b in a] return c graph, = self._build_cfg(test_fn).values() self.assertGraphMatches( graph, ( ('a', 'c = [b for b in a]', 'return c'), ('c = [b for b in a]', 'return c', None), ), ) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/cfg_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for templates module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import imp from absl.testing import parameterized import gast from tensorflow.python.autograph.pyct import compiler from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import qual_names as qn from tensorflow.python.autograph.pyct import templates from tensorflow.python.platform import test class _CtxClearer(gast.NodeTransformer): def visit(self, node): super(_CtxClearer, self).visit(node) if hasattr(node, 'ctx'): node.ctx = None return node def _parse_with_unset_ctx(expr_source): ast_node = parser.parse_expression(expr_source) _CtxClearer().visit(ast_node) return ast_node class _CtxChecker(gast.NodeTransformer): def __init__(self, test_instance, expected_ctx): self.at_top_level = True self.test_instance = test_instance self.expected_ctx = expected_ctx def visit(self, node): if hasattr(node, 'ctx'): self.test_instance.assertIsInstance(node.ctx, self.expected_ctx) if self.at_top_level: self.at_top_level = False self.expected_ctx = gast.Load return super(_CtxChecker, self).visit(node) class TemplatesTest(test.TestCase, parameterized.TestCase): def assertExpectedCtxSet(self, node, ctx): """Assert that node has ctx=ctx at top and ctx=gast.Load everywhere else.""" checker = _CtxChecker(self, ctx) checker.visit(node) def test_replace_tuple(self): template = """ def test_fn(a, c): return b, """ node = templates.replace(template, b=('a', 'c'))[0] result, _, _ = compiler.ast_to_object(node) self.assertEqual((2, 3), result.test_fn(2, 3)) def test_replace_variable(self): template = """ def test_fn(a): a += 1 a = 2 * a + 1 return b """ node = templates.replace(template, a='b')[0] result, _, _ = compiler.ast_to_object(node) self.assertEqual(7, result.test_fn(2)) def test_replace_function_name(self): template = """ def fname(a): a += 1 a = 2 * a + 1 return a """ node = templates.replace(template, fname='test_fn')[0] result, _, _ = compiler.ast_to_object(node) self.assertEqual(7, result.test_fn(2)) def test_replace_code_block(self): template = """ def test_fn(a): block return a """ node = templates.replace( template, block=[ gast.Assign([ gast.Name('a', None, None) ], gast.BinOp(gast.Name('a', None, None), gast.Add(), gast.Num(1))), ] * 2)[0] result, _, _ = compiler.ast_to_object(node) self.assertEqual(3, result.test_fn(1)) def test_replace_attribute(self): template = """ def test_fn(a): return a.foo """ node = templates.replace(template, foo='b')[0] result, _, _ = compiler.ast_to_object(node) mod = imp.new_module('test') mod.b = 3 self.assertEqual(3, result.test_fn(mod)) with self.assertRaises(ValueError): templates.replace(template, foo=1) def test_replace_attribute_context(self): template = """ def test_fn(foo): foo = 0 """ node = templates.replace( template, foo=parser.parse_expression('a.b.c'))[0] self.assertIsInstance(node.body[0].targets[0].ctx, gast.Store) self.assertIsInstance(node.body[0].targets[0].value.ctx, gast.Load) self.assertIsInstance(node.body[0].targets[0].value.value.ctx, gast.Load) def test_replace_list_context(self): template = """ def test_fn(foo): foo = 0 """ node = templates.replace(template, foo=parser.parse_expression('[a, b]'))[0] self.assertIsInstance(node.body[0].targets[0].ctx, gast.Store) self.assertIsInstance(node.body[0].targets[0].elts[0].ctx, gast.Store) self.assertIsInstance(node.body[0].targets[0].elts[1].ctx, gast.Store) def test_replace_tuple_context(self): template = """ def test_fn(foo): foo = 0 """ node = templates.replace(template, foo=parser.parse_expression('(a, b)'))[0] self.assertIsInstance(node.body[0].targets[0].ctx, gast.Store) self.assertIsInstance(node.body[0].targets[0].elts[0].ctx, gast.Store) self.assertIsInstance(node.body[0].targets[0].elts[1].ctx, gast.Store) def test_replace_expression_context(self): template = """ def test_fn(): foo """ node = templates.replace( template, foo=parser.parse_expression('a + 2 * b / -c'))[0] self.assertIsInstance(node.body[0].left.ctx, gast.Load) self.assertIsInstance(node.body[0].right.left.right.ctx, gast.Load) def test_replace_complex_context(self): template = """ def test_fn(): foo = 0 """ node = templates.replace( template, foo=parser.parse_expression('bar(([a, b],)).baz'))[0] self.assertIsInstance(node.body[0].targets[0].ctx, gast.Store) function_call_arg = node.body[0].targets[0].value.args[0] self.assertIsInstance(function_call_arg.elts[0].ctx, gast.Load) self.assertIsInstance(function_call_arg.elts[0].elts[0].ctx, gast.Load) self.assertIsInstance(function_call_arg.elts[0].elts[1].ctx, gast.Load) def test_replace_index(self): template = """ def test_fn(): foo = 0 """ node = templates.replace( template, foo=parser.parse_expression('foo(a[b]).bar'))[0] function_call_arg = node.body[0].targets[0].value.args[0] self.assertIsInstance(function_call_arg.ctx, gast.Load) self.assertIsInstance(function_call_arg.slice.value.ctx, gast.Load) def test_replace_call_keyword(self): template = """ def test_fn(): def f(a, d, f): return a + d + f return f(1, kws=None) """ source = parser.parse_expression('f(d=3, f=5)') node = templates.replace(template, kws=source.keywords)[0] result, _, _ = compiler.ast_to_object(node) self.assertEqual(9, result.test_fn()) with self.assertRaises(ValueError): templates.replace(template, kws=[]) templates.replace(template, kws=1) def test_replace_name_with_call(self): template = """ def test_fn(): b = 5 def g(a): return 3 * a def f(): return g return foo """ source = parser.parse_expression('f()(b)') node = templates.replace(template, foo=source)[0] result, _, _ = compiler.ast_to_object(node) self.assertEqual(15, result.test_fn()) def test_replace_name_with_dict(self): template = """ def test_fn(): return foo['bar'] """ source = parser.parse_expression('{\'bar\': 3}') node = templates.replace(template, foo=source)[0] result, _, _ = compiler.ast_to_object(node) self.assertEqual(3, result.test_fn()) def test_replace_as_expression(self): template = """ foo(a) """ node = templates.replace_as_expression(template, foo='bar', a='baz') self.assertIsInstance(node, gast.Call) self.assertEqual(node.func.id, 'bar') self.assertEqual(node.args[0].id, 'baz') def test_replace_as_expression_restrictions(self): template = """ foo(a) bar(b) """ with self.assertRaises(ValueError): templates.replace_as_expression(template) def test_function_call_in_list(self): template = """ foo(bar) """ source = parser.parse_expression('[a(b(1))]') templates.replace_as_expression(template, bar=source) def test_star_comprehension_in_function_call(self): template = """ a = foo(func, args) """ source = parser.parse_expression('bar(*[i for i in range(j)])') node = templates.replace(template, func=source.func, args=source.args) arg_node = node[0].value.args[1].value self.assertIsInstance(arg_node.generators[0].target.ctx, gast.Store) self.assertIsInstance(arg_node.elt.ctx, gast.Load) def test_lambda_in_function_call(self): template = """ a = foo(arg) """ source = parser.parse_expression('[lambda i: i]') node = templates.replace(template, arg=source) lambda_arg = node[0].value.args[0].elts[0] self.assertIsInstance(lambda_arg.args.args[0].ctx, gast.Param) self.assertIsInstance(lambda_arg.body.ctx, gast.Load) def test_replace_name_with_subscript(self): template = """ foo = bar """ replacement = qn.QN(qn.QN('dictionary'), subscript=qn.QN('key')) node = templates.replace(template, foo=replacement)[0].targets[0] self.assertIsInstance(node.ctx, gast.Store) self.assertIsInstance(node.value.ctx, gast.Load) @parameterized.named_parameters([ ('mixed_attr_subscript', 'a.b["c"]'), ('mixed_subscript_attr', 'a[b.c]'), ('nested_subscript', 'a[b[c]]'), ('repeated_subscript', 'a[b][c]'), ]) def test_replace_name_mixed_attr_subscript(self, expression_source): template = 'foo = bar' replacement = _parse_with_unset_ctx(expression_source) target_node = templates.replace(template, foo=replacement)[0].targets[0] self.assertExpectedCtxSet(target_node, gast.Store) value_node = templates.replace(template, bar=replacement)[0].value self.assertExpectedCtxSet(value_node, gast.Load) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/templates_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Python source code transformation library.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function
tensorflow-master
tensorflow/python/autograph/pyct/__init__.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for parser module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.pyct import parser from tensorflow.python.platform import test class ParserTest(test.TestCase): def test_parse_entity(self): def f(x): return x + 1 node, _ = parser.parse_entity(f, future_features=()) self.assertEqual('f', node.name) def test_parse_entity_print_function(self): def f(x): print(x) node, _ = parser.parse_entity(f, future_features=('print_function',)) self.assertEqual('f', node.name) def test_parse_comments(self): def f(): # unindented comment pass with self.assertRaises(ValueError): parser.parse_entity(f, future_features=()) def test_parse_multiline_strings(self): def f(): print(""" some multiline string""") with self.assertRaises(ValueError): parser.parse_entity(f, future_features=()) def test_parse_expression(self): node = parser.parse_expression('a.b') self.assertEqual('a', node.value.id) self.assertEqual('b', node.attr) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/parser_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Live entity inspection utilities. This module contains whatever inspect doesn't offer out of the box. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import inspect import itertools import linecache import sys import threading import types import six from tensorflow.python.util import tf_inspect # This lock seems to help avoid linecache concurrency errors. _linecache_lock = threading.Lock() # These functions test negative for isinstance(*, types.BuiltinFunctionType) # and inspect.isbuiltin, and are generally not visible in globals(). # TODO(mdan): Remove this. SPECIAL_BUILTINS = { 'dict': dict, 'enumerate': enumerate, 'float': float, 'int': int, 'len': len, 'list': list, 'print': print, 'range': range, 'tuple': tuple, 'type': type, 'zip': zip } if six.PY2: SPECIAL_BUILTINS['xrange'] = xrange def islambda(f): if not tf_inspect.isfunction(f): return False if not hasattr(f, '__name__'): return False return f.__name__ == '<lambda>' def isnamedtuple(f): """Returns True if the argument is a namedtuple-like.""" if not (tf_inspect.isclass(f) and issubclass(f, tuple)): return False if not hasattr(f, '_fields'): return False fields = getattr(f, '_fields') if not isinstance(fields, tuple): return False if not all(isinstance(f, str) for f in fields): return False return True def isbuiltin(f): """Returns True if the argument is a built-in function.""" if f in six.moves.builtins.__dict__.values(): return True elif isinstance(f, types.BuiltinFunctionType): return True elif inspect.isbuiltin(f): return True elif f is eval: return True else: return False def _fix_linecache_record(obj): """Fixes potential corruption of linecache in the presence of functools.wraps. functools.wraps modifies the target object's __module__ field, which seems to confuse linecache in special instances, for example when the source is loaded from a .par file (see https://google.github.io/subpar/subpar.html). This function simply triggers a call to linecache.updatecache when a mismatch was detected between the object's __module__ property and the object's source file. Args: obj: Any """ if hasattr(obj, '__module__'): obj_file = inspect.getfile(obj) obj_module = obj.__module__ # A snapshot of the loaded modules helps avoid "dict changed size during # iteration" errors. loaded_modules = tuple(sys.modules.values()) for m in loaded_modules: if hasattr(m, '__file__') and m.__file__ == obj_file: if obj_module is not m: linecache.updatecache(obj_file, m.__dict__) def getimmediatesource(obj): """A variant of inspect.getsource that ignores the __wrapped__ property.""" with _linecache_lock: _fix_linecache_record(obj) lines, lnum = inspect.findsource(obj) return ''.join(inspect.getblock(lines[lnum:])) def getnamespace(f): """Returns the complete namespace of a function. Namespace is defined here as the mapping of all non-local variables to values. This includes the globals and the closure variables. Note that this captures the entire globals collection of the function, and may contain extra symbols that it does not actually use. Args: f: User defined function. Returns: A dict mapping symbol names to values. """ namespace = dict(six.get_function_globals(f)) closure = six.get_function_closure(f) freevars = six.get_function_code(f).co_freevars if freevars and closure: for name, cell in zip(freevars, closure): namespace[name] = cell.cell_contents return namespace def getqualifiedname(namespace, object_, max_depth=5, visited=None): """Returns the name by which a value can be referred to in a given namespace. If the object defines a parent module, the function attempts to use it to locate the object. This function will recurse inside modules, but it will not search objects for attributes. The recursion depth is controlled by max_depth. Args: namespace: Dict[str, Any], the namespace to search into. object_: Any, the value to search. max_depth: Optional[int], a limit to the recursion depth when searching inside modules. visited: Optional[Set[int]], ID of modules to avoid visiting. Returns: Union[str, None], the fully-qualified name that resolves to the value o, or None if it couldn't be found. """ if visited is None: visited = set() # Copy the dict to avoid "changed size error" during concurrent invocations. # TODO(mdan): This is on the hot path. Can we avoid the copy? namespace = dict(namespace) for name in namespace: # The value may be referenced by more than one symbol, case in which # any symbol will be fine. If the program contains symbol aliases that # change over time, this may capture a symbol that will later point to # something else. # TODO(mdan): Prefer the symbol that matches the value type name. if object_ is namespace[name]: return name # If an object is not found, try to search its parent modules. parent = tf_inspect.getmodule(object_) if (parent is not None and parent is not object_ and parent is not namespace): # No limit to recursion depth because of the guard above. parent_name = getqualifiedname( namespace, parent, max_depth=0, visited=visited) if parent_name is not None: name_in_parent = getqualifiedname( parent.__dict__, object_, max_depth=0, visited=visited) assert name_in_parent is not None, ( 'An object should always be found in its owner module') return '{}.{}'.format(parent_name, name_in_parent) if max_depth: # Iterating over a copy prevents "changed size due to iteration" errors. # It's unclear why those occur - suspecting new modules may load during # iteration. for name in namespace.keys(): value = namespace[name] if tf_inspect.ismodule(value) and id(value) not in visited: visited.add(id(value)) name_in_module = getqualifiedname(value.__dict__, object_, max_depth - 1, visited) if name_in_module is not None: return '{}.{}'.format(name, name_in_module) return None def _get_unbound_function(m): # TODO(mdan): Figure out why six.get_unbound_function fails in some cases. # The failure case is for tf.keras.Model. if hasattr(m, '__func__'): return m.__func__ if hasattr(m, 'im_func'): return m.im_func return m def getdefiningclass(m, owner_class): """Resolves the class (e.g. one of the superclasses) that defined a method.""" # Normalize bound functions to their respective unbound versions. m = _get_unbound_function(m) for superclass in reversed(inspect.getmro(owner_class)): if hasattr(superclass, m.__name__): superclass_m = getattr(superclass, m.__name__) if _get_unbound_function(superclass_m) is m: return superclass elif hasattr(m, '__self__') and m.__self__ == owner_class: # Python 3 class methods only work this way it seems :S return superclass return owner_class def istfmethodtarget(m): """Tests whether an object is a `function.TfMethodTarget`.""" # See eager.function.TfMethodTarget for more details. return (hasattr(m, '__self__') and hasattr(m.__self__, 'weakrefself_target__') and hasattr(m.__self__, 'weakrefself_func__') and hasattr(m, '__module__') and (m.__module__ != 'mock')) def getmethodself(m): """An extended version of inspect.getmethodclass.""" if not hasattr(m, '__self__'): return None if m.__self__ is None: return None # A fallback allowing methods to be actually bound to a type different # than __self__. This is useful when a strong reference from the method # to the object is not desired, for example when caching is involved. if istfmethodtarget(m): return m.__self__.target return m.__self__ def getmethodclass(m): """Resolves a function's owner, e.g. a method's class. Note that this returns the object that the function was retrieved from, not necessarily the class where it was defined. This function relies on Python stack frame support in the interpreter, and has the same limitations that inspect.currentframe. Limitations. This function will only work correctly if the owned class is visible in the caller's global or local variables. Args: m: A user defined function Returns: The class that this function was retrieved from, or None if the function is not an object or class method, or the class that owns the object or method is not visible to m. Raises: ValueError: if the class could not be resolved for any unexpected reason. """ # Callable objects: return their own class. if (not hasattr(m, '__name__') and hasattr(m, '__class__') and hasattr(m, '__call__')): if isinstance(m.__class__, six.class_types): return m.__class__ # Instance method and class methods: return the class of "self". m_self = getmethodself(m) if m_self is not None: if tf_inspect.isclass(m_self): return m_self return m_self.__class__ # Class, static and unbound methods: search all defined classes in any # namespace. This is inefficient but more robust method. owners = [] caller_frame = tf_inspect.currentframe().f_back try: # TODO(mdan): This doesn't consider cell variables. # TODO(mdan): This won't work if the owner is hidden inside a container. # Cell variables may be pulled using co_freevars and the closure. for v in itertools.chain(caller_frame.f_locals.values(), caller_frame.f_globals.values()): if hasattr(v, m.__name__): candidate = getattr(v, m.__name__) # Py2 methods may be bound or unbound, extract im_func to get the # underlying function. if hasattr(candidate, 'im_func'): candidate = candidate.im_func if hasattr(m, 'im_func'): m = m.im_func if candidate is m: owners.append(v) finally: del caller_frame if owners: if len(owners) == 1: return owners[0] # If multiple owners are found, and are not subclasses, raise an error. owner_types = tuple(o if tf_inspect.isclass(o) else type(o) for o in owners) for o in owner_types: if tf_inspect.isclass(o) and issubclass(o, tuple(owner_types)): return o raise ValueError('Found too many owners of %s: %s' % (m, owners)) return None def getfutureimports(entity): """Detects what future imports are necessary to safely execute entity source. Args: entity: Any object Returns: A tuple of future strings """ if not (tf_inspect.isfunction(entity) or tf_inspect.ismethod(entity)): return tuple() return tuple(sorted(name for name, value in entity.__globals__.items() if getattr(value, '__module__', None) == '__future__')) class SuperWrapperForDynamicAttrs(object): """A wrapper that supports dynamic attribute lookup on the super object. For example, in the following code, `super` incorrectly reports that `super(Bar, b)` lacks the `a` attribute: class Foo(object): def __init__(self): self.a = lambda: 1 def bar(self): return hasattr(self, 'a') class Bar(Foo): def bar(self): return super(Bar, self).bar() b = Bar() print(hasattr(super(Bar, b), 'a')) # False print(super(Bar, b).bar()) # True A practical situation when this tends to happen is Keras model hierarchies that hold references to certain layers, like this: class MiniModel(keras.Model): def __init__(self): super(MiniModel, self).__init__() self.fc = keras.layers.Dense(1) def call(self, inputs, training=True): return self.fc(inputs) class DefunnedMiniModel(MiniModel): def call(self, inputs, training=True): return super(DefunnedMiniModel, self).call(inputs, training=training) A side effect of this wrapper is that all attributes become visible, even those created in the subclass. """ # TODO(mdan): Investigate why that happens - it may be for a reason. # TODO(mdan): Probably need more overrides to make it look like super. def __init__(self, target): self._target = target def __getattribute__(self, name): target = object.__getattribute__(self, '_target') if hasattr(target, name): return getattr(target, name) return getattr(target.__self__, name)
tensorflow-master
tensorflow/python/autograph/pyct/inspect_utils.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for inspect_utils module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import functools import imp import textwrap import types import weakref import six from tensorflow.python import lib from tensorflow.python.autograph.pyct import inspect_utils from tensorflow.python.autograph.pyct.testing import basic_definitions from tensorflow.python.autograph.pyct.testing import decorators from tensorflow.python.eager import function from tensorflow.python.framework import constant_op from tensorflow.python.platform import test def decorator(f): return f def function_decorator(): def dec(f): return f return dec def wrapping_decorator(): def dec(f): def replacement(*_): return None @functools.wraps(f) def wrapper(*args, **kwargs): return replacement(*args, **kwargs) return wrapper return dec class TestClass(object): def member_function(self): pass @decorator def decorated_member(self): pass @function_decorator() def fn_decorated_member(self): pass @wrapping_decorator() def wrap_decorated_member(self): pass @staticmethod def static_method(): pass @classmethod def class_method(cls): pass def free_function(): pass def factory(): return free_function def free_factory(): def local_function(): pass return local_function class InspectUtilsTest(test.TestCase): def test_islambda(self): def test_fn(): pass self.assertTrue(inspect_utils.islambda(lambda x: x)) self.assertFalse(inspect_utils.islambda(test_fn)) def test_isnamedtuple(self): nt = collections.namedtuple('TestNamedTuple', ['a', 'b']) class NotANamedTuple(tuple): pass self.assertTrue(inspect_utils.isnamedtuple(nt)) self.assertFalse(inspect_utils.isnamedtuple(NotANamedTuple)) def test_isnamedtuple_confounder(self): """This test highlights false positives when detecting named tuples.""" class NamedTupleLike(tuple): _fields = ('a', 'b') self.assertTrue(inspect_utils.isnamedtuple(NamedTupleLike)) def test_isnamedtuple_subclass(self): """This test highlights false positives when detecting named tuples.""" class NamedTupleSubclass(collections.namedtuple('Test', ['a', 'b'])): pass self.assertTrue(inspect_utils.isnamedtuple(NamedTupleSubclass)) def assertSourceIdentical(self, actual, expected): self.assertEqual( textwrap.dedent(actual).strip(), textwrap.dedent(expected).strip() ) def test_getimmediatesource_basic(self): def test_decorator(f): def f_wrapper(*args, **kwargs): return f(*args, **kwargs) return f_wrapper expected = """ def f_wrapper(*args, **kwargs): return f(*args, **kwargs) """ @test_decorator def test_fn(a): """Test docstring.""" return [a] self.assertSourceIdentical( inspect_utils.getimmediatesource(test_fn), expected) def test_getimmediatesource_noop_decorator(self): def test_decorator(f): return f expected = ''' @test_decorator def test_fn(a): """Test docstring.""" return [a] ''' @test_decorator def test_fn(a): """Test docstring.""" return [a] self.assertSourceIdentical( inspect_utils.getimmediatesource(test_fn), expected) def test_getimmediatesource_functools_wrapper(self): def wrapper_decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) return wrapper expected = textwrap.dedent(""" @functools.wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) """) @wrapper_decorator def test_fn(a): """Test docstring.""" return [a] self.assertSourceIdentical( inspect_utils.getimmediatesource(test_fn), expected) def test_getimmediatesource_functools_wrapper_different_module(self): expected = textwrap.dedent(""" @functools.wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) """) @decorators.wrapping_decorator def test_fn(a): """Test docstring.""" return [a] self.assertSourceIdentical( inspect_utils.getimmediatesource(test_fn), expected) def test_getimmediatesource_normal_decorator_different_module(self): expected = textwrap.dedent(""" def standalone_wrapper(*args, **kwargs): return f(*args, **kwargs) """) @decorators.standalone_decorator def test_fn(a): """Test docstring.""" return [a] self.assertSourceIdentical( inspect_utils.getimmediatesource(test_fn), expected) def test_getimmediatesource_normal_functional_decorator_different_module( self): expected = textwrap.dedent(""" def functional_wrapper(*args, **kwargs): return f(*args, **kwargs) """) @decorators.functional_decorator() def test_fn(a): """Test docstring.""" return [a] self.assertSourceIdentical( inspect_utils.getimmediatesource(test_fn), expected) def test_getnamespace_globals(self): ns = inspect_utils.getnamespace(factory) self.assertEqual(ns['free_function'], free_function) def test_getnamespace_hermetic(self): # Intentionally hiding the global function to make sure we don't overwrite # it in the global namespace. free_function = object() # pylint:disable=redefined-outer-name def test_fn(): return free_function ns = inspect_utils.getnamespace(test_fn) globs = six.get_function_globals(test_fn) self.assertTrue(ns['free_function'] is free_function) self.assertFalse(globs['free_function'] is free_function) def test_getnamespace_locals(self): def called_fn(): return 0 closed_over_list = [] closed_over_primitive = 1 def local_fn(): closed_over_list.append(1) local_var = 1 return called_fn() + local_var + closed_over_primitive ns = inspect_utils.getnamespace(local_fn) self.assertEqual(ns['called_fn'], called_fn) self.assertEqual(ns['closed_over_list'], closed_over_list) self.assertEqual(ns['closed_over_primitive'], closed_over_primitive) self.assertTrue('local_var' not in ns) def test_getqualifiedname(self): foo = object() qux = imp.new_module('quxmodule') bar = imp.new_module('barmodule') baz = object() bar.baz = baz ns = { 'foo': foo, 'bar': bar, 'qux': qux, } self.assertIsNone(inspect_utils.getqualifiedname(ns, inspect_utils)) self.assertEqual(inspect_utils.getqualifiedname(ns, foo), 'foo') self.assertEqual(inspect_utils.getqualifiedname(ns, bar), 'bar') self.assertEqual(inspect_utils.getqualifiedname(ns, baz), 'bar.baz') def test_getqualifiedname_efficiency(self): foo = object() # We create a densely connected graph consisting of a relatively small # number of modules and hide our symbol in one of them. The path to the # symbol is at least 10, and each node has about 10 neighbors. However, # by skipping visited modules, the search should take much less. ns = {} prev_level = [] for i in range(10): current_level = [] for j in range(10): mod_name = 'mod_{}_{}'.format(i, j) mod = imp.new_module(mod_name) current_level.append(mod) if i == 9 and j == 9: mod.foo = foo if prev_level: # All modules at level i refer to all modules at level i+1 for prev in prev_level: for mod in current_level: prev.__dict__[mod.__name__] = mod else: for mod in current_level: ns[mod.__name__] = mod prev_level = current_level self.assertIsNone(inspect_utils.getqualifiedname(ns, inspect_utils)) self.assertIsNotNone( inspect_utils.getqualifiedname(ns, foo, max_depth=10000000000)) def test_getqualifiedname_cycles(self): foo = object() # We create a graph of modules that contains circular references. The # search process should avoid them. The searched object is hidden at the # bottom of a path of length roughly 10. ns = {} mods = [] for i in range(10): mod = imp.new_module('mod_{}'.format(i)) if i == 9: mod.foo = foo # Module i refers to module i+1 if mods: mods[-1].__dict__[mod.__name__] = mod else: ns[mod.__name__] = mod # Module i refers to all modules j < i. for prev in mods: mod.__dict__[prev.__name__] = prev mods.append(mod) self.assertIsNone(inspect_utils.getqualifiedname(ns, inspect_utils)) self.assertIsNotNone( inspect_utils.getqualifiedname(ns, foo, max_depth=10000000000)) def test_getqualifiedname_finds_via_parent_module(self): # TODO(mdan): This test is vulnerable to change in the lib module. # A better way to forge modules should be found. self.assertEqual( inspect_utils.getqualifiedname( lib.__dict__, lib.io.file_io.FileIO, max_depth=1), 'io.file_io.FileIO') def test_getmethodclass(self): self.assertEqual( inspect_utils.getmethodclass(free_function), None) self.assertEqual( inspect_utils.getmethodclass(free_factory()), None) self.assertEqual( inspect_utils.getmethodclass(TestClass.member_function), TestClass) self.assertEqual( inspect_utils.getmethodclass(TestClass.decorated_member), TestClass) self.assertEqual( inspect_utils.getmethodclass(TestClass.fn_decorated_member), TestClass) self.assertEqual( inspect_utils.getmethodclass(TestClass.wrap_decorated_member), TestClass) self.assertEqual( inspect_utils.getmethodclass(TestClass.static_method), TestClass) self.assertEqual( inspect_utils.getmethodclass(TestClass.class_method), TestClass) test_obj = TestClass() self.assertEqual( inspect_utils.getmethodclass(test_obj.member_function), TestClass) self.assertEqual( inspect_utils.getmethodclass(test_obj.decorated_member), TestClass) self.assertEqual( inspect_utils.getmethodclass(test_obj.fn_decorated_member), TestClass) self.assertEqual( inspect_utils.getmethodclass(test_obj.wrap_decorated_member), TestClass) self.assertEqual( inspect_utils.getmethodclass(test_obj.static_method), TestClass) self.assertEqual( inspect_utils.getmethodclass(test_obj.class_method), TestClass) def test_getmethodclass_locals(self): def local_function(): pass class LocalClass(object): def member_function(self): pass @decorator def decorated_member(self): pass @function_decorator() def fn_decorated_member(self): pass @wrapping_decorator() def wrap_decorated_member(self): pass self.assertEqual( inspect_utils.getmethodclass(local_function), None) self.assertEqual( inspect_utils.getmethodclass(LocalClass.member_function), LocalClass) self.assertEqual( inspect_utils.getmethodclass(LocalClass.decorated_member), LocalClass) self.assertEqual( inspect_utils.getmethodclass(LocalClass.fn_decorated_member), LocalClass) self.assertEqual( inspect_utils.getmethodclass(LocalClass.wrap_decorated_member), LocalClass) test_obj = LocalClass() self.assertEqual( inspect_utils.getmethodclass(test_obj.member_function), LocalClass) self.assertEqual( inspect_utils.getmethodclass(test_obj.decorated_member), LocalClass) self.assertEqual( inspect_utils.getmethodclass(test_obj.fn_decorated_member), LocalClass) self.assertEqual( inspect_utils.getmethodclass(test_obj.wrap_decorated_member), LocalClass) def test_getmethodclass_callables(self): class TestCallable(object): def __call__(self): pass c = TestCallable() self.assertEqual(inspect_utils.getmethodclass(c), TestCallable) def test_getmethodclass_weakref_mechanism(self): test_obj = TestClass() def test_fn(self): return self bound_method = types.MethodType( test_fn, function.TfMethodTarget( weakref.ref(test_obj), test_obj.member_function)) self.assertEqual(inspect_utils.getmethodclass(bound_method), TestClass) def test_getmethodclass_no_bool_conversion(self): tensor = constant_op.constant([1]) self.assertEqual( inspect_utils.getmethodclass(tensor.get_shape), type(tensor)) def test_getdefiningclass(self): class Superclass(object): def foo(self): pass def bar(self): pass @classmethod def class_method(cls): pass class Subclass(Superclass): def foo(self): pass def baz(self): pass self.assertTrue( inspect_utils.getdefiningclass(Subclass.foo, Subclass) is Subclass) self.assertTrue( inspect_utils.getdefiningclass(Subclass.bar, Subclass) is Superclass) self.assertTrue( inspect_utils.getdefiningclass(Subclass.baz, Subclass) is Subclass) self.assertTrue( inspect_utils.getdefiningclass(Subclass.class_method, Subclass) is Superclass) def test_isbuiltin(self): self.assertTrue(inspect_utils.isbuiltin(enumerate)) self.assertTrue(inspect_utils.isbuiltin(eval)) self.assertTrue(inspect_utils.isbuiltin(float)) self.assertTrue(inspect_utils.isbuiltin(int)) self.assertTrue(inspect_utils.isbuiltin(len)) self.assertTrue(inspect_utils.isbuiltin(range)) self.assertTrue(inspect_utils.isbuiltin(zip)) self.assertFalse(inspect_utils.isbuiltin(function_decorator)) def test_getfutureimports_functions(self): self.assertEqual( inspect_utils.getfutureimports(basic_definitions.function_with_print), ('absolute_import', 'division', 'print_function', 'with_statement')) def test_getfutureimports_lambdas(self): self.assertEqual( inspect_utils.getfutureimports(basic_definitions.simple_lambda), ('absolute_import', 'division', 'print_function', 'with_statement')) def test_getfutureimports_methods(self): self.assertEqual( inspect_utils.getfutureimports( basic_definitions.SimpleClass.method_with_print), ('absolute_import', 'division', 'print_function', 'with_statement')) def test_super_wrapper_for_dynamic_attrs(self): a = object() b = object() class Base(object): def __init__(self): self.a = a class Subclass(Base): def __init__(self): super(Subclass, self).__init__() self.b = b base = Base() sub = Subclass() sub_super = super(Subclass, sub) sub_super_wrapped = inspect_utils.SuperWrapperForDynamicAttrs(sub_super) self.assertIs(base.a, a) self.assertIs(sub.a, a) self.assertFalse(hasattr(sub_super, 'a')) self.assertIs(sub_super_wrapped.a, a) # TODO(mdan): Is this side effect harmful? Can it be avoided? # Note that `b` was set in `Subclass.__init__`. self.assertIs(sub_super_wrapped.b, b) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/inspect_utils_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """AST manipulation utilities.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import ast import gast from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import parser from tensorflow.python.util import tf_inspect class CleanCopier(object): """NodeTransformer-like visitor that copies an AST.""" def __init__(self, preserve_annos): super(CleanCopier, self).__init__() self.preserve_annos = preserve_annos def copy(self, node): """Returns a deep copy of node (excluding some fields, see copy_clean).""" if isinstance(node, list): return [self.copy(n) for n in node] elif isinstance(node, tuple): return tuple(self.copy(n) for n in node) elif not isinstance(node, (gast.AST, ast.AST)): # Assuming everything that's not an AST, list or tuple is a value type # and may simply be assigned. return node assert isinstance(node, (gast.AST, ast.AST)) new_fields = {} for f in node._fields: if not f.startswith('__') and hasattr(node, f): new_fields[f] = self.copy(getattr(node, f)) new_node = type(node)(**new_fields) if self.preserve_annos: for k in self.preserve_annos: anno.copyanno(node, new_node, k) return new_node def copy_clean(node, preserve_annos=None): """Creates a deep copy of an AST. The copy will not include fields that are prefixed by '__', with the exception of user-specified annotations. Args: node: ast.AST preserve_annos: Optional[Set[Hashable]], annotation keys to include in the copy Returns: ast.AST """ return CleanCopier(preserve_annos).copy(node) class SymbolRenamer(gast.NodeTransformer): """Transformer that can rename symbols to a simple names.""" def __init__(self, name_map): self.name_map = name_map def _process(self, node): qn = anno.getanno(node, anno.Basic.QN) if qn in self.name_map: new_node = gast.Name(str(self.name_map[qn]), node.ctx, None) # All annotations get carried over. for k in anno.keys(node): anno.copyanno(node, new_node, k) return new_node return self.generic_visit(node) def visit_Name(self, node): return self._process(node) def visit_Attribute(self, node): if anno.hasanno(node, anno.Basic.QN): return self._process(node) # Attributes of dynamic objects will not have a QN. return self.generic_visit(node) def rename_symbols(node, name_map): """Renames symbols in an AST. Requires qual_names annotations.""" renamer = SymbolRenamer(name_map) if isinstance(node, list): return [renamer.visit(n) for n in node] elif isinstance(node, tuple): return tuple(renamer.visit(n) for n in node) return renamer.visit(node) def keywords_to_dict(keywords): """Converts a list of ast.keyword objects to a dict.""" keys = [] values = [] for kw in keywords: keys.append(gast.Str(kw.arg)) values.append(kw.value) return gast.Dict(keys=keys, values=values) class PatternMatcher(gast.NodeVisitor): """Matches a node against a pattern represented by a node.""" def __init__(self, pattern): self.pattern = pattern self.pattern_stack = [] self.matches = True def compare_and_visit(self, node, pattern): self.pattern_stack.append(self.pattern) self.pattern = pattern self.generic_visit(node) self.pattern = self.pattern_stack.pop() def no_match(self): self.matches = False return False def is_wildcard(self, p): if isinstance(p, (list, tuple)) and len(p) == 1: p, = p if isinstance(p, gast.Name) and p.id == '_': return True if p == '_': return True return False def generic_visit(self, node): if not self.matches: return pattern = self.pattern for f in node._fields: if f.startswith('__'): continue if not hasattr(node, f): if hasattr(pattern, f) and getattr(pattern, f): return self.no_match() else: continue if not hasattr(pattern, f): return self.no_match() v = getattr(node, f) p = getattr(pattern, f) if self.is_wildcard(p): continue if isinstance(v, (list, tuple)): if not isinstance(p, (list, tuple)) or len(v) != len(p): return self.no_match() for v_item, p_item in zip(v, p): self.compare_and_visit(v_item, p_item) elif isinstance(v, (gast.AST, ast.AST)): if not isinstance(v, type(p)) and not isinstance(p, type(v)): return self.no_match() self.compare_and_visit(v, p) else: # Assume everything else is a value type. if v != p: return self.no_match() def matches(node, pattern): """Basic pattern matcher for AST. The pattern may contain wildcards represented by the symbol '_'. A node matches a pattern if for every node in the tree, either there is a node of the same type in pattern, or a Name node with id='_'. Args: node: ast.AST pattern: ast.AST Returns: bool """ if isinstance(pattern, str): pattern = parser.parse_str(pattern) matcher = PatternMatcher(pattern) matcher.visit(node) return matcher.matches # TODO(mdan): Once we have error tracing, we may be able to just go to SSA. def apply_to_single_assignments(targets, values, apply_fn): """Applies a function to each individual assignment. This function can process a possibly-unpacked (e.g. a, b = c, d) assignment. It tries to break down the unpacking if possible. In effect, it has the same effect as passing the assigned values in SSA form to apply_fn. Examples: The following will result in apply_fn(a, c), apply_fn(b, d): a, b = c, d The following will result in apply_fn(a, c[0]), apply_fn(b, c[1]): a, b = c The following will result in apply_fn(a, (b, c)): a = b, c It uses the visitor pattern to allow subclasses to process single assignments individually. Args: targets: Union[List[ast.AST, ...], Tuple[ast.AST, ...], ast.AST, should be used with the targets field of an ast.Assign node values: ast.AST apply_fn: Callable[[ast.AST, ast.AST], None], called with the respective nodes of each single assignment """ if not isinstance(targets, (list, tuple)): targets = (targets,) for target in targets: if isinstance(target, (gast.Tuple, gast.List)): for i in range(len(target.elts)): target_el = target.elts[i] if isinstance(values, (gast.Tuple, gast.List)): value_el = values.elts[i] else: idx = parser.parse_expression(str(i)) value_el = gast.Subscript(values, gast.Index(idx), ctx=gast.Load()) apply_to_single_assignments(target_el, value_el, apply_fn) else: apply_fn(target, values) def parallel_walk(node, other): """Walks two ASTs in parallel. The two trees must have identical structure. Args: node: Union[ast.AST, Iterable[ast.AST]] other: Union[ast.AST, Iterable[ast.AST]] Yields: Tuple[ast.AST, ast.AST] Raises: ValueError: if the two trees don't have identical structure. """ if isinstance(node, (list, tuple)): node_stack = list(node) else: node_stack = [node] if isinstance(other, (list, tuple)): other_stack = list(other) else: other_stack = [other] while node_stack and other_stack: assert len(node_stack) == len(other_stack) n = node_stack.pop() o = other_stack.pop() if ((not isinstance(n, (ast.AST, gast.AST, str)) and n is not None) or (not isinstance(o, (ast.AST, gast.AST, str)) and n is not None) or n.__class__.__name__ != o.__class__.__name__): raise ValueError('inconsistent nodes: {} ({}) and {} ({})'.format( n, n.__class__.__name__, o, o.__class__.__name__)) yield n, o if isinstance(n, str): assert isinstance(o, str), 'The check above should have ensured this' continue if n is None: assert o is None, 'The check above should have ensured this' continue for f in n._fields: n_child = getattr(n, f, None) o_child = getattr(o, f, None) if f.startswith('__') or n_child is None or o_child is None: continue if isinstance(n_child, (list, tuple)): if (not isinstance(o_child, (list, tuple)) or len(n_child) != len(o_child)): raise ValueError( 'inconsistent values for field {}: {} and {}'.format( f, n_child, o_child)) node_stack.extend(n_child) other_stack.extend(o_child) elif isinstance(n_child, (gast.AST, ast.AST)): node_stack.append(n_child) other_stack.append(o_child) elif n_child != o_child: raise ValueError( 'inconsistent values for field {}: {} and {}'.format( f, n_child, o_child)) class LambdaDefinitionMatcher(gast.NodeVisitor): """Finds lambda nodes that match a given lambda's signature.""" def __init__(self, fn): self.fn = fn self.matching_nodes = [] def _arg_name(self, node): if node is None: return None if isinstance(node, gast.Name): return node.id assert isinstance(node, str) return node def _argspec_matches(self, node): arg_spec = tf_inspect.getfullargspec(self.fn) node_args = tuple(self._arg_name(arg) for arg in node.args.args) if node_args != tuple(arg_spec.args): return False if arg_spec.varargs != self._arg_name(node.args.vararg): return False if arg_spec.varkw != self._arg_name(node.args.kwarg): return False node_kwonlyargs = tuple(self._arg_name(arg) for arg in node.args.kwonlyargs) if node_kwonlyargs != tuple(arg_spec.kwonlyargs): return False return True def visit_Lambda(self, node): self.generic_visit(node) if self.fn.__name__ != '<lambda>': return if not self._argspec_matches(node): return self.matching_nodes.append(node) def find_matching_definitions(node, f): matcher = LambdaDefinitionMatcher(f) matcher.visit(node) return tuple(matcher.matching_nodes)
tensorflow-master
tensorflow/python/autograph/pyct/ast_util.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for pretty_printer module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import ast import textwrap from tensorflow.python.autograph.pyct import pretty_printer from tensorflow.python.platform import test class PrettyPrinterTest(test.TestCase): def test_unicode_bytes(self): source = textwrap.dedent(''' def f(): return b'b', u'u', 'depends_py2_py3' ''') node = ast.parse(source) self.assertIsNotNone(pretty_printer.fmt(node)) def test_format(self): node = ast.FunctionDef( name='f', args=ast.arguments( args=[ast.Name(id='a', ctx=ast.Param())], vararg=None, kwarg=None, defaults=[]), body=[ ast.Return( ast.BinOp( op=ast.Add(), left=ast.Name(id='a', ctx=ast.Load()), right=ast.Num(1))) ], decorator_list=[], returns=None) # Just checking for functionality, the color control characters make it # difficult to inspect the result. self.assertIsNotNone(pretty_printer.fmt(node)) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/pretty_printer_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Converting code to AST. Adapted from Tangent. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import textwrap import gast from tensorflow.python.autograph.pyct import inspect_utils from tensorflow.python.util import tf_inspect STANDARD_PREAMBLE = textwrap.dedent(""" from __future__ import division from __future__ import print_function """) STANDARD_PREAMBLE_LEN = 2 def parse_entity(entity, future_features): """Returns the AST and source code of given entity. Args: entity: Any, Python function/method/class future_features: Iterable[Text], future features to use (e.g. 'print_statement'). See https://docs.python.org/2/reference/simple_stmts.html#future Returns: gast.AST, Text: the parsed AST node; the source code that was parsed to generate the AST (including any prefixes that this function may have added). """ try: source = inspect_utils.getimmediatesource(entity) except (IOError, OSError) as e: raise ValueError( 'Unable to locate the source code of {}. Note that functions defined' ' in certain environments, like the interactive Python shell do not' ' expose their source code. If that is the case, you should to define' ' them in a .py source file. If you are certain the code is' ' graph-compatible, wrap the call using' ' @tf.autograph.do_not_convert. Original error: {}'.format(entity, e)) def raise_parse_failure(comment): raise ValueError( 'Failed to parse source code of {}, which Python reported as:\n{}\n' '{}'.format(entity, source, comment)) # Comments and multiline strings can appear at arbitrary indentation levels, # causing textwrap.dedent to not correctly dedent source code. # TODO(b/115884650): Automatic handling of comments/multiline strings. source = textwrap.dedent(source) future_statements = tuple( 'from __future__ import {}'.format(name) for name in future_features) source = '\n'.join(future_statements + (source,)) try: return parse_str(source, preamble_len=len(future_features)), source except IndentationError: # The text below lists the causes of this error known to us. There may # be more. raise_parse_failure( 'This may be caused by multiline strings or comments not indented at' ' the same level as the code.') except SyntaxError as e: if not tf_inspect.isfunction(entity) or entity.__name__ != '<lambda>': raise # Certain entities, like lambdas, only hold the raw code lines which defined # them, which may include surrounding tokens and may be syntactically # invalid out of context. For example: # # l = ( # lambda x: x,)[0] # # will have the dedented source "lambda x: x,)[0]" # Here we make an attempt to stip away the garbage by looking at the # information in the syntax error. lines = source.split('\n') lineno, offset = e.lineno, e.offset # 1-based # Give up if there's nothing we can chip away. if len(lines) == lineno and len(lines[-1]) == offset: raise_parse_failure( 'If this is a lambda function, the error may be avoided by creating' ' the lambda in a standalone statement.') # Drop all lines following the error location # TODO(mdan): What's with the pylint errors? lines = lines[:lineno] # pylint:disable=invalid-slice-index # Drop all characters following the error location lines[-1] = lines[-1][:offset - 1] # pylint:disable=invalid-slice-index source = '\n'.join(lines) try: return parse_str(source, preamble_len=len(future_features)), source except SyntaxError as e: raise_parse_failure( 'If this is a lambda function, the error may be avoided by creating' ' the lambda in a standalone statement. Tried to strip down the' ' source to:\n{}\nBut that did not work.'.format(source)) # TODO(mdan): This should take futures as input instead. def parse_str(src, preamble_len=0, single_node=True): """Returns the AST of given piece of code. Args: src: Text preamble_len: Int, indicates leading nodes in the parsed AST which should be dropped. single_node: Bool, whether `src` is assumed to be represented by exactly one AST node. Returns: ast.AST """ module_node = gast.parse(src) nodes = module_node.body if preamble_len: nodes = nodes[preamble_len:] if single_node: if len(nodes) != 1: raise ValueError('expected exactly one node node, found {}'.format(nodes)) return nodes[0] return nodes def parse_expression(src): """Returns the AST of given identifier. Args: src: A piece of code that represents a single Python expression Returns: A gast.AST object. Raises: ValueError: if src does not consist of a single Expression. """ src = STANDARD_PREAMBLE + src.strip() node = parse_str(src, preamble_len=STANDARD_PREAMBLE_LEN, single_node=True) if __debug__: if not isinstance(node, gast.Expr): raise ValueError( 'expected a single expression, found instead {}'.format(node)) return node.value
tensorflow-master
tensorflow/python/autograph/pyct/parser.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """AST conversion templates. Adapted from Tangent. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import ast import textwrap import gast from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import ast_util from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import qual_names class ContextAdjuster(gast.NodeTransformer): """Adjusts the ctx field of nodes to ensure consistency. This transformer can change the ctx fields of a variable, tuple and other AST elements that allow one, based on whether the element is being read or written. """ def __init__(self, override_value): self._ctx_override = override_value def visit(self, node): original_override = self._ctx_override node = super(ContextAdjuster, self).visit(node) if hasattr(node, 'ctx'): assert node.ctx is not None, 'node {} has ctx unset'.format(node) self._ctx_override = original_override return node def _apply_override(self, node): if self._ctx_override is not None: node.ctx = self._ctx_override() def visit_Attribute(self, node): self._apply_override(node) self._ctx_override = gast.Load node = self.generic_visit(node) return node def visit_Tuple(self, node): self._apply_override(node) return self.generic_visit(node) def visit_List(self, node): self._apply_override(node) return self.generic_visit(node) def visit_Name(self, node): self._apply_override(node) return self.generic_visit(node) def visit_Call(self, node): self._apply_override(node) # We may be able to override these to Load(), but for now it's simpler # to just assert that they're set. self._ctx_override = None return self.generic_visit(node) def visit_Dict(self, node): # We may be able to override these to Load(), but for now it's simpler # to just assert that they're set. self._ctx_override = None return self.generic_visit(node) def visit_Subscript(self, node): self._apply_override(node) self._ctx_override = gast.Load node.value = self.visit(node.value) return self.generic_visit(node) def visit_comprehension(self, node): # We may be able to override some of these, but for now it's simpler # to just assert that they're set. self._ctx_override = None return self.generic_visit(node) def visit_Lambda(self, node): # We may be able to override some of these, but for now it's simpler # to just assert that they're set. self._ctx_override = None return self.generic_visit(node) class ReplaceTransformer(gast.NodeTransformer): """Replace AST nodes.""" def __init__(self, replacements): """Create a new ReplaceTransformer. Args: replacements: A mapping from placeholder names to (lists of) AST nodes that these placeholders will be replaced by. """ self.replacements = replacements self.in_replacements = False self.preserved_annos = { anno.Basic.ORIGIN, anno.Basic.SKIP_PROCESSING, anno.Static.ORIG_DEFINITIONS, 'extra_test', } def _prepare_replacement(self, replaced, key): """Prepares a replacement AST that's safe to swap in for a node. Args: replaced: ast.AST, the node being replaced key: Hashable, the key of the replacement AST Returns: ast.AST, the replacement AST """ repl = self.replacements[key] new_nodes = ast_util.copy_clean(repl, preserve_annos=self.preserved_annos) if isinstance(new_nodes, gast.AST): new_nodes = [new_nodes] return new_nodes def visit_Expr(self, node): # When replacing a placeholder with an entire statement, the replacement # must stand on its own and not be wrapped in an Expr. new_value = self.visit(node.value) if new_value is node.value: return node return new_value def visit_keyword(self, node): if node.arg not in self.replacements: return self.generic_visit(node) repl = self._prepare_replacement(node, node.arg) if isinstance(repl, gast.keyword): return repl elif (repl and isinstance(repl, (list, tuple)) and all(isinstance(r, gast.keyword) for r in repl)): return repl # TODO(mdan): We may allow replacing with a string as well. # For example, if one wanted to replace foo with bar in foo=baz, then # we could allow changing just node arg, so that we end up with bar=baz. raise ValueError( 'a keyword argument may only be replaced by another keyword or a ' 'non-empty list of keywords. Found: {} for keyword {}'.format( repl, node.arg)) def visit_FunctionDef(self, node): node = self.generic_visit(node) if node.name not in self.replacements: return node repl = self.replacements[node.name] if not isinstance(repl, (gast.Name, ast.Name)): raise ValueError( 'a function name can only be replaced by a Name node. Found: %s' % repl) node.name = repl.id return node def visit_Attribute(self, node): node = self.generic_visit(node) if node.attr not in self.replacements: return node repl = self.replacements[node.attr] if not isinstance(repl, gast.Name): raise ValueError( 'An attribute can only be replaced by a Name node. Found: %s' % repl) node.attr = repl.id return node def visit_Name(self, node): if node.id not in self.replacements: return node new_nodes = self._prepare_replacement(node, node.id) if not new_nodes: return new_nodes # Preserve the target context. adjuster = ContextAdjuster(type(node.ctx)) for n in new_nodes: if hasattr(n, 'ctx'): adjuster.visit(n) if len(new_nodes) == 1: new_nodes, = new_nodes return new_nodes def _convert_to_ast(n): """Converts from a known data type to AST.""" # Note: When generating AST nodes from strings/QNs in isolation, ctx is # unknown. ctx must be filled in according to the template being used. # See ReplaceTransformer.visit_Name. if isinstance(n, str): return gast.Name(id=n, ctx=None, annotation=None) if isinstance(n, qual_names.QN): return n.ast() if isinstance(n, list): return [_convert_to_ast(e) for e in n] if isinstance(n, tuple): return tuple(_convert_to_ast(e) for e in n) return n def replace(template, **replacements): """Replaces placeholders in a Python template. AST Name and Tuple nodes always receive the context that inferred from the template. However, when replacing more complex nodes (that can potentially contain Name children), then the caller is responsible for setting the appropriate context. Args: template: A string representing Python code. Any symbol name can be used that appears in the template code can be used as placeholder. **replacements: A mapping from placeholder names to (lists of) AST nodes that these placeholders will be replaced by. String values are also supported as a shorthand for AST Name nodes with the respective ID. Returns: An AST node or list of AST nodes with the replacements made. If the template was a function, a list will be returned. If the template was a node, the same node will be returned. If the template was a string, an AST node will be returned (a `Module` node in the case of a multi-line string, an `Expr` node otherwise). Raises: ValueError: if the arguments are incorrect. """ if not isinstance(template, str): raise ValueError('Expected string template, got %s' % type(template)) for k in replacements: replacements[k] = _convert_to_ast(replacements[k]) template_str = parser.STANDARD_PREAMBLE + textwrap.dedent(template) nodes = parser.parse_str( template_str, preamble_len=parser.STANDARD_PREAMBLE_LEN, single_node=False) results = [] for node in nodes: node = ReplaceTransformer(replacements).visit(node) if isinstance(node, (list, tuple)): results.extend(node) else: results.append(node) results = [qual_names.resolve(r) for r in results] return results def replace_as_expression(template, **replacements): """Variant of replace that generates expressions, instead of code blocks.""" replacement = replace(template, **replacements) if len(replacement) != 1: raise ValueError( 'single expression expected; for more general templates use replace') node, = replacement if isinstance(node, gast.Expr): return node.value elif isinstance(node, gast.Name): return node raise ValueError( 'the template is expected to generate an expression or a name node;' ' instead found %s' % node)
tensorflow-master
tensorflow/python/autograph/pyct/templates.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Print an AST tree in a form more readable than ast.dump.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast import six import termcolor class PrettyPrinter(gast.NodeVisitor): """Print AST nodes.""" def __init__(self, color, noanno): self.indent_lvl = 0 self.result = '' self.color = color self.noanno = noanno def _color(self, string, color, attrs=None): if self.color: return termcolor.colored(string, color, attrs=attrs) return string def _type(self, node): return self._color(node.__class__.__name__, None, ['bold']) def _field(self, name): return self._color(name, 'blue') def _value(self, name): return self._color(name, 'magenta') def _warning(self, name): return self._color(name, 'red') def _indent(self): return self._color('| ' * self.indent_lvl, None, ['dark']) def _print(self, s): self.result += s self.result += '\n' def generic_visit(self, node, name=None): # In very rare instances, a list can contain something other than a Node. # e.g. Global contains a list of strings. if isinstance(node, str): if name: self._print('%s%s="%s"' % (self._indent(), name, node)) else: self._print('%s"%s"' % (self._indent(), node)) return if node._fields: cont = ':' else: cont = '()' if name: self._print('%s%s=%s%s' % (self._indent(), self._field(name), self._type(node), cont)) else: self._print('%s%s%s' % (self._indent(), self._type(node), cont)) self.indent_lvl += 1 for f in node._fields: if self.noanno and f.startswith('__'): continue if not hasattr(node, f): self._print('%s%s' % (self._indent(), self._warning('%s=<unset>' % f))) continue v = getattr(node, f) if isinstance(v, list): if v: self._print('%s%s=[' % (self._indent(), self._field(f))) self.indent_lvl += 1 for n in v: if n is not None: self.generic_visit(n) else: self._print('%sNone' % (self._indent())) self.indent_lvl -= 1 self._print('%s]' % (self._indent())) else: self._print('%s%s=[]' % (self._indent(), self._field(f))) elif isinstance(v, tuple): if v: self._print('%s%s=(' % (self._indent(), self._field(f))) self.indent_lvl += 1 for n in v: if n is not None: self.generic_visit(n) else: self._print('%sNone' % (self._indent())) self.indent_lvl -= 1 self._print('%s)' % (self._indent())) else: self._print('%s%s=()' % (self._indent(), self._field(f))) elif isinstance(v, gast.AST): self.generic_visit(v, f) elif isinstance(v, six.binary_type): self._print('%s%s=%s' % (self._indent(), self._field(f), self._value('b"%s"' % v))) elif isinstance(v, six.text_type): self._print('%s%s=%s' % (self._indent(), self._field(f), self._value('u"%s"' % v))) else: self._print('%s%s=%s' % (self._indent(), self._field(f), self._value(v))) self.indent_lvl -= 1 def fmt(node, color=True, noanno=False): printer = PrettyPrinter(color, noanno) if isinstance(node, (list, tuple)): for n in node: printer.visit(n) else: printer.visit(node) return printer.result
tensorflow-master
tensorflow/python/autograph/pyct/pretty_printer.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for ast_util module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import ast import collections import textwrap import gast from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import ast_util from tensorflow.python.autograph.pyct import compiler from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import qual_names from tensorflow.python.platform import test class AstUtilTest(test.TestCase): def setUp(self): super(AstUtilTest, self).setUp() self._invocation_counts = collections.defaultdict(lambda: 0) def test_rename_symbols_basic(self): node = parser.parse_str('a + b') node = qual_names.resolve(node) node = ast_util.rename_symbols( node, {qual_names.QN('a'): qual_names.QN('renamed_a')}) self.assertIsInstance(node.value.left.id, str) source = compiler.ast_to_source(node) self.assertEqual(source.strip(), 'renamed_a + b') def test_rename_symbols_attributes(self): node = parser.parse_str('b.c = b.c.d') node = qual_names.resolve(node) node = ast_util.rename_symbols( node, {qual_names.from_str('b.c'): qual_names.QN('renamed_b_c')}) source = compiler.ast_to_source(node) self.assertEqual(source.strip(), 'renamed_b_c = renamed_b_c.d') def test_rename_symbols_annotations(self): node = parser.parse_str('a[i]') node = qual_names.resolve(node) anno.setanno(node, 'foo', 'bar') orig_anno = anno.getanno(node, 'foo') node = ast_util.rename_symbols(node, {qual_names.QN('a'): qual_names.QN('b')}) self.assertIs(anno.getanno(node, 'foo'), orig_anno) def test_copy_clean(self): node = parser.parse_str( textwrap.dedent(""" def f(a): return a + 1 """)) setattr(node, '__foo', 'bar') new_node = ast_util.copy_clean(node) self.assertIsNot(new_node, node) self.assertFalse(hasattr(new_node, '__foo')) def test_copy_clean_preserves_annotations(self): node = parser.parse_str( textwrap.dedent(""" def f(a): return a + 1 """)) anno.setanno(node, 'foo', 'bar') anno.setanno(node, 'baz', 1) new_node = ast_util.copy_clean(node, preserve_annos={'foo'}) self.assertEqual(anno.getanno(new_node, 'foo'), 'bar') self.assertFalse(anno.hasanno(new_node, 'baz')) def test_keywords_to_dict(self): keywords = parser.parse_expression('f(a=b, c=1, d=\'e\')').keywords d = ast_util.keywords_to_dict(keywords) # Make sure we generate a usable dict node by attaching it to a variable and # compiling everything. node = parser.parse_str('def f(b): pass') node.body.append(ast.Return(d)) result, _, _ = compiler.ast_to_object(node) self.assertDictEqual(result.f(3), {'a': 3, 'c': 1, 'd': 'e'}) def assertMatch(self, target_str, pattern_str): node = parser.parse_expression(target_str) pattern = parser.parse_expression(pattern_str) self.assertTrue(ast_util.matches(node, pattern)) def assertNoMatch(self, target_str, pattern_str): node = parser.parse_expression(target_str) pattern = parser.parse_expression(pattern_str) self.assertFalse(ast_util.matches(node, pattern)) def test_matches_symbols(self): self.assertMatch('foo', '_') self.assertNoMatch('foo()', '_') self.assertMatch('foo + bar', 'foo + _') self.assertNoMatch('bar + bar', 'foo + _') self.assertNoMatch('foo - bar', 'foo + _') def test_matches_function_args(self): self.assertMatch('super(Foo, self).__init__(arg1, arg2)', 'super(_).__init__(_)') self.assertMatch('super().__init__()', 'super(_).__init__(_)') self.assertNoMatch('super(Foo, self).bar(arg1, arg2)', 'super(_).__init__(_)') self.assertMatch('super(Foo, self).__init__()', 'super(Foo, _).__init__(_)') self.assertNoMatch('super(Foo, self).__init__()', 'super(Bar, _).__init__(_)') def _mock_apply_fn(self, target, source): target = compiler.ast_to_source(target) source = compiler.ast_to_source(source) self._invocation_counts[(target.strip(), source.strip())] += 1 def test_apply_to_single_assignments_dynamic_unpack(self): node = parser.parse_str('a, b, c = d') ast_util.apply_to_single_assignments(node.targets, node.value, self._mock_apply_fn) self.assertDictEqual(self._invocation_counts, { ('a', 'd[0]'): 1, ('b', 'd[1]'): 1, ('c', 'd[2]'): 1, }) def test_apply_to_single_assignments_static_unpack(self): node = parser.parse_str('a, b, c = d, e, f') ast_util.apply_to_single_assignments(node.targets, node.value, self._mock_apply_fn) self.assertDictEqual(self._invocation_counts, { ('a', 'd'): 1, ('b', 'e'): 1, ('c', 'f'): 1, }) def test_parallel_walk(self): src = """ def f(a): return a + 1 """ node = parser.parse_str(textwrap.dedent(src)) for child_a, child_b in ast_util.parallel_walk(node, node): self.assertEqual(child_a, child_b) def test_parallel_walk_string_leaves(self): src = """ def f(a): global g """ node = parser.parse_str(textwrap.dedent(src)) for child_a, child_b in ast_util.parallel_walk(node, node): self.assertEqual(child_a, child_b) def test_parallel_walk_inconsistent_trees(self): node_1 = parser.parse_str( textwrap.dedent(""" def f(a): return a + 1 """)) node_2 = parser.parse_str( textwrap.dedent(""" def f(a): return a + (a * 2) """)) node_3 = parser.parse_str( textwrap.dedent(""" def f(a): return a + 2 """)) with self.assertRaises(ValueError): for _ in ast_util.parallel_walk(node_1, node_2): pass # There is not particular reason to reject trees that differ only in the # value of a constant. # TODO(mdan): This should probably be allowed. with self.assertRaises(ValueError): for _ in ast_util.parallel_walk(node_1, node_3): pass def assertLambdaNodes(self, matching_nodes, expected_bodies): self.assertEqual(len(matching_nodes), len(expected_bodies)) for node in matching_nodes: self.assertIsInstance(node, gast.Lambda) self.assertIn(compiler.ast_to_source(node.body).strip(), expected_bodies) def test_find_matching_definitions_lambda(self): node = parser.parse_str( textwrap.dedent(""" f = lambda x: 1 """)) f = lambda x: x nodes = ast_util.find_matching_definitions(node, f) self.assertLambdaNodes(nodes, ('(1)',)) def test_find_matching_definitions_lambda_multiple_matches(self): node = parser.parse_str( textwrap.dedent(""" f = lambda x: 1, lambda x: 2 """)) f = lambda x: x nodes = ast_util.find_matching_definitions(node, f) self.assertLambdaNodes(nodes, ('(1)', '(2)')) def test_find_matching_definitions_lambda_uses_arg_names(self): node = parser.parse_str( textwrap.dedent(""" f = lambda x: 1, lambda y: 2 """)) f = lambda x: x nodes = ast_util.find_matching_definitions(node, f) self.assertLambdaNodes(nodes, ('(1)',)) f = lambda y: y nodes = ast_util.find_matching_definitions(node, f) self.assertLambdaNodes(nodes, ('(2)',)) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/ast_util_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for origin_info module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import textwrap from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import inspect_utils from tensorflow.python.autograph.pyct import origin_info from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct.testing import basic_definitions from tensorflow.python.platform import test from tensorflow.python.util import tf_inspect class OriginInfoTest(test.TestCase): def test_create_source_map(self): source = """ def test_fn(x): return x + 1 """ source = textwrap.dedent(source) node = parser.parse_str(source) fake_origin = origin_info.OriginInfo( loc=origin_info.Location('fake_filename', 3, 7), function_name='fake_function_name', source_code_line='fake source line', comment=None) anno.setanno(node, anno.Basic.ORIGIN, fake_origin) source_map = origin_info.create_source_map(node, source, 'test_filename') loc = origin_info.LineLocation('test_filename', 2) self.assertIn(loc, source_map) self.assertIs(source_map[loc], fake_origin) def _create_source_map(self, test_fn): node, source = parser.parse_entity(test_fn, ()) origin_info.resolve_entity(node, source, test_fn) # Creating a source map with the source code as output will create # an identity map. return origin_info.create_source_map(node, source, 'test_filename') def test_create_source_map_identity(self): test_fn = basic_definitions.simple_function source_map = self._create_source_map(test_fn) module_path = tf_inspect.getsourcefile(test_fn) # Origin line numbers below should match those in basic_definitions.py definition_loc = origin_info.LineLocation('test_filename', 1) self.assertIn(definition_loc, source_map) self.assertEqual(source_map[definition_loc].loc.lineno, 23) self.assertEqual(source_map[definition_loc].loc.filename, module_path) self.assertEqual(source_map[definition_loc].function_name, 'simple_function') def test_create_source_map_multiline_call(self): test_fn = basic_definitions.function_with_multiline_call source_map = self._create_source_map(test_fn) module_path = tf_inspect.getsourcefile(test_fn) # Origin line numbers below should match those in basic_definitions.py call_loc = origin_info.LineLocation('test_filename', 3) self.assertIn(call_loc, source_map) self.assertEqual(source_map[call_loc].loc.lineno, 55) self.assertEqual(source_map[call_loc].loc.filename, module_path) self.assertEqual(source_map[call_loc].function_name, 'function_with_multiline_call') self.assertEqual(source_map[call_loc].source_code_line, ' return range(') second_arg_loc = origin_info.LineLocation('test_filename', 5) self.assertIn(second_arg_loc, source_map) self.assertEqual(source_map[second_arg_loc].loc.lineno, 57) self.assertEqual(source_map[second_arg_loc].loc.filename, module_path) self.assertEqual(source_map[second_arg_loc].function_name, 'function_with_multiline_call') self.assertEqual(source_map[second_arg_loc].source_code_line, ' x + 1,') def test_create_source_map_no_origin_info(self): test_fn = basic_definitions.simple_function node, _ = parser.parse_entity(test_fn, inspect_utils.getfutureimports(test_fn)) # No origin information should result in an empty map. test_fn_lines, _ = tf_inspect.getsourcelines(test_fn) source_map = origin_info.create_source_map(node, '\n'.join(test_fn_lines), test_fn) self.assertEmpty(source_map) def test_resolve(self): source = """ def test_fn(x): '''Docstring.''' return x # comment """ source = textwrap.dedent(source) node = parser.parse_str(source) origin_info.resolve(node, source, 'test_file', 10, 10) def_origin = anno.getanno(node, anno.Basic.ORIGIN) self.assertEqual(def_origin.loc.filename, 'test_file') self.assertEqual(def_origin.loc.lineno, 10) self.assertEqual(def_origin.loc.col_offset, 10) self.assertEqual(def_origin.source_code_line, 'def test_fn(x):') self.assertIsNone(def_origin.comment) docstring_origin = anno.getanno(node.body[0], anno.Basic.ORIGIN) self.assertEqual(def_origin.loc.filename, 'test_file') self.assertEqual(docstring_origin.loc.lineno, 11) self.assertEqual(docstring_origin.loc.col_offset, 12) self.assertEqual(docstring_origin.source_code_line, " '''Docstring.'''") self.assertIsNone(docstring_origin.comment) ret_origin = anno.getanno(node.body[1], anno.Basic.ORIGIN) self.assertEqual(def_origin.loc.filename, 'test_file') self.assertEqual(ret_origin.loc.lineno, 12) self.assertEqual(ret_origin.loc.col_offset, 12) self.assertEqual(ret_origin.source_code_line, ' return x # comment') self.assertEqual(ret_origin.comment, 'comment') def test_resolve_entity(self): test_fn = basic_definitions.simple_function node, source = parser.parse_entity( test_fn, inspect_utils.getfutureimports(test_fn)) origin_info.resolve_entity(node, source, test_fn) # The line numbers below should match those in basic_definitions.py def_origin = anno.getanno(node, anno.Basic.ORIGIN) self.assertEqual(def_origin.loc.lineno, 23) self.assertEqual(def_origin.loc.col_offset, 0) self.assertEqual(def_origin.source_code_line, 'def simple_function(x):') self.assertIsNone(def_origin.comment) docstring_origin = anno.getanno(node.body[0], anno.Basic.ORIGIN) self.assertEqual(docstring_origin.loc.lineno, 24) self.assertEqual(docstring_origin.loc.col_offset, 2) self.assertEqual(docstring_origin.source_code_line, ' """Docstring."""') self.assertIsNone(docstring_origin.comment) ret_origin = anno.getanno(node.body[1], anno.Basic.ORIGIN) self.assertEqual(ret_origin.loc.lineno, 25) self.assertEqual(ret_origin.loc.col_offset, 2) self.assertEqual(ret_origin.source_code_line, ' return x # comment') self.assertEqual(ret_origin.comment, 'comment') def test_resolve_entity_nested_function(self): test_fn = basic_definitions.nested_functions node, source = parser.parse_entity( test_fn, inspect_utils.getfutureimports(test_fn)) origin_info.resolve_entity(node, source, test_fn) # The line numbers below should match those in basic_definitions.py inner_def_origin = anno.getanno(node.body[1], anno.Basic.ORIGIN) self.assertEqual(inner_def_origin.loc.lineno, 31) self.assertEqual(inner_def_origin.loc.col_offset, 2) self.assertEqual(inner_def_origin.source_code_line, ' def inner_fn(y):') self.assertIsNone(inner_def_origin.comment) inner_ret_origin = anno.getanno(node.body[1].body[0], anno.Basic.ORIGIN) self.assertEqual(inner_ret_origin.loc.lineno, 32) self.assertEqual(inner_ret_origin.loc.col_offset, 4) self.assertEqual(inner_ret_origin.source_code_line, ' return y') self.assertIsNone(inner_ret_origin.comment) def test_resolve_entity_indented_block(self): test_fn = basic_definitions.SimpleClass.simple_method node, source = parser.parse_entity( test_fn, inspect_utils.getfutureimports(test_fn)) origin_info.resolve_entity(node, source, test_fn) # The line numbers below should match those in basic_definitions.py def_origin = anno.getanno(node, anno.Basic.ORIGIN) self.assertEqual(def_origin.loc.lineno, 46) self.assertEqual(def_origin.loc.col_offset, 2) self.assertEqual(def_origin.source_code_line, 'def simple_method(self):') self.assertIsNone(def_origin.comment) ret_origin = anno.getanno(node.body[0], anno.Basic.ORIGIN) self.assertEqual(ret_origin.loc.lineno, 47) self.assertEqual(ret_origin.loc.col_offset, 4) self.assertEqual(ret_origin.source_code_line, ' return self') self.assertIsNone(ret_origin.comment) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/origin_info_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """A node transformer that includes utilities for SCT.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import gast from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import compiler from tensorflow.python.autograph.pyct import pretty_printer from tensorflow.python.autograph.pyct import templates # TODO(znado): Use namedtuple. class Context(object): """Contains information about a source code transformation. This object is mutable, and is updated during conversion. Not thread safe. Attributes: info: EntityInfo, immutable. current_origin: origin_info.OriginInfo, holds the OriginInfo of the last AST node to be processed successfully. Useful for error handling. """ def __init__(self, info): self.info = info self.current_origin = None # TODO(mdan): Move to a standalone file. class EntityInfo( collections.namedtuple( 'EntityInfo', ('source_code', 'source_file', 'future_features', 'namespace'))): """Contains information about a Python entity. Immutable. Examples of entities include functions and classes. Attributes: source_code: The entity's source code. source_file: The entity's source file. future_features: Tuple[Text], the future features that this entity was compiled with. See https://docs.python.org/2/reference/simple_stmts.html#future. namespace: Dict[str, ], containing symbols visible to the entity (excluding parameters). """ pass class _StateStack(object): """Typed stack abstraction. This class provides syntactic sugar for a stack of objects of known type. It allows accessing attributes of the object at the top of the stack directly against this object, which allows for very terse syntax. For example, this code: stack = _StateStack(Foo) stack.enter() stack.bar Is equivalent to: stack = [] stack.append(Foo()) foo = stack[-1] foo.bar See _State for more on how this is used. Attributes: type: Any, the type of objects that this stack holds level: int, the current stack depth stack: List[Any], the actual stack value: Any, the instance of the object at the top of the stack """ def __init__(self, type_): # Because we override __setattr__, we need to attach these attributes using # the superclass' setattr. object.__setattr__(self, 'type', type_) object.__setattr__(self, '_stack', []) if not hasattr(type_, 'no_root'): self.enter() def enter(self): self._stack.append(self.type()) def exit(self): return self._stack.pop() @property def stack(self): return self._stack @property def level(self): return len(self._stack) @property def value(self): return self._stack[-1] def __iter__(self): return iter(self._stack) def __getattr__(self, key): return getattr(self._stack[-1], key) def __setattr__(self, key, value): setattr(self._stack[-1], key, value) class _State(object): """Supporting class for nested scope variable space for converter.Base. This structure offers syntactic sugar over a dict of stacks of objects of known type. These structures are useful to keep state during AST walks. Multiple different scopes can be tracked in parallel. For example: s = _State() s[foo].enter() s[bar].enter() # this will not affect s[foo] Element access has special semantics: * keys are a data type * element values are _StateStack(type=key) objects * missing elements are automatically added, similarly to defaultdict For example, the following block : _State s s[Foo] Is equivalent to: s = {} if Foo not in s: s[Foo] = Foo() s[Foo] See Base for how it's used. """ def __init__(self): self._value = {} def __getitem__(self, key): if key not in self._value: self._value[key] = _StateStack(key) return self._value[key] class Base(gast.NodeTransformer): """Base class for general-purpose code transformers transformers. This is an extension of ast.NodeTransformer that provides a few additional functions, like state tracking within the scope of arbitrary node, helpers for processing code blocks, debugging, mapping of transformed code to original code, and others. Scope-local state tracking: to keep state across nodes, at the level of (possibly nested) scopes, use enter/exit_local_scope and set/get_local. You must call enter/exit_local_scope manually, but the transformer detects when they are not properly paired. The transformer allows keeping state across calls to visit_* that is local to arbitrary nodes and their descendants, using the self.state attribute. Multiple independent scopes are allowed and automatically constructed. For example, to keep track of the If node that encloses any Name node, one can write: class FooType(object): def __init__(self): self.foo_property = None class DummyTransformer(Base): def visit_If(self, node): self.state[FooType].enter() self.state[FooType].foo_property = node def visit_Name(self, node): self.state[FooType].foo_property # will hold the innermost enclosing if """ # TODO(mdan): Document all extra features. def __init__(self, ctx): """Initialize the transformer. Subclasses should call this. Args: ctx: A Context object. """ self._lineno = 0 self._col_offset = 0 self.ctx = ctx self._enclosing_entities = [] # A stack that allows keeping mutable, scope-local state where scopes may be # nested. For example, it can be used to track the usage of break # statements in each loop, where loops may be nested. self._local_scope_state = [] self.enter_local_scope() # Allows scoping of local variables to keep state across calls to visit_* # methods. Multiple scope hierchies may exist and are keyed by tag. A scope # is valid at one or more nodes and all its children. Scopes created in # child nodes supersede their parent. Scopes are isolated from one another. self.state = _State() @property def enclosing_entities(self): return tuple(self._enclosing_entities) @property def local_scope_level(self): return len(self._local_scope_state) def enter_local_scope(self, inherit=None): """Deprecated. Use self.state instead. Marks entry into a new local scope. Args: inherit: Optional enumerable of variable names to copy from the parent scope. """ scope_entered = {} if inherit: this_scope = self._local_scope_state[-1] for name in inherit: if name in this_scope: scope_entered[name] = this_scope[name] self._local_scope_state.append(scope_entered) def exit_local_scope(self, keep=None): """Deprecated. Use self.state instead. Marks exit from the current local scope. Args: keep: Optional enumerable of variable names to copy into the parent scope. Returns: A dict containing the scope that has just been exited. """ scope_left = self._local_scope_state.pop() if keep: this_scope = self._local_scope_state[-1] for name in keep: if name in scope_left: this_scope[name] = scope_left[name] return scope_left def set_local(self, name, value): """Deprecated. Use self.state instead.""" self._local_scope_state[-1][name] = value def get_local(self, name, default=None): """Deprecated. Use self.state instead.""" return self._local_scope_state[-1].get(name, default) def debug_print(self, node): """Helper method useful for debugging. Prints the AST.""" if __debug__: print(pretty_printer.fmt(node)) return node def debug_print_src(self, node): """Helper method useful for debugging. Prints the AST as code.""" if __debug__: print(compiler.ast_to_source(node)) return node def create_assignment(self, target, expression): template = """ target = expression """ return templates.replace(template, target=target, expression=expression) def visit_block(self, nodes, before_visit=None, after_visit=None): """A more powerful version of generic_visit for statement blocks. An example of a block is the body of an if statement. This function allows specifying a postprocessing callback (the after_visit argument) argument which can be used to move nodes to a new destination. This is done by after_visit by returning a non-null second return value, e.g. return new_node, new_destination. For example, a transformer could perform the following move: foo() bar() baz() foo() if cond: bar() baz() The above could be done with a postprocessor of this kind: def after_visit(node): if node_is_function_call(bar): new_container_node = build_cond() new_container_node.body.append(node) return new_container_node, new_container_node.body else: # Once we set a new destination, all subsequent items will be # moved to it, so we don't need to explicitly handle baz. return node, None Args: nodes: enumerable of AST node objects. If None, the function returns None. before_visit: optional callable that is called before visiting each item in nodes after_visit: optional callable that takes in an AST node and returns a tuple (new_node, new_destination). It is called after visiting each item in nodes. Is used in the same was as the visit_* methods: new_node will replace the node; if not None, new_destination must be a list, and subsequent nodes will be placed in this list instead of the list returned by visit_block. Returns: A list of AST node objects containing the transformed items fron nodes, except those nodes that have been relocated using after_visit. """ if nodes is None: return None results = [] node_destination = results for node in nodes: if before_visit: # TODO(mdan): We can modify node here too, if ever needed. before_visit() replacement = self.visit(node) if after_visit and replacement: replacement, new_destination = after_visit(replacement) else: new_destination = None if replacement: if isinstance(replacement, (list, tuple)): node_destination.extend(replacement) else: node_destination.append(replacement) # Allow the postprocessor to reroute the remaining nodes to a new list. if new_destination is not None: node_destination = new_destination return results # TODO(mdan): Remove. def apply_to_single_assignments(self, targets, values, apply_fn): """Applies a function to each individual assignment. This function can process a possibly-unpacked (e.g. a, b = c, d) assignment. It tries to break down the unpacking if possible. In effect, it has the same effect as passing the assigned values in SSA form to apply_fn. Examples: The following will result in apply_fn(a, c), apply_fn(b, d): a, b = c, d The following will result in apply_fn(a, c[0]), apply_fn(b, c[1]): a, b = c The following will result in apply_fn(a, (b, c)): a = b, c It uses the visitor pattern to allow subclasses to process single assignments individually. Args: targets: list, tuple of or individual AST node. Should be used with the targets field of an ast.Assign node. values: an AST node. apply_fn: a function of a single argument, which will be called with the respective nodes of each single assignment. The signature is apply_fn(target, value), no return value. """ if not isinstance(targets, (list, tuple)): targets = (targets,) for target in targets: if isinstance(target, (gast.Tuple, gast.List)): for i in range(len(target.elts)): target_el = target.elts[i] if isinstance(values, (gast.Tuple, gast.List)): value_el = values.elts[i] else: value_el = gast.Subscript(values, gast.Index(i), ctx=gast.Store()) self.apply_to_single_assignments(target_el, value_el, apply_fn) else: # TODO(mdan): Look into allowing to rewrite the AST here. apply_fn(target, values) def _get_source(self, node): try: source, _ = compiler.ast_to_source(node) return source # pylint: disable=broad-except # This function is used for error reporting. If an exception occurs here, # it should be suppressed, in favor of emitting as informative a message # about the original error as possible. except Exception: return '<could not convert AST to source>' def visit(self, node): if not isinstance(node, gast.AST): # This is not that uncommon a mistake: various node bodies are lists, for # example, posing a land mine for transformers that need to recursively # call `visit`. The error needs to be raised before the exception handler # below is installed, because said handler will mess up if `node` is not, # in fact, a node. msg = ('invalid value for "node": expected "ast.AST", got "{}"; to' ' visit lists of nodes, use "visit_block" instead').format( type(node)) raise ValueError(msg) did_enter_function = False local_scope_size_at_entry = len(self._local_scope_state) processing_expr_node = False parent_origin = self.ctx.current_origin if isinstance(node, (gast.FunctionDef, gast.ClassDef, gast.Lambda)): did_enter_function = True elif isinstance(node, gast.Expr): processing_expr_node = True if did_enter_function: self._enclosing_entities.append(node) if anno.hasanno(node, anno.Basic.ORIGIN): self.ctx.current_origin = anno.getanno(node, anno.Basic.ORIGIN) if processing_expr_node: entry_expr_value = node.value if not anno.hasanno(node, anno.Basic.SKIP_PROCESSING): result = super(Base, self).visit(node) self.ctx.current_origin = parent_origin # Adjust for consistency: replacing the value of an Expr with # an Assign node removes the need for the Expr node. if processing_expr_node: if isinstance(result, gast.Expr) and result.value != entry_expr_value: # When the replacement is a list, it is assumed that the list came # from a template that contained a number of statements, which # themselves are standalone and don't require an enclosing Expr. if isinstance(result.value, (list, tuple, gast.Assign, gast.AugAssign)): result = result.value # By default, all replacements receive the origin info of the replaced node. if result is not node and result is not None: nodes_to_adjust = result if isinstance(result, (list, tuple)): nodes_to_adjust = result else: nodes_to_adjust = (result,) for n in nodes_to_adjust: if not anno.hasanno(n, anno.Basic.ORIGIN): inherited_origin = anno.getanno( node, anno.Basic.ORIGIN, default=parent_origin) if inherited_origin is not None: anno.setanno(n, anno.Basic.ORIGIN, inherited_origin) # On exception, the local scope integrity is not guaranteed. if did_enter_function: self._enclosing_entities.pop() if local_scope_size_at_entry != len(self._local_scope_state): raise AssertionError( 'Inconsistent local scope stack. Before entering node %s, the' ' stack had length %d, after exit it has length %d. This' ' indicates enter_local_scope and exit_local_scope are not' ' well paired.' % (node, local_scope_size_at_entry, len(self._local_scope_state))) return result
tensorflow-master
tensorflow/python/autograph/pyct/transformer.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for qual_names module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import textwrap from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import qual_names from tensorflow.python.autograph.pyct.qual_names import QN from tensorflow.python.autograph.pyct.qual_names import resolve from tensorflow.python.platform import test class QNTest(test.TestCase): def test_from_str(self): a = QN('a') b = QN('b') a_dot_b = QN(a, attr='b') a_sub_b = QN(a, subscript=b) self.assertEqual(qual_names.from_str('a.b'), a_dot_b) self.assertEqual(qual_names.from_str('a'), a) self.assertEqual(qual_names.from_str('a[b]'), a_sub_b) def test_basic(self): a = QN('a') self.assertEqual(a.qn, ('a',)) self.assertEqual(str(a), 'a') self.assertEqual(a.ssf(), 'a') self.assertEqual(a.ast().id, 'a') self.assertFalse(a.is_composite()) with self.assertRaises(ValueError): _ = a.parent a_b = QN(a, attr='b') self.assertEqual(a_b.qn, (a, 'b')) self.assertEqual(str(a_b), 'a.b') self.assertEqual(a_b.ssf(), 'a_b') self.assertEqual(a_b.ast().value.id, 'a') self.assertEqual(a_b.ast().attr, 'b') self.assertTrue(a_b.is_composite()) self.assertEqual(a_b.parent.qn, ('a',)) def test_subscripts(self): a = QN('a') b = QN('b') a_sub_b = QN(a, subscript=b) self.assertEqual(a_sub_b.qn, (a, b)) self.assertEqual(str(a_sub_b), 'a[b]') self.assertEqual(a_sub_b.ssf(), 'a_sub_b') self.assertEqual(a_sub_b.ast().value.id, 'a') self.assertEqual(a_sub_b.ast().slice.value.id, 'b') self.assertTrue(a_sub_b.is_composite()) self.assertTrue(a_sub_b.has_subscript()) self.assertEqual(a_sub_b.parent.qn, ('a',)) c = QN('c') b_sub_c = QN(b, subscript=c) a_sub_b_sub_c = QN(a, subscript=b_sub_c) self.assertEqual(a_sub_b_sub_c.qn, (a, b_sub_c)) self.assertTrue(a_sub_b.is_composite()) self.assertTrue(a_sub_b_sub_c.is_composite()) self.assertTrue(a_sub_b.has_subscript()) self.assertTrue(a_sub_b_sub_c.has_subscript()) self.assertEqual(b_sub_c.qn, (b, c)) self.assertEqual(str(a_sub_b_sub_c), 'a[b[c]]') self.assertEqual(a_sub_b_sub_c.ssf(), 'a_sub_b_sub_c') self.assertEqual(a_sub_b_sub_c.ast().value.id, 'a') self.assertEqual(a_sub_b_sub_c.ast().slice.value.value.id, 'b') self.assertEqual(a_sub_b_sub_c.ast().slice.value.slice.value.id, 'c') self.assertEqual(b_sub_c.ast().slice.value.id, 'c') self.assertEqual(a_sub_b_sub_c.parent.qn, ('a',)) with self.assertRaises(ValueError): QN('a', 'b') def test_equality(self): a = QN('a') a2 = QN('a') a_b = QN(a, attr='b') self.assertEqual(a2.qn, ('a',)) with self.assertRaises(ValueError): _ = a.parent a_b2 = QN(a, attr='b') self.assertEqual(a_b2.qn, (a, 'b')) self.assertEqual(a_b2.parent.qn, ('a',)) self.assertTrue(a2 == a) self.assertFalse(a2 is a) self.assertTrue(a_b.parent == a) self.assertTrue(a_b2.parent == a) self.assertTrue(a_b2 == a_b) self.assertFalse(a_b2 is a_b) self.assertFalse(a_b2 == a) a_sub_b = QN(a, subscript='b') a_sub_b2 = QN(a, subscript='b') self.assertTrue(a_sub_b == a_sub_b2) self.assertFalse(a_sub_b == a_b) def test_nested_attrs_subscripts(self): a = QN('a') b = QN('b') c = QN('c') b_sub_c = QN(b, subscript=c) a_sub_b_sub_c = QN(a, subscript=b_sub_c) b_dot_c = QN(b, attr='c') a_sub__b_dot_c = QN(a, subscript=b_dot_c) a_sub_b = QN(a, subscript=b) a_sub_b__dot_c = QN(a_sub_b, attr='c') a_dot_b = QN(a, attr='b') a_dot_b_sub_c = QN(a_dot_b, subscript=c) self.assertEqual(str(a_sub_b_sub_c), 'a[b[c]]') self.assertEqual(str(a_sub__b_dot_c), 'a[b.c]') self.assertEqual(str(a_sub_b__dot_c), 'a[b].c') self.assertEqual(str(a_dot_b_sub_c), 'a.b[c]') self.assertNotEqual(a_sub_b_sub_c, a_sub__b_dot_c) self.assertNotEqual(a_sub_b_sub_c, a_sub_b__dot_c) self.assertNotEqual(a_sub_b_sub_c, a_dot_b_sub_c) self.assertNotEqual(a_sub__b_dot_c, a_sub_b__dot_c) self.assertNotEqual(a_sub__b_dot_c, a_dot_b_sub_c) self.assertNotEqual(a_sub_b__dot_c, a_dot_b_sub_c) def test_hashable(self): d = {QN('a'): 'a', QN('b'): 'b'} self.assertEqual(d[QN('a')], 'a') self.assertEqual(d[QN('b')], 'b') self.assertTrue(QN('c') not in d) def test_literals(self): a = QN('a') a_sub_str_b = QN(a, subscript=QN(qual_names.StringLiteral('b'))) a_sub_b = QN(a, subscript=QN('b')) self.assertNotEqual(a_sub_str_b, a_sub_b) self.assertNotEqual(hash(a_sub_str_b), hash(a_sub_b)) a_sub_three = QN(a, subscript=QN(qual_names.NumberLiteral(3))) self.assertEqual(a_sub_three.ast().slice.value.n, 3) def test_support_set(self): a = QN('a') b = QN('b') c = QN('c') a_sub_b = QN(a, subscript=b) a_dot_b = QN(a, attr='b') a_dot_b_dot_c = QN(a_dot_b, attr='c') a_dot_b_sub_c = QN(a_dot_b, subscript=c) self.assertSetEqual(a.support_set, set((a,))) self.assertSetEqual(a_sub_b.support_set, set((a, b))) self.assertSetEqual(a_dot_b.support_set, set((a,))) self.assertSetEqual(a_dot_b_dot_c.support_set, set((a,))) self.assertSetEqual(a_dot_b_sub_c.support_set, set((a, c))) class QNResolverTest(test.TestCase): def assertQNStringIs(self, node, qn_str): self.assertEqual(str(anno.getanno(node, anno.Basic.QN)), qn_str) def test_resolve(self): samples = """ a a.b (c, d.e) [f, (g.h.i)] j(k, l) """ nodes = parser.parse_str(textwrap.dedent(samples), single_node=False) nodes = tuple(resolve(node).value for node in nodes) self.assertQNStringIs(nodes[0], 'a') self.assertQNStringIs(nodes[1], 'a.b') self.assertQNStringIs(nodes[2].elts[0], 'c') self.assertQNStringIs(nodes[2].elts[1], 'd.e') self.assertQNStringIs(nodes[3].elts[0], 'f') self.assertQNStringIs(nodes[3].elts[1], 'g.h.i') self.assertQNStringIs(nodes[4].func, 'j') self.assertQNStringIs(nodes[4].args[0], 'k') self.assertQNStringIs(nodes[4].args[1], 'l') def test_subscript_resolve(self): samples = """ x[i] x[i.b] a.b[c] a.b[x.y] a[z[c]] a[b[c[d]]] a[b].c a.b.c[d].e.f a.b[c[d]].e.f a.b[c[d.e.f].g].h """ nodes = parser.parse_str(textwrap.dedent(samples), single_node=False) nodes = tuple(resolve(node).value for node in nodes) self.assertQNStringIs(nodes[0], 'x[i]') self.assertQNStringIs(nodes[1], 'x[i.b]') self.assertQNStringIs(nodes[2], 'a.b[c]') self.assertQNStringIs(nodes[3], 'a.b[x.y]') self.assertQNStringIs(nodes[4], 'a[z[c]]') self.assertQNStringIs(nodes[5], 'a[b[c[d]]]') self.assertQNStringIs(nodes[6], 'a[b].c') self.assertQNStringIs(nodes[7], 'a.b.c[d].e.f') self.assertQNStringIs(nodes[8], 'a.b[c[d]].e.f') self.assertQNStringIs(nodes[9], 'a.b[c[d.e.f].g].h') def test_function_calls(self): samples = """ a.b a.b() a().b z[i] z[i]() z()[i] """ nodes = parser.parse_str(textwrap.dedent(samples), single_node=False) nodes = tuple(resolve(node).value for node in nodes) self.assertQNStringIs(nodes[0], 'a.b') self.assertQNStringIs(nodes[1].func, 'a.b') self.assertQNStringIs(nodes[2].value.func, 'a') self.assertQNStringIs(nodes[3], 'z[i]') self.assertQNStringIs(nodes[4].func, 'z[i]') self.assertQNStringIs(nodes[5].value.func, 'z') if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/qual_names_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for anno module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import ast from tensorflow.python.autograph.pyct import anno from tensorflow.python.platform import test # TODO(mdan): Consider strong types instead of primitives. class AnnoTest(test.TestCase): def test_basic(self): node = ast.Name() self.assertEqual(anno.keys(node), set()) self.assertFalse(anno.hasanno(node, 'foo')) with self.assertRaises(AttributeError): anno.getanno(node, 'foo') anno.setanno(node, 'foo', 3) self.assertEqual(anno.keys(node), {'foo'}) self.assertTrue(anno.hasanno(node, 'foo')) self.assertEqual(anno.getanno(node, 'foo'), 3) self.assertEqual(anno.getanno(node, 'bar', default=7), 7) anno.delanno(node, 'foo') self.assertEqual(anno.keys(node), set()) self.assertFalse(anno.hasanno(node, 'foo')) with self.assertRaises(AttributeError): anno.getanno(node, 'foo') self.assertIsNone(anno.getanno(node, 'foo', default=None)) def test_copy(self): node_1 = ast.Name() anno.setanno(node_1, 'foo', 3) node_2 = ast.Name() anno.copyanno(node_1, node_2, 'foo') anno.copyanno(node_1, node_2, 'bar') self.assertTrue(anno.hasanno(node_2, 'foo')) self.assertFalse(anno.hasanno(node_2, 'bar')) def test_duplicate(self): node = ast.If( test=ast.Num(1), body=[ast.Expr(ast.Name('bar', ast.Load()))], orelse=[]) anno.setanno(node, 'spam', 1) anno.setanno(node, 'ham', 1) anno.setanno(node.body[0], 'ham', 1) anno.dup(node, {'spam': 'eggs'}) self.assertTrue(anno.hasanno(node, 'spam')) self.assertTrue(anno.hasanno(node, 'ham')) self.assertTrue(anno.hasanno(node, 'eggs')) self.assertFalse(anno.hasanno(node.body[0], 'eggs')) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/anno_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Code transformation exceptions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import os from tensorflow.python.autograph.pyct import origin_info class FrameInfo( collections.namedtuple( 'FrameInfo', ('filename', 'lineno', 'function_name', 'code', 'converted'))): pass def _stack_trace_inside_mapped_code(tb, source_map): """Summarizes inner traceback frames up to the call to a given function. This functions locates the innermost (i.e. most recent) frame that corresponds to code that can be mapped by source_map originated from, and returns a translated stack trace ending at that frame. If no such frame is found, the entire stack trace is summarized. For example, the following code: def f(): for i in tf.range(1): z = y + i # z only defined here Would generate this traceback: <converted code> ag__.for_stmt(...) <for_stmt> return _known_len_tf_for_stmt(iter_, extra_test, body, init_state) <_known_len_tf_for_stmt> _disallow_undefs_into_loop(*init_state) <_disallow_undefs_into_loop> raise ... Which is then processed into: <f> for i in tf.range(1): <for_stmt> return _known_len_tf_for_stmt(iter_, extra_test, body, init_state) <_known_len_tf_for_stmt> _disallow_undefs_into_loop(*init_state) <_disallow_undefs_into_loop> raise ... Args: tb: List[Tuple], the traceback corresponding to an error; typically, the output of traceback.extract_tb. source_map: Dict[LineLocation, OriginInfo], a source map as created by origin_info.create_source_map. Returns: List[FrameInfo] """ result_frames = [] for filename, line_number, function_name, text in reversed(tb): loc = origin_info.LineLocation(filename=filename, lineno=line_number) if loc in source_map: origin = source_map[loc] origin_frame_info = FrameInfo( filename=origin.loc.filename, lineno=origin.loc.lineno, function_name=origin.function_name, code=origin.source_code_line, converted=True) result_frames.append(origin_frame_info) break fi = FrameInfo( filename=filename, lineno=line_number, function_name=function_name, code=text, converted=False) result_frames.append(fi) return tuple(result_frames) KNOWN_STRING_CONSTRUCTOR_ERRORS = ( AssertionError, AttributeError, NameError, NotImplementedError, RuntimeError, StopIteration, TypeError, ValueError, ) # KeyError escapes newlines in strings. We create a special subclass # that doesn't do that. Overriding the name for display purposes; hopefully # that won't create too many surprises. class MultilineMessageKeyError(KeyError): def __init__(self, message, original_key): super(MultilineMessageKeyError, self).__init__(original_key) self.__message = message def __str__(self): return self.__message MultilineMessageKeyError.__name__ = KeyError.__name__ class ErrorMetadataBase(object): """Container objects attached to exceptions in converted code. This metadata allows re-raising exceptions that occur in generated code, with a custom error message that includes a stack trace relative to user-readable code from which the generated code originated. """ def __init__(self, callsite_tb, cause_metadata, cause_message, source_map): translated_stack = _stack_trace_inside_mapped_code(callsite_tb, source_map) if cause_metadata is None: self.translated_stack = translated_stack self.cause_message = cause_message else: # Daisy chain the translated stacks. self.translated_stack = ( cause_metadata.translated_stack + (translated_stack[-1],)) self.cause_message = cause_metadata.cause_message def get_message(self): """Returns the message for the underlying exception.""" all_paths = tuple(fi.filename for fi in self.translated_stack) if len(all_paths) > 1: common_path = os.path.dirname(os.path.commonprefix(all_paths)) if common_path == os.path.sep: common_path = '' if common_path: path_idx = len(common_path) + 1 else: path_idx = 0 else: common_path = '' path_idx = 0 lines = [] lines.append('in converted code:') if common_path: lines.append(' relative to {}:'.format(common_path)) lines.append('') for frame_info in reversed(self.translated_stack): lines.append(' {}:{} {}{}'.format( frame_info.filename[path_idx:], frame_info.lineno, frame_info.function_name, ' *' if frame_info.converted else '', )) if frame_info.code is None: code_snippet = '<source unavailable>' else: code_snippet = frame_info.code.strip() lines.append(' {}'.format(code_snippet)) lines.append('') message_lines = self.cause_message.split('\n') for i in range(len(message_lines)): message_lines[i] = ' ' + message_lines[i] lines.extend(message_lines) lines.append('') return '\n'.join(lines) def create_exception(self, preferred_type): if preferred_type.__init__ is Exception.__init__: return preferred_type(self.get_message()) if preferred_type in KNOWN_STRING_CONSTRUCTOR_ERRORS: return preferred_type(self.get_message()) elif preferred_type is KeyError: return MultilineMessageKeyError(self.get_message(), self.cause_message) return None def to_exception(self, preferred_type): exc = self.create_exception(preferred_type) exc.__suppress_context__ = True exc.ag_error_metadata = self return exc
tensorflow-master
tensorflow/python/autograph/pyct/errors.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """AST node annotation support. Adapted from Tangent. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import enum # pylint:disable=g-bad-import-order import gast # pylint:enable=g-bad-import-order # TODO(mdan): Shorten the names. # These names are heavily used, and anno.blaa # TODO(mdan): Replace the attr-dict mechanism with a more typed solution. class NoValue(enum.Enum): def __repr__(self): return self.name class Basic(NoValue): """Container for basic annotation keys. The enum values are used strictly for documentation purposes. """ QN = 'Qualified name, as it appeared in the code. See qual_names.py.' SKIP_PROCESSING = ( 'This node should be preserved as is and not processed any further.') INDENT_BLOCK_REMAINDER = ( 'When a node is annotated with this, the remainder of the block should' ' be indented below it. The annotation contains a tuple' ' (new_body, name_map), where `new_body` is the new indented block and' ' `name_map` allows renaming symbols.') ORIGIN = ('Information about the source code that converted code originated' ' from. See origin_information.py.') class Static(NoValue): """Container for static analysis annotation keys. The enum values are used strictly for documentation purposes. """ # Symbols # These flags are boolean. IS_PARAM = 'Symbol is a parameter to the function being analyzed.' # Scopes # Scopes are represented by objects of type activity.Scope. SCOPE = 'The scope for the annotated node. See activity.py.' # TODO(mdan): Drop these in favor of accessing the child's SCOPE. ARGS_SCOPE = 'The scope for the argument list of a function call.' COND_SCOPE = 'The scope for the test node of a conditional statement.' BODY_SCOPE = ( 'The scope for the main body of a statement (True branch for if ' 'statements, main body for loops).') ORELSE_SCOPE = ( 'The scope for the orelse body of a statement (False branch for if ' 'statements, orelse body for loops).') # Static analysis annotations. DEFINITIONS = ( 'Reaching definition information. See reaching_definitions.py.') ORIG_DEFINITIONS = ( 'The value of DEFINITIONS that applied to the original code before any' ' conversion.') DEFINED_VARS_IN = ( 'Symbols defined when entering the node. See reaching_definitions.py.') LIVE_VARS_OUT = ('Symbols live when exiting the node. See liveness.py.') LIVE_VARS_IN = ('Symbols live when entering the node. See liveness.py.') FAIL = object() def keys(node, field_name='___pyct_anno'): if not hasattr(node, field_name): return frozenset() return frozenset(getattr(node, field_name).keys()) def getanno(node, key, default=FAIL, field_name='___pyct_anno'): if (default is FAIL or (hasattr(node, field_name) and (key in getattr(node, field_name)))): return getattr(node, field_name)[key] else: return default def hasanno(node, key, field_name='___pyct_anno'): return hasattr(node, field_name) and key in getattr(node, field_name) def setanno(node, key, value, field_name='___pyct_anno'): annotations = getattr(node, field_name, {}) setattr(node, field_name, annotations) annotations[key] = value # So that the annotations survive gast_to_ast() and ast_to_gast() if field_name not in node._fields: node._fields += (field_name,) def delanno(node, key, field_name='___pyct_anno'): annotations = getattr(node, field_name) del annotations[key] if not annotations: delattr(node, field_name) node._fields = tuple(f for f in node._fields if f != field_name) def copyanno(from_node, to_node, key, field_name='___pyct_anno'): if hasanno(from_node, key, field_name=field_name): setanno( to_node, key, getanno(from_node, key, field_name=field_name), field_name=field_name) def dup(node, copy_map, field_name='___pyct_anno'): """Recursively copies annotations in an AST tree. Args: node: ast.AST copy_map: Dict[Hashable, Hashable], maps a source anno key to a destination key. All annotations with the source key will be copied to identical annotations with the destination key. field_name: str """ for n in gast.walk(node): for k in copy_map: if hasanno(n, k, field_name): setanno(n, copy_map[k], getanno(n, k, field_name), field_name)
tensorflow-master
tensorflow/python/autograph/pyct/anno.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Container for origin source code information before AutoGraph compilation.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import difflib import os import tokenize import gast import six from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import ast_util from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import pretty_printer from tensorflow.python.autograph.utils import ag_logging as logging from tensorflow.python.util import tf_inspect class LineLocation( collections.namedtuple('LineLocation', ('filename', 'lineno'))): """Similar to Location, but without column information. Attributes: filename: Text lineno: int, 1-based """ pass class Location( collections.namedtuple('Location', ('filename', 'lineno', 'col_offset'))): """Encodes code location information. Attributes: filename: Text lineno: int, 1-based col_offset: int line_loc: LineLocation """ @property def line_loc(self): return LineLocation(self.filename, self.lineno) class OriginInfo( collections.namedtuple( 'OriginInfo', ('loc', 'function_name', 'source_code_line', 'comment'))): """Container for information about the source code before conversion. Attributes: loc: Location function_name: Optional[Text] source_code_line: Text comment: Optional[Text] """ def as_frame(self): """Returns a 4-tuple consistent with the return of traceback.extract_tb.""" return (self.loc.filename, self.loc.lineno, self.function_name, self.source_code_line) def __repr__(self): if self.loc.filename: return '{}:{}:{}'.format( os.path.split(self.loc.filename)[1], self.loc.lineno, self.loc.col_offset) return '<no file>:{}:{}'.format(self.loc.lineno, self.loc.col_offset) # TODO(mdan): This source map should be a class - easier to refer to. def create_source_map(nodes, code, filepath): """Creates a source map between an annotated AST and the code it compiles to. Note: this function assumes nodes nodes, code and filepath correspond to the same code. Args: nodes: Iterable[ast.AST, ...], one or more AST modes. code: Text, the source code in which nodes are found. filepath: Text Returns: Dict[LineLocation, OriginInfo], mapping locations in code to locations indicated by origin annotations in node. """ reparsed_nodes = parser.parse_str(code, preamble_len=0, single_node=False) for node in reparsed_nodes: resolve(node, code, filepath, node.lineno, node.col_offset) source_map = {} try: for before, after in ast_util.parallel_walk(nodes, reparsed_nodes): # Note: generated code might not be mapped back to its origin. # TODO(mdan): Generated code should always be mapped to something. origin_info = anno.getanno(before, anno.Basic.ORIGIN, default=None) final_info = anno.getanno(after, anno.Basic.ORIGIN, default=None) if origin_info is None or final_info is None: continue # Note: the keys are by line only, excluding the column offset. line_loc = LineLocation(final_info.loc.filename, final_info.loc.lineno) existing_origin = source_map.get(line_loc) if existing_origin is not None: # Overlaps may exist because of child nodes, but almost never to # different line locations. Exception make decorated functions, where # both lines are mapped to the same line in the AST. # Line overlaps: keep bottom node. if existing_origin.loc.line_loc == origin_info.loc.line_loc: if existing_origin.loc.lineno >= origin_info.loc.lineno: continue # In case of column overlaps, keep the leftmost node. if existing_origin.loc.col_offset <= origin_info.loc.col_offset: continue source_map[line_loc] = origin_info except ValueError: if logging.has_verbosity(3): for n, rn in zip(nodes, reparsed_nodes): nodes_str = pretty_printer.fmt(n, color=False, noanno=True) reparsed_nodes_str = pretty_printer.fmt(rn, color=False, noanno=True) diff = difflib.context_diff( nodes_str.split('\n'), reparsed_nodes_str.split('\n'), fromfile='Original nodes', tofile='Reparsed nodes', n=7) diff = '\n'.join(diff) logging.log(3, 'AST seems to lack integrity. Diff:\n%s', diff) raise return source_map class _Function(object): def __init__(self, name): self.name = name class OriginResolver(gast.NodeVisitor): """Annotates an AST with additional source information like file name.""" def __init__(self, root_node, source_lines, comments_map, context_lineno, context_col_offset, filepath): self._source_lines = source_lines self._comments_map = comments_map self._lineno_offset = context_lineno - root_node.lineno self._col_offset = context_col_offset - root_node.col_offset self._filepath = filepath self._function_stack = [] def _absolute_lineno(self, node): return node.lineno + self._lineno_offset def _absolute_col_offset(self, node): return node.col_offset + self._col_offset def _attach_origin_info(self, node): if self._function_stack: function_name = self._function_stack[-1].name else: function_name = None source_code_line = self._source_lines[node.lineno - 1] comment = self._comments_map.get(node.lineno) loc = Location(self._filepath, self._absolute_lineno(node), self._absolute_col_offset(node)) origin = OriginInfo(loc, function_name, source_code_line, comment) anno.setanno(node, 'lineno', node.lineno) anno.setanno(node, anno.Basic.ORIGIN, origin) def visit(self, node): entered_function = False if isinstance(node, gast.FunctionDef): entered_function = True self._function_stack.append(_Function(node.name)) if hasattr(node, 'lineno'): self._attach_origin_info(node) self.generic_visit(node) if entered_function: self._function_stack.pop() def resolve(node, source, context_filepath, context_lineno, context_col_offset): """Adds origin information to an AST, based on the source it was loaded from. This allows us to map the original source code line numbers to generated source code. Note: the AST may be a part of a larger context (e.g. a function is part of a module that may contain other things). However, this function does not assume the source argument contains the entire context, nor that it contains only code corresponding to node itself. However, it assumes that node was parsed from the given source code. For this reason, two extra arguments are required, and they indicate the location of the node in the original context. Args: node: gast.AST, the AST to annotate. source: Text, the source code representing node. context_filepath: Text context_lineno: int context_col_offset: int """ # TODO(mdan): Pull this to a separate utility. code_reader = six.StringIO(source) comments_map = {} for token in tokenize.generate_tokens(code_reader.readline): tok_type, tok_string, loc, _, _ = token srow, _ = loc if tok_type == tokenize.COMMENT: comments_map[srow] = tok_string.strip()[1:].strip() source_lines = source.split('\n') visitor = OriginResolver(node, source_lines, comments_map, context_lineno, context_col_offset, context_filepath) visitor.visit(node) def resolve_entity(node, source, entity): """Like resolve, but extracts the context informartion from an entity.""" lines, lineno = tf_inspect.getsourcelines(entity) filepath = tf_inspect.getsourcefile(entity) # Poor man's attempt at guessing the column offset: count the leading # whitespace. This might not work well with tabs. definition_line = lines[0] col_offset = len(definition_line) - len(definition_line.lstrip()) resolve(node, source, filepath, lineno, col_offset)
tensorflow-master
tensorflow/python/autograph/pyct/origin_info.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities for manipulating qualified names. A qualified name is a uniform way to refer to simple (e.g. 'foo') and composite (e.g. 'foo.bar') syntactic symbols. This is *not* related to the __qualname__ attribute used by inspect, which refers to scopes. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import gast from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import parser class Symbol(collections.namedtuple('Symbol', ['name'])): """Represents a Python symbol.""" class StringLiteral(collections.namedtuple('StringLiteral', ['value'])): """Represents a Python string literal.""" def __str__(self): return '\'%s\'' % self.value def __repr__(self): return str(self) class NumberLiteral(collections.namedtuple('NumberLiteral', ['value'])): """Represents a Python numeric literal.""" def __str__(self): return '%s' % self.value def __repr__(self): return str(self) # TODO(mdan): Use subclasses to remove the has_attr has_subscript booleans. class QN(object): """Represents a qualified name.""" def __init__(self, base, attr=None, subscript=None): if attr is not None and subscript is not None: raise ValueError('A QN can only be either an attr or a subscript, not ' 'both: attr={}, subscript={}.'.format(attr, subscript)) self._has_attr = False self._has_subscript = False if attr is not None: if not isinstance(base, QN): raise ValueError( 'for attribute QNs, base must be a QN; got instead "%s"' % base) if not isinstance(attr, str): raise ValueError('attr may only be a string; got instead "%s"' % attr) self._parent = base # TODO(mdan): Get rid of the tuple - it can only have 1 or 2 elements now. self.qn = (base, attr) self._has_attr = True elif subscript is not None: if not isinstance(base, QN): raise ValueError('For subscript QNs, base must be a QN.') self._parent = base self.qn = (base, subscript) self._has_subscript = True else: if not isinstance(base, (str, StringLiteral, NumberLiteral)): # TODO(mdan): Require Symbol instead of string. raise ValueError( 'for simple QNs, base must be a string or a Literal object;' ' got instead "%s"' % type(base)) assert '.' not in base and '[' not in base and ']' not in base self._parent = None self.qn = (base,) def is_symbol(self): return isinstance(self.qn[0], str) def is_simple(self): return len(self.qn) <= 1 def is_composite(self): return len(self.qn) > 1 def has_subscript(self): return self._has_subscript def has_attr(self): return self._has_attr @property def parent(self): if self._parent is None: raise ValueError('Cannot get parent of simple name "%s".' % self.qn[0]) return self._parent @property def owner_set(self): """Returns all the symbols (simple or composite) that own this QN. In other words, if this symbol was modified, the symbols in the owner set may also be affected. Examples: 'a.b[c.d]' has two owners, 'a' and 'a.b' """ owners = set() if self.has_attr() or self.has_subscript(): owners.add(self.parent) owners.update(self.parent.owner_set) return owners @property def support_set(self): """Returns the set of simple symbols that this QN relies on. This would be the smallest set of symbols necessary for the QN to statically resolve (assuming properties and index ranges are verified at runtime). Examples: 'a.b' has only one support symbol, 'a' 'a[i]' has two support symbols, 'a' and 'i' """ # TODO(mdan): This might be the set of Name nodes in the AST. Track those? roots = set() if self.has_attr(): roots.update(self.parent.support_set) elif self.has_subscript(): roots.update(self.parent.support_set) roots.update(self.qn[1].support_set) else: roots.add(self) return roots def __hash__(self): return hash(self.qn + (self._has_attr, self._has_subscript)) def __eq__(self, other): return (isinstance(other, QN) and self.qn == other.qn and self.has_subscript() == other.has_subscript() and self.has_attr() == other.has_attr()) def __str__(self): if self.has_subscript(): return str(self.qn[0]) + '[' + str(self.qn[1]) + ']' if self.has_attr(): return '.'.join(map(str, self.qn)) else: return str(self.qn[0]) def __repr__(self): return str(self) def ssf(self): """Simple symbol form.""" ssfs = [n.ssf() if isinstance(n, QN) else n for n in self.qn] ssf_string = '' for i in range(0, len(self.qn) - 1): if self.has_subscript(): delimiter = '_sub_' else: delimiter = '_' ssf_string += ssfs[i] + delimiter return ssf_string + ssfs[-1] def ast(self): # The caller must adjust the context appropriately. if self.has_subscript(): return gast.Subscript(self.parent.ast(), gast.Index(self.qn[-1].ast()), None) if self.has_attr(): return gast.Attribute(self.parent.ast(), self.qn[-1], None) base = self.qn[0] if isinstance(base, str): return gast.Name(base, None, None) elif isinstance(base, StringLiteral): return gast.Str(base.value) elif isinstance(base, NumberLiteral): return gast.Num(base.value) else: assert False, ('the constructor should prevent types other than ' 'str, StringLiteral and NumberLiteral') class QnResolver(gast.NodeTransformer): """Annotates nodes with QN information. Note: Not using NodeAnnos to avoid circular dependencies. """ def visit_Name(self, node): node = self.generic_visit(node) anno.setanno(node, anno.Basic.QN, QN(node.id)) return node def visit_Attribute(self, node): node = self.generic_visit(node) if anno.hasanno(node.value, anno.Basic.QN): anno.setanno(node, anno.Basic.QN, QN(anno.getanno(node.value, anno.Basic.QN), attr=node.attr)) return node def visit_Subscript(self, node): # TODO(mdan): This may no longer apply if we overload getitem. node = self.generic_visit(node) s = node.slice if not isinstance(s, gast.Index): # TODO(mdan): Support range and multi-dimensional indices. # Continuing silently because some demos use these. return node if isinstance(s.value, gast.Num): subscript = QN(NumberLiteral(s.value.n)) elif isinstance(s.value, gast.Str): subscript = QN(StringLiteral(s.value.s)) else: # The index may be an expression, case in which a name doesn't make sense. if anno.hasanno(node.slice.value, anno.Basic.QN): subscript = anno.getanno(node.slice.value, anno.Basic.QN) else: return node if anno.hasanno(node.value, anno.Basic.QN): anno.setanno(node, anno.Basic.QN, QN(anno.getanno(node.value, anno.Basic.QN), subscript=subscript)) return node def resolve(node): return QnResolver().visit(node) def from_str(qn_str): node = parser.parse_expression(qn_str) node = resolve(node) return anno.getanno(node, anno.Basic.QN)
tensorflow-master
tensorflow/python/autograph/pyct/qual_names.py
# python3 # Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for reaching_definitions module, that only run in Python 3.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.pyct.static_analysis import reaching_definitions_test from tensorflow.python.platform import test class ReachingDefinitionsAnalyzerTest( reaching_definitions_test.ReachingDefinitionsAnalyzerTestBase): """Tests which can only run in Python 3.""" def test_nonlocal_symbol(self): nonlocal_a = 3 nonlocal_b = 13 def test_fn(): nonlocal nonlocal_a nonlocal nonlocal_b if nonlocal_a: nonlocal_b = [] return nonlocal_a, nonlocal_b node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasDefs(fn_body[2].test, 1) self.assertHasDefs(fn_body[2].body[0].targets[0], 1) self.assertHasDefs(fn_body[3].value.elts[0], 1) self.assertHasDefs(fn_body[3].value.elts[1], 2) self.assertSameDef(fn_body[2].test, fn_body[3].value.elts[0]) self.assertHasDefinedIn(fn_body[2], ('nonlocal_a', 'nonlocal_b')) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/static_analysis/reaching_definitions_py3_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for liveness module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import cfg from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import qual_names from tensorflow.python.autograph.pyct import transformer from tensorflow.python.autograph.pyct.static_analysis import activity from tensorflow.python.autograph.pyct.static_analysis import liveness from tensorflow.python.platform import test global_a = 7 global_b = 17 class LivenessAnalyzerTestBase(test.TestCase): def _parse_and_analyze(self, test_fn): node, source = parser.parse_entity(test_fn, future_features=()) entity_info = transformer.EntityInfo( source_code=source, source_file=None, future_features=(), namespace={}) node = qual_names.resolve(node) ctx = transformer.Context(entity_info) node = activity.resolve(node, ctx) graphs = cfg.build(node) liveness.resolve(node, ctx, graphs) return node def assertHasLiveOut(self, node, expected): live_out = anno.getanno(node, anno.Static.LIVE_VARS_OUT) live_out_strs = set(str(v) for v in live_out) if not expected: expected = () if not isinstance(expected, tuple): expected = (expected,) self.assertSetEqual(live_out_strs, set(expected)) def assertHasLiveIn(self, node, expected): live_in = anno.getanno(node, anno.Static.LIVE_VARS_IN) live_in_strs = set(str(v) for v in live_in) if not expected: expected = () if not isinstance(expected, tuple): expected = (expected,) self.assertSetEqual(live_in_strs, set(expected)) class LivenessAnalyzerTest(LivenessAnalyzerTestBase): def test_live_out_try_block(self): def test_fn(x, a, b, c): # pylint:disable=unused-argument if a > 0: try: pass except: # pylint:disable=bare-except pass return x node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveOut(fn_body[0], 'x') self.assertHasLiveOut(fn_body[0].body[0], 'x') def test_live_out_if_inside_except(self): def test_fn(x, a, b, c): # pylint:disable=unused-argument if a > 0: try: pass except: # pylint:disable=bare-except if b > 0: x = b return x node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveOut(fn_body[0], 'x') self.assertHasLiveOut(fn_body[0].body[0], 'x') self.assertHasLiveOut(fn_body[0].body[0].handlers[0].body[0], 'x') def test_live_out_stacked_if(self): def test_fn(x, a): if a > 0: x = 0 if a > 1: x = 1 return x node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveOut(fn_body[0], ('a', 'x')) self.assertHasLiveOut(fn_body[1], 'x') def test_live_out_stacked_if_else(self): def test_fn(x, a): if a > 0: x = 0 if a > 1: x = 1 else: x = 2 return x node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveOut(fn_body[0], 'a') self.assertHasLiveOut(fn_body[1], 'x') def test_live_out_for_basic(self): def test_fn(x, a): for i in range(a): x += i return x node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveOut(fn_body[0], 'x') def test_live_out_for_iterate(self): def test_fn(x, a): for i in range(a): x += i return x, i # pylint:disable=undefined-loop-variable node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveOut(fn_body[0], ('x', 'i')) def test_live_out_attributes(self): def test_fn(x, a): if a > 0: x.y = 0 return x.y node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveOut(fn_body[0], ('x.y', 'x')) def test_live_out_nested_functions(self): def test_fn(a, b): if b: a = [] def foo(): return a foo() node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveOut(fn_body[0], 'a') def test_live_out_nested_functions_isolation(self): def test_fn(b): if b: a = 0 # pylint:disable=unused-variable def child(): max(a) # pylint:disable=used-before-assignment a = 1 return a child() node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveOut(fn_body[0], 'max') def test_live_out_deletion(self): def test_fn(x, y, a): for _ in a: if x: del y else: y = 0 node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveOut(fn_body[0], ()) def test_live_in_pass(self): def test_fn(x, a, b, c): # pylint:disable=unused-argument if a > 0: pass return x node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('a', 'x')) self.assertHasLiveIn(fn_body[0].body[0], ('x',)) self.assertHasLiveIn(fn_body[1], ('x',)) def test_live_in_return_statement(self): def test_fn(x, a, b, c): # pylint:disable=unused-argument if a > 0: return x return x node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('a', 'x')) self.assertHasLiveIn(fn_body[0].body[0], ('x',)) self.assertHasLiveIn(fn_body[1], ('x',)) def test_live_in_try_block(self): def test_fn(x, a, b, c): # pylint:disable=unused-argument if a > 0: try: pass except: # pylint:disable=bare-except pass return x node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('a', 'x')) self.assertHasLiveIn(fn_body[0].body[0], ('x',)) self.assertHasLiveIn(fn_body[1], ('x',)) def test_live_in_try_orelse(self): def test_fn(x, a, b, c): # pylint:disable=unused-argument if a > 0: try: pass except: # pylint:disable=bare-except pass else: x = b return x node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('a', 'b', 'x')) self.assertHasLiveIn(fn_body[0].body[0], ('b', 'x')) self.assertHasLiveIn(fn_body[1], ('x',)) def test_live_in_if_inside_except(self): def test_fn(x, a, b, c): # pylint:disable=unused-argument if a > 0: try: pass except: # pylint:disable=bare-except if b > 0: x = b return x node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('a', 'b', 'x')) self.assertHasLiveIn(fn_body[0].body[0], ('b', 'x')) self.assertHasLiveIn(fn_body[0].body[0].handlers[0].body[0], ('b', 'x')) self.assertHasLiveIn(fn_body[1], ('x',)) def test_live_in_stacked_if(self): def test_fn(x, a, b, c): if a > 0: x = b if c > 1: x = 0 return x node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('a', 'b', 'c', 'x')) self.assertHasLiveIn(fn_body[1], ('c', 'x')) def test_live_in_stacked_if_else(self): def test_fn(x, a, b, c, d): if a > 1: x = b else: x = c if d > 0: x = 0 return x node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('a', 'b', 'c', 'd')) self.assertHasLiveIn(fn_body[1], ('d', 'x')) def test_live_in_for_basic(self): def test_fn(x, y, a): for i in a: x = i y += x z = 0 return y, z node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('a', 'y', 'z')) def test_live_in_for_nested(self): def test_fn(x, y, a): for i in a: for j in i: x = i y += x z = j return y, z node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('a', 'y', 'z')) def test_live_in_deletion(self): def test_fn(x, y, a): for _ in a: if x: del y else: y = 0 node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('a', 'x', 'y')) def test_live_in_generator_comprehension(self): def test_fn(y): if all(x for x in y): return node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('all', 'y')) def test_live_in_list_comprehension(self): def test_fn(y): if [x for x in y]: return node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('y',)) def test_live_in_list_comprehension_expression(self): def test_fn(y, s): s += foo([x for x in y]) # pylint:disable=undefined-variable node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('y', 'foo', 's')) def test_live_in_set_comprehension(self): def test_fn(y): if {x for x in y}: return node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('y',)) def test_live_in_dict_comprehension(self): def test_fn(y): if {k: v for k, v in y}: return node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveIn(fn_body[0], ('y',)) def test_global_symbol(self): def test_fn(c): global global_a global global_b if global_a: global_b = c else: global_b = c return global_b node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveOut(fn_body[2], ('global_b',)) self.assertHasLiveIn(fn_body[2], ('global_a', 'c')) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/static_analysis/liveness_test.py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Live variable analysis. See https://en.wikipedia.org/wiki/Live_variable_analysis for a definition of the following idioms: live variable, live in, live out, which are used throughout this file. This analysis attaches the following: * symbols that are live at the exit of control flow statements * symbols that are live at the entry of control flow statements Requires activity analysis. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import cfg from tensorflow.python.autograph.pyct import transformer from tensorflow.python.autograph.pyct.static_analysis import annos class Analyzer(cfg.GraphVisitor): """CFG visitor that performs liveness analysis at statement level.""" def __init__(self, graph): super(Analyzer, self).__init__(graph) # This allows communicating that nodes generate extra symbols, # e.g. those that a function definition closes over. self.extra_gen = {} def init_state(self, _): return set() def visit_node(self, node): prev_live_in = self.in_[node] if anno.hasanno(node.ast_node, anno.Static.SCOPE): node_scope = anno.getanno(node.ast_node, anno.Static.SCOPE) gen = node_scope.read | self.extra_gen.get(node.ast_node, frozenset()) # TODO(mdan): verify whether composites' parents need to be added. # E.g. whether x needs to be added if x.y is live. Theoretically the # activity analysis should have both so that wouldn't be needed. kill = node_scope.modified | node_scope.deleted live_out = set() for n in node.next: live_out |= self.in_[n] live_in = gen | (live_out - kill) else: # Nodes that don't have a scope annotation are assumed not to touch any # symbols. # This Name node below is a literal name, e.g. False assert isinstance(node.ast_node, (gast.Name, gast.Continue, gast.Break, gast.Pass, gast.Global, gast.Nonlocal)), type(node.ast_node) live_out = set() for n in node.next: live_out |= self.in_[n] live_in = live_out self.in_[node] = live_in self.out[node] = live_out # TODO(mdan): Move this to the superclass? return prev_live_in != live_in class WholeTreeAnalyzer(transformer.Base): """Runs liveness analysis on each of the functions defined in the AST. If a function defined other local functions, those will have separate CFGs. However, dataflow analysis needs to tie up these CFGs to properly emulate the effect of closures. In the case of liveness, the parent function's live variables must account for the variables that are live at the entry of each subfunction. For example: def foo(): # baz is live here def bar(): print(baz) This analyzer runs liveness analysis on each individual function, accounting for the effect above. """ def __init__(self, source_info, graphs): super(WholeTreeAnalyzer, self).__init__(source_info) self.graphs = graphs self.current_analyzer = None self.analyzers = {} def visit_FunctionDef(self, node): parent_analyzer = self.current_analyzer subgraph = self.graphs[node] # Postorder tree processing makes this a bit complicated: # 1. construct an analyzer object and put it on stack # 2. recursively walk the subtree; this will initialize the analyzer's # in_ state properly (done in a block below) # 3. run the final analysis analyzer = Analyzer(subgraph) self.current_analyzer = analyzer node = self.generic_visit(node) analyzer.visit_reverse() if parent_analyzer is not None: # Wire the state between the two subgraphs' analyzers. child_in_state = analyzer.in_[subgraph.entry] # Exception: symbols modified in the child function are local to it body_scope = anno.getanno(node, annos.NodeAnno.BODY_SCOPE) for qn in body_scope.modified: # Note: a function modifying the symbol doesn't make that symbol # live at the function's entry. In fact when that happens it is # probably a case of undefined assignment, like this: # # bar = 0 # def foo(): # print(bar) # bar is undefined here! # bar = 1 # # Hence we use discard and not remove below. child_in_state.discard(qn) parent_analyzer.extra_gen[node] = frozenset(child_in_state,) self.analyzers[node] = analyzer self.current_analyzer = parent_analyzer return node class Annotator(transformer.Base): """AST visitor that annotates each control flow block with live symbols.""" # Note: additional nodes may be added as needed. def __init__(self, source_info, cross_function_analyzer): super(Annotator, self).__init__(source_info) self.cross_function_analyzer = cross_function_analyzer self.current_analyzer = None def visit(self, node): node = super(Annotator, self).visit(node) if (self.current_analyzer is not None and isinstance(node, gast.stmt) and node in self.current_analyzer.graph.index): cfg_node = self.current_analyzer.graph.index[node] anno.setanno(node, anno.Static.LIVE_VARS_IN, frozenset(self.current_analyzer.in_[cfg_node])) return node def visit_FunctionDef(self, node): parent_analyzer = self.current_analyzer self.current_analyzer = self.cross_function_analyzer.analyzers[node] node = self.generic_visit(node) self.current_analyzer = parent_analyzer return node def _block_statement_live_out(self, node): successors = self.current_analyzer.graph.stmt_next[node] stmt_live_out = set() for s in successors: stmt_live_out.update(self.current_analyzer.in_[s]) anno.setanno(node, anno.Static.LIVE_VARS_OUT, frozenset(stmt_live_out)) return node def _block_statement_live_in(self, node, entry_node): if entry_node in self.current_analyzer.graph.index: cfg_node = self.current_analyzer.graph.index[entry_node] stmt_live_in = frozenset(self.current_analyzer.in_[cfg_node]) else: assert anno.hasanno(entry_node, anno.Static.LIVE_VARS_IN), ( 'If not matching a CFG node, must be a block statement:' ' {}'.format(entry_node)) stmt_live_in = anno.getanno(entry_node, anno.Static.LIVE_VARS_IN) anno.setanno(node, anno.Static.LIVE_VARS_IN, stmt_live_in) return node def visit_If(self, node): node = self.generic_visit(node) node = self._block_statement_live_out(node) return self._block_statement_live_in(node, node.test) def visit_For(self, node): node = self.generic_visit(node) node = self._block_statement_live_out(node) return self._block_statement_live_in(node, node.iter) def visit_While(self, node): node = self.generic_visit(node) node = self._block_statement_live_out(node) return self._block_statement_live_in(node, node.test) def visit_Try(self, node): node = self.generic_visit(node) node = self._block_statement_live_out(node) return self._block_statement_live_in(node, node.body[0]) def visit_ExceptHandler(self, node): node = self.generic_visit(node) node = self._block_statement_live_out(node) return self._block_statement_live_in(node, node.body[0]) def visit_With(self, node): node = self.generic_visit(node) return self._block_statement_live_in(node, node.items[0]) def visit_Expr(self, node): node = self.generic_visit(node) cfg_node = self.current_analyzer.graph.index[node] anno.setanno(node, anno.Static.LIVE_VARS_OUT, frozenset(self.current_analyzer.out[cfg_node])) return node def resolve(node, source_info, graphs): """Resolves the live symbols at the exit of control flow statements. Args: node: ast.AST source_info: transformer.SourceInfo graphs: Dict[ast.FunctionDef, cfg.Graph] Returns: ast.AST """ cross_function_analyzer = WholeTreeAnalyzer(source_info, graphs) node = cross_function_analyzer.visit(node) visitor = Annotator(source_info, cross_function_analyzer) node = visitor.visit(node) return node
tensorflow-master
tensorflow/python/autograph/pyct/static_analysis/liveness.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for activity module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast import six from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import parser from tensorflow.python.autograph.pyct import qual_names from tensorflow.python.autograph.pyct import transformer from tensorflow.python.autograph.pyct.static_analysis import activity from tensorflow.python.autograph.pyct.static_analysis import annos from tensorflow.python.platform import test QN = qual_names.QN NodeAnno = annos.NodeAnno global_a = 7 global_b = 17 class ScopeTest(test.TestCase): def assertMissing(self, qn, scope): self.assertNotIn(qn, scope.read) self.assertNotIn(qn, scope.modified) def assertReadOnly(self, qn, scope): self.assertIn(qn, scope.read) self.assertNotIn(qn, scope.modified) def assertWriteOnly(self, qn, scope): self.assertNotIn(qn, scope.read) self.assertIn(qn, scope.modified) def assertReadWrite(self, qn, scope): self.assertIn(qn, scope.read) self.assertIn(qn, scope.modified) def test_basic(self): scope = activity.Scope(None) self.assertMissing(QN('foo'), scope) scope.mark_read(QN('foo')) self.assertReadOnly(QN('foo'), scope) scope.mark_modified(QN('foo')) self.assertReadWrite(QN('foo'), scope) def test_copy_from(self): scope = activity.Scope(None) scope.mark_modified(QN('foo')) other = activity.Scope(None) other.copy_from(scope) self.assertWriteOnly(QN('foo'), other) scope.mark_modified(QN('bar')) scope.copy_from(other) self.assertMissing(QN('bar'), scope) scope.mark_modified(QN('bar')) scope.merge_from(other) self.assertWriteOnly(QN('bar'), scope) self.assertMissing(QN('bar'), other) def test_copy_of(self): scope = activity.Scope(None) scope.mark_read(QN('foo')) other = activity.Scope.copy_of(scope) self.assertReadOnly(QN('foo'), other) child_scope = activity.Scope(scope) child_scope.mark_read(QN('bar')) other = activity.Scope.copy_of(child_scope) self.assertReadOnly(QN('bar'), other) def test_referenced(self): scope = activity.Scope(None) scope.mark_read(QN('a')) child = activity.Scope(scope) child.mark_read(QN('b')) child2 = activity.Scope(child, isolated=False) child2.mark_read(QN('c')) self.assertTrue(QN('c') in child2.referenced) self.assertTrue(QN('b') in child2.referenced) self.assertFalse(QN('a') in child2.referenced) self.assertTrue(QN('c') in child.referenced) self.assertTrue(QN('b') in child.referenced) self.assertFalse(QN('a') in child.referenced) class ActivityAnalyzerTestBase(test.TestCase): def _parse_and_analyze(self, test_fn): node, source = parser.parse_entity(test_fn, future_features=()) entity_info = transformer.EntityInfo( source_code=source, source_file=None, future_features=(), namespace={}) node = qual_names.resolve(node) ctx = transformer.Context(entity_info) node = activity.resolve(node, ctx) return node, entity_info def assertSymbolSetsAre(self, expected, actual, name): expected = set(expected) actual = set(str(s) for s in actual) self.assertSetEqual( expected, actual, 'for symbol set: %s\n' ' Expected: %s\n' ' Got: %s\n' ' Missing: %s\n' ' Extra: %s\n' % (name.upper(), expected, actual, expected - actual, actual - expected)) def assertScopeIs(self, scope, used, modified): """Assert the scope contains specific used, modified & created variables.""" self.assertSymbolSetsAre(used, scope.read, 'read') self.assertSymbolSetsAre(modified, scope.modified, 'modified') class ActivityAnalyzerTest(ActivityAnalyzerTestBase): def test_print_statement(self): def test_fn(a): b = 0 c = 1 print(a, b) return c node, _ = self._parse_and_analyze(test_fn) print_node = node.body[2] if isinstance(print_node, gast.Print): # Python 2 print_args_scope = anno.getanno(print_node, NodeAnno.ARGS_SCOPE) else: # Python 3 assert isinstance(print_node, gast.Expr) # The call node should be the one being annotated. print_node = print_node.value print_args_scope = anno.getanno(print_node, NodeAnno.ARGS_SCOPE) # We basically need to detect which variables are captured by the call # arguments. self.assertScopeIs(print_args_scope, ('a', 'b'), ()) def test_call_args(self): def test_fn(a): b = 0 c = 1 foo(a, b) # pylint:disable=undefined-variable return c node, _ = self._parse_and_analyze(test_fn) call_node = node.body[2].value # We basically need to detect which variables are captured by the call # arguments. self.assertScopeIs( anno.getanno(call_node, NodeAnno.ARGS_SCOPE), ('a', 'b'), ()) def test_call_args_attributes(self): def foo(*_): pass def test_fn(a): a.c = 0 foo(a.b, a.c) return a.d node, _ = self._parse_and_analyze(test_fn) call_node = node.body[1].value self.assertScopeIs( anno.getanno(call_node, NodeAnno.ARGS_SCOPE), ('a', 'a.b', 'a.c'), ()) def test_call_args_subscripts(self): def foo(*_): pass def test_fn(a): b = 1 c = 2 foo(a[0], a[b]) return a[c] node, _ = self._parse_and_analyze(test_fn) call_node = node.body[2].value self.assertScopeIs( anno.getanno(call_node, NodeAnno.ARGS_SCOPE), ('a', 'a[0]', 'a[b]', 'b'), ()) def test_while(self): def test_fn(a): b = a while b > 0: c = b b -= 1 return b, c node, _ = self._parse_and_analyze(test_fn) while_node = node.body[1] self.assertScopeIs( anno.getanno(while_node, NodeAnno.BODY_SCOPE), ('b',), ('b', 'c')) self.assertScopeIs( anno.getanno(while_node, NodeAnno.BODY_SCOPE).parent, ('a', 'b', 'c'), ('b', 'c')) self.assertScopeIs( anno.getanno(while_node, NodeAnno.COND_SCOPE), ('b',), ()) def test_for(self): def test_fn(a): b = a for _ in a: c = b b -= 1 return b, c node, _ = self._parse_and_analyze(test_fn) for_node = node.body[1] self.assertScopeIs( anno.getanno(for_node, NodeAnno.ITERATE_SCOPE), (), ('_')) self.assertScopeIs( anno.getanno(for_node, NodeAnno.BODY_SCOPE), ('b',), ('b', 'c')) self.assertScopeIs( anno.getanno(for_node, NodeAnno.BODY_SCOPE).parent, ('a', 'b', 'c'), ('b', 'c', '_')) def test_if(self): def test_fn(x): if x > 0: x = -x y = 2 * x z = -y else: x = 2 * x y = -x u = -y return z, u node, _ = self._parse_and_analyze(test_fn) if_node = node.body[0] self.assertScopeIs( anno.getanno(if_node, NodeAnno.BODY_SCOPE), ('x', 'y'), ('x', 'y', 'z')) self.assertScopeIs( anno.getanno(if_node, NodeAnno.BODY_SCOPE).parent, ('x', 'y', 'z', 'u'), ('x', 'y', 'z', 'u')) self.assertScopeIs( anno.getanno(if_node, NodeAnno.ORELSE_SCOPE), ('x', 'y'), ('x', 'y', 'u')) self.assertScopeIs( anno.getanno(if_node, NodeAnno.ORELSE_SCOPE).parent, ('x', 'y', 'z', 'u'), ('x', 'y', 'z', 'u')) def test_if_attributes(self): def test_fn(a): if a > 0: a.b = -a.c d = 2 * a else: a.b = a.c d = 1 return d node, _ = self._parse_and_analyze(test_fn) if_node = node.body[0] self.assertScopeIs( anno.getanno(if_node, NodeAnno.BODY_SCOPE), ('a', 'a.c'), ('a.b', 'd')) self.assertScopeIs( anno.getanno(if_node, NodeAnno.ORELSE_SCOPE), ('a', 'a.c'), ('a.b', 'd')) self.assertScopeIs( anno.getanno(if_node, NodeAnno.BODY_SCOPE).parent, ('a', 'a.c', 'd'), ('a.b', 'd')) def test_if_subscripts(self): def test_fn(a, b, c, e): if a > 0: a[b] = -a[c] d = 2 * a else: a[0] = e d = 1 return d node, _ = self._parse_and_analyze(test_fn) if_node = node.body[0] self.assertScopeIs( anno.getanno(if_node, NodeAnno.BODY_SCOPE), ('a', 'b', 'c', 'a[c]'), ('a[b]', 'd')) # TODO(mdan): Should subscript writes (a[0] = 1) be considered to read "a"? self.assertScopeIs( anno.getanno(if_node, NodeAnno.ORELSE_SCOPE), ('a', 'e'), ('a[0]', 'd')) self.assertScopeIs( anno.getanno(if_node, NodeAnno.ORELSE_SCOPE).parent, ('a', 'b', 'c', 'd', 'e', 'a[c]'), ('d', 'a[b]', 'a[0]')) def test_nested_if(self): def test_fn(b): if b > 0: if b < 5: a = b else: a = b * b return a node, _ = self._parse_and_analyze(test_fn) inner_if_node = node.body[0].body[0] self.assertScopeIs( anno.getanno(inner_if_node, NodeAnno.BODY_SCOPE), ('b',), ('a',)) self.assertScopeIs( anno.getanno(inner_if_node, NodeAnno.ORELSE_SCOPE), ('b',), ('a',)) def test_nested_function(self): def test_fn(a): def f(x): y = x * x return y b = a for i in a: c = b b -= f(i) return b, c node, _ = self._parse_and_analyze(test_fn) fn_def_node = node.body[0] self.assertScopeIs( anno.getanno(fn_def_node, NodeAnno.BODY_SCOPE), ('x', 'y'), ('y',)) def test_constructor_attributes(self): class TestClass(object): def __init__(self, a): self.b = a self.b.c = 1 node, _ = self._parse_and_analyze(TestClass) init_node = node.body[0] self.assertScopeIs( anno.getanno(init_node, NodeAnno.BODY_SCOPE), ('self', 'a', 'self.b'), ('self', 'self.b', 'self.b.c')) def test_aug_assign_subscripts(self): def test_fn(a): a[0] += 1 node, _ = self._parse_and_analyze(test_fn) fn_node = node self.assertScopeIs( anno.getanno(fn_node, NodeAnno.BODY_SCOPE), ('a', 'a[0]'), ('a[0]',)) def test_return_vars_are_read(self): def test_fn(a, b, c): # pylint: disable=unused-argument return c node, _ = self._parse_and_analyze(test_fn) fn_node = node self.assertScopeIs(anno.getanno(fn_node, NodeAnno.BODY_SCOPE), ('c',), ()) def test_aug_assign(self): def test_fn(a, b): a += b node, _ = self._parse_and_analyze(test_fn) fn_node = node self.assertScopeIs( anno.getanno(fn_node, NodeAnno.BODY_SCOPE), ('a', 'b'), ('a')) def test_aug_assign_rvalues(self): a = dict(bar=3) def foo(): return a def test_fn(x): foo()['bar'] += x node, _ = self._parse_and_analyze(test_fn) fn_node = node self.assertScopeIs( anno.getanno(fn_node, NodeAnno.BODY_SCOPE), ('foo', 'x'), ()) def test_params(self): def test_fn(a, b): # pylint: disable=unused-argument return b node, _ = self._parse_and_analyze(test_fn) fn_node = node body_scope = anno.getanno(fn_node, NodeAnno.BODY_SCOPE) self.assertScopeIs(body_scope, ('b',), ()) self.assertScopeIs(body_scope.parent, ('b',), ('a', 'b')) args_scope = anno.getanno(fn_node.args, anno.Static.SCOPE) self.assertSymbolSetsAre(('a', 'b'), args_scope.params.keys(), 'params') def test_lambda_captures_reads(self): def test_fn(a, b): return lambda: a + b node, _ = self._parse_and_analyze(test_fn) fn_node = node body_scope = anno.getanno(fn_node, NodeAnno.BODY_SCOPE) self.assertScopeIs(body_scope, ('a', 'b'), ()) # Nothing local to the lambda is tracked. self.assertSymbolSetsAre((), body_scope.params.keys(), 'params') def test_lambda_params_are_isolated(self): def test_fn(a, b): # pylint: disable=unused-argument return lambda a: a + b node, _ = self._parse_and_analyze(test_fn) fn_node = node body_scope = anno.getanno(fn_node, NodeAnno.BODY_SCOPE) self.assertScopeIs(body_scope, ('b',), ()) self.assertSymbolSetsAre((), body_scope.params.keys(), 'params') def test_lambda_complex(self): def test_fn(a, b, c, d): # pylint: disable=unused-argument a = (lambda a, b, c: a + b + c)(d, 1, 2) + b node, _ = self._parse_and_analyze(test_fn) fn_node = node body_scope = anno.getanno(fn_node, NodeAnno.BODY_SCOPE) self.assertScopeIs(body_scope, ('b', 'd'), ('a',)) self.assertSymbolSetsAre((), body_scope.params.keys(), 'params') def test_lambda_nested(self): def test_fn(a, b, c, d, e): # pylint: disable=unused-argument a = lambda a, b: d(lambda b: a + b + c) # pylint: disable=undefined-variable node, _ = self._parse_and_analyze(test_fn) fn_node = node body_scope = anno.getanno(fn_node, NodeAnno.BODY_SCOPE) self.assertScopeIs(body_scope, ('c', 'd'), ('a',)) self.assertSymbolSetsAre((), body_scope.params.keys(), 'params') def test_comprehension_targets_are_isolated(self): def test_fn(a): b = [c for c in a] # pylint:disable=unused-variable node, _ = self._parse_and_analyze(test_fn) fn_node = node body_scope = anno.getanno(fn_node, NodeAnno.BODY_SCOPE) if six.PY2: self.assertScopeIs(body_scope, ('a',), ('b', 'c')) else: self.assertScopeIs(body_scope, ('a',), ('b',)) def test_comprehension_targets_are_isolated_in_augassign(self): def test_fn(a, b): b += [c for c in a] # pylint:disable=unused-variable node, _ = self._parse_and_analyze(test_fn) fn_node = node body_scope = anno.getanno(fn_node, NodeAnno.BODY_SCOPE) if six.PY2: self.assertScopeIs(body_scope, ('a', 'b'), ('b', 'c')) else: self.assertScopeIs(body_scope, ('a', 'b'), ('b',)) def test_global_symbol(self): def test_fn(c): global global_a global global_b global_a = global_b + c node, _ = self._parse_and_analyze(test_fn) fn_node = node body_scope = anno.getanno(fn_node, NodeAnno.BODY_SCOPE) self.assertScopeIs(body_scope, ('global_b', 'c'), ('global_a',)) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/static_analysis/activity_test.py
# python3 # Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for liveness module, that only run in Python 3.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.autograph.pyct.static_analysis import annos from tensorflow.python.autograph.pyct.static_analysis import liveness_test from tensorflow.python.platform import test NodeAnno = annos.NodeAnno class LivenessAnalyzerTest(liveness_test.LivenessAnalyzerTestBase): """Tests which can only run in Python 3.""" def test_nonlocal_symbol(self): nonlocal_a = 3 nonlocal_b = 13 def test_fn(c): nonlocal nonlocal_a nonlocal nonlocal_b if nonlocal_a: nonlocal_b = c else: nonlocal_b = c return nonlocal_b node = self._parse_and_analyze(test_fn) fn_body = node.body self.assertHasLiveOut(fn_body[2], ('nonlocal_b',)) self.assertHasLiveIn(fn_body[2], ('nonlocal_a', 'c')) if __name__ == '__main__': test.main()
tensorflow-master
tensorflow/python/autograph/pyct/static_analysis/liveness_py3_test.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Activity analysis. Requires qualified name annotations (see qual_names.py). """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import weakref import gast import six from tensorflow.python.autograph.pyct import anno from tensorflow.python.autograph.pyct import qual_names from tensorflow.python.autograph.pyct import transformer from tensorflow.python.autograph.pyct.static_analysis.annos import NodeAnno class Scope(object): """Encloses local symbol definition and usage information. This can track for instance whether a symbol is modified in the current scope. Note that scopes do not necessarily align with Python's scopes. For example, the body of an if statement may be considered a separate scope. Caution - the AST references held by this object are weak. Attributes: modified: Set[qual_names.QN], identifiers modified in this scope read: Set[qual_names.QN], identifiers read in this scope deleted: Set[qual_names.QN], identifiers deleted in this scope params: WeakValueDictionary[qual_names.QN, ast.Node], function arguments visible in this scope, mapped to the function node that defines them Note - simple statements may never delete and modify a symbol at the same time. However, compound ones like if statements can. In that latter case, it's undefined whether the symbol is actually modified or deleted upon statement exit. Certain analyses like reaching definitions need to be careful about this. """ def __init__(self, parent, isolated=True, add_unknown_symbols=False): """Create a new scope. Args: parent: A Scope or None. isolated: Whether the scope is isolated, that is, whether variables modified in this scope should be considered modified in the parent scope. add_unknown_symbols: Whether to handle attributed and subscripts without having first seen the base name. E.g., analyzing the statement 'x.y = z' without first having seen 'x'. """ self.isolated = isolated self.parent = parent self.add_unknown_symbols = add_unknown_symbols self.modified = set() self.read = set() self.deleted = set() self.params = weakref.WeakValueDictionary() @property def affects_parent(self): return not self.isolated and self.parent is not None @property def referenced(self): if self.affects_parent: return self.read | self.parent.referenced return self.read def __repr__(self): return 'Scope{r=%s, w=%s}' % (tuple(self.read), tuple(self.modified)) def copy_from(self, other): """Recursively copies the contents of this scope from another scope.""" if (self.parent is None) != (other.parent is None): raise ValueError('cannot copy scopes of different structures') if other.parent is not None: self.parent.copy_from(other.parent) self.isolated = other.isolated self.modified = copy.copy(other.modified) self.read = copy.copy(other.read) self.params = copy.copy(other.params) @classmethod def copy_of(cls, other): if other.parent is not None: parent = cls.copy_of(other.parent) else: parent = None new_copy = cls(parent) new_copy.copy_from(other) return new_copy def merge_from(self, other): if (self.parent is None) != (other.parent is None): raise ValueError('cannot merge scopes of different structures') if other.parent is not None: self.parent.merge_from(other.parent) self.modified |= other.modified self.read |= other.read self.params.update(other.params) def mark_read(self, name): self.read.add(name) if self.parent is not None and name not in self.params: self.parent.mark_read(name) def mark_modified(self, name): self.modified.add(name) if self.affects_parent: self.parent.mark_modified(name) def mark_deleted(self, name): self.deleted.add(name) def mark_param(self, name, owner): # Assumption: all AST nodes have the same life span. This lets us use # a weak reference to mark the connection between a symbol node and the # function node whose argument that symbol is. self.params[name] = owner class _Lambda(object): no_root = True def __init__(self): self.args = set() class _Comprehension(object): no_root = True def __init__(self): self.targets = set() class ActivityAnalyzer(transformer.Base): """Annotates nodes with local scope information. See Scope. The use of this class requires that qual_names.resolve() has been called on the node. This class will ignore nodes have not been annotated with their qualified names. """ def __init__(self, context, parent_scope=None, add_unknown_symbols=False): super(ActivityAnalyzer, self).__init__(context) self.scope = Scope(parent_scope, None, add_unknown_symbols) # Note: all these flags crucially rely on the respective nodes are # leaves in the AST, that is, they cannot contain other statements. self._in_aug_assign = False self._in_function_def_args = False @property def _in_constructor(self): if len(self.enclosing_entities) > 1: innermost = self.enclosing_entities[-1] parent = self.enclosing_entities[-2] return isinstance(parent, gast.ClassDef) and innermost.name == '__init__' return False def _node_sets_self_attribute(self, node): if anno.hasanno(node, anno.Basic.QN): qn = anno.getanno(node, anno.Basic.QN) # TODO(mdan): The 'self' argument is not guaranteed to be called 'self'. if qn.has_attr and qn.parent.qn == ('self',): return True return False def _track_symbol(self, node, composite_writes_alter_parent=False): # A QN may be missing when we have an attribute (or subscript) on a function # call. Example: a().b if not anno.hasanno(node, anno.Basic.QN): return qn = anno.getanno(node, anno.Basic.QN) # When inside a lambda, ignore any of the lambda's arguments. # This includes attributes or slices of those arguments. for l in self.state[_Lambda]: if qn in l.args: return if qn.owner_set & set(l.args): return # When inside a comprehension, ignore reads to any of the comprehensions's # targets. This includes attributes or slices of those arguments. for l in self.state[_Comprehension]: if qn in l.targets: return if qn.owner_set & set(l.targets): return if isinstance(node.ctx, gast.Store): # In comprehensions, modified symbols are the comprehension targets. if self.state[_Comprehension].level > 0: self.state[_Comprehension].targets.add(qn) # Comprehension targets are completely isolated in Python 3. if six.PY2 or self.state[_Comprehension].level == 0: self.scope.mark_modified(qn) if qn.is_composite and composite_writes_alter_parent: self.scope.mark_modified(qn.parent) if self._in_aug_assign: self.scope.mark_read(qn) elif isinstance(node.ctx, gast.Load): self.scope.mark_read(qn) elif isinstance(node.ctx, gast.Param): if self._in_function_def_args: # In function defs have the meaning of defining a variable. self.scope.mark_modified(qn) self.scope.mark_param(qn, self.enclosing_entities[-1]) elif self.state[_Lambda].level: # In lambdas, they are tracked separately. self.state[_Lambda].args.add(qn) else: # TODO(mdan): Is this case possible at all? raise NotImplementedError( 'Param "{}" outside a function arguments or lambda.'.format(qn)) elif isinstance(node.ctx, gast.Del): # The read matches the Python semantics - attempting to delete an # undefined symbol is illegal. self.scope.mark_read(qn) self.scope.mark_deleted(qn) else: raise ValueError('Unknown context {} for node "{}".'.format( type(node.ctx), qn)) def _enter_scope(self, isolated): self.scope = Scope(self.scope, isolated=isolated) def _exit_scope(self): self.scope = self.scope.parent def _process_statement(self, node): self._enter_scope(False) node = self.generic_visit(node) anno.setanno(node, anno.Static.SCOPE, self.scope) self._exit_scope() return node def visit_Expr(self, node): return self._process_statement(node) def visit_Return(self, node): return self._process_statement(node) def visit_Assign(self, node): return self._process_statement(node) def visit_AugAssign(self, node): # Special rules for AugAssign. Here, the AST only shows the target as # written, when it is in fact also read. self._enter_scope(False) self._in_aug_assign = True node.target = self.visit(node.target) self._in_aug_assign = False node.op = self.visit(node.op) node.value = self.visit(node.value) anno.setanno(node, anno.Static.SCOPE, self.scope) self._exit_scope() return node def visit_Delete(self, node): return self._process_statement(node) def visit_Name(self, node): node = self.generic_visit(node) self._track_symbol(node) return node def visit_Attribute(self, node): node = self.generic_visit(node) if self._in_constructor and self._node_sets_self_attribute(node): self._track_symbol(node, composite_writes_alter_parent=True) else: self._track_symbol(node) return node def visit_Subscript(self, node): node = self.generic_visit(node) # Subscript writes (e.g. a[b] = "value") are considered to modify # both the element itself (a[b]) and its parent (a). self._track_symbol(node) return node def visit_Print(self, node): self._enter_scope(False) node.values = self.visit_block(node.values) anno.setanno(node, anno.Static.SCOPE, self.scope) anno.setanno(node, NodeAnno.ARGS_SCOPE, self.scope) self._exit_scope() return node def visit_Assert(self, node): return self._process_statement(node) def visit_Call(self, node): self._enter_scope(False) node.args = self.visit_block(node.args) node.keywords = self.visit_block(node.keywords) # TODO(mdan): Account starargs, kwargs anno.setanno(node, NodeAnno.ARGS_SCOPE, self.scope) self._exit_scope() node.func = self.visit(node.func) return node def _process_block_node(self, node, block, scope_name): self._enter_scope(False) block = self.visit_block(block) anno.setanno(node, scope_name, self.scope) self._exit_scope() return node def _process_parallel_blocks(self, parent, children): # Because the scopes are not isolated, processing any child block # modifies the parent state causing the other child blocks to be # processed incorrectly. So we need to checkpoint the parent scope so that # each child sees the same context. before_parent = Scope.copy_of(self.scope) after_children = [] for child, scope_name in children: self.scope.copy_from(before_parent) parent = self._process_block_node(parent, child, scope_name) after_child = Scope.copy_of(self.scope) after_children.append(after_child) for after_child in after_children: self.scope.merge_from(after_child) return parent def visit_Lambda(self, node): assert not self._in_function_def_args self.state[_Lambda].enter() node = self.generic_visit(node) self.state[_Lambda].exit() return node def _process_iterable_comprehension(self, node): # This handles ListComp, SetComp, GeneratorExp. self.state[_Comprehension].enter() # Note: it's important to visit the generators first to properly account # for the variables local to these generators. Example: `x` is local to the # expression `x for x in y`. # It is important to visit the generators in reverse order when targets of # outer comprehensions are accessed by inner generators. node.generators = self.visit_block(reversed(node.generators)) node.elt = self.visit(node.elt) self.state[_Comprehension].exit() return node def visit_comprehension(self, node): # It is important to visit the target first so that it's properly tracked as # comprehension target. node.target = self.visit(node.target) return self.generic_visit(node) def visit_DictComp(self, node): # Identical to _process_iterable_comprehension, different node names. self.state[_Comprehension].enter() node.generators = self.visit_block(node.generators) node.key = self.visit(node.key) node.value = self.visit(node.value) self.state[_Comprehension].exit() return node def visit_ListComp(self, node): return self._process_iterable_comprehension(node) def visit_SetComp(self, node): return self._process_iterable_comprehension(node) def visit_GeneratorExp(self, node): return self._process_iterable_comprehension(node) def visit_arguments(self, node): return self._process_statement(node) def visit_FunctionDef(self, node): # The FunctionDef node itself has a Scope object that tracks the creation # of its name, along with the usage of any decorator accompanying it. self._enter_scope(False) node.decorator_list = self.visit_block(node.decorator_list) self.scope.mark_modified(qual_names.QN(node.name)) anno.setanno(node, anno.Static.SCOPE, self.scope) self._exit_scope() # A separate Scope tracks the actual function definition. self._enter_scope(True) assert not (self._in_function_def_args or self.state[_Lambda].level) self._in_function_def_args = True node.args = self.visit(node.args) self._in_function_def_args = False # Track the body separately. This is for compatibility reasons, it may not # be strictly needed. self._enter_scope(False) node.body = self.visit_block(node.body) anno.setanno(node, NodeAnno.BODY_SCOPE, self.scope) self._exit_scope() self._exit_scope() return node def visit_With(self, node): self._enter_scope(False) node = self.generic_visit(node) anno.setanno(node, NodeAnno.BODY_SCOPE, self.scope) self._exit_scope() return node def visit_withitem(self, node): return self._process_statement(node) def visit_If(self, node): self._enter_scope(False) node.test = self.visit(node.test) anno.setanno(node, NodeAnno.COND_SCOPE, self.scope) anno.setanno(node.test, anno.Static.SCOPE, self.scope) self._exit_scope() node = self._process_parallel_blocks(node, ((node.body, NodeAnno.BODY_SCOPE), (node.orelse, NodeAnno.ORELSE_SCOPE))) return node def visit_For(self, node): self._enter_scope(False) node.target = self.visit(node.target) node.iter = self.visit(node.iter) anno.setanno(node.iter, anno.Static.SCOPE, self.scope) self._exit_scope() self._enter_scope(False) self.visit(node.target) anno.setanno(node, NodeAnno.ITERATE_SCOPE, self.scope) self._exit_scope() node = self._process_parallel_blocks(node, ((node.body, NodeAnno.BODY_SCOPE), (node.orelse, NodeAnno.ORELSE_SCOPE))) return node def visit_While(self, node): self._enter_scope(False) node.test = self.visit(node.test) anno.setanno(node, NodeAnno.COND_SCOPE, self.scope) anno.setanno(node.test, anno.Static.SCOPE, self.scope) self._exit_scope() node = self._process_parallel_blocks(node, ((node.body, NodeAnno.BODY_SCOPE), (node.orelse, NodeAnno.ORELSE_SCOPE))) return node def resolve(node, context, parent_scope=None): return ActivityAnalyzer(context, parent_scope).visit(node)
tensorflow-master
tensorflow/python/autograph/pyct/static_analysis/activity.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Static information resolution. This module contains utilities to help annotate AST nodes with as much runtime information as can be possibly extracted without actually executing the code, under that assumption that the context in which the code will run is known. Overall, the different analyses have the functions listed below: * activity: inventories symbols read, written to, params, etc. at different levels * liveness, reaching_definitions: dataflow analyses based on the program's CFG and using the symbol information gathered by activity analysis """ from __future__ import absolute_import from __future__ import division from __future__ import print_function
tensorflow-master
tensorflow/python/autograph/pyct/static_analysis/__init__.py