Paweł Hajdan, Jr | e2f9feec | 2017-05-09 10:04:02 +0200 | [diff] [blame] | 1 | # Copyright 2017 The Chromium Authors. All rights reserved. |
| 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
| 5 | import ast |
| 6 | |
| 7 | |
| 8 | def _gclient_eval(node_or_string, global_scope, filename='<unknown>'): |
| 9 | """Safely evaluates a single expression. Returns the result.""" |
| 10 | _allowed_names = {'None': None, 'True': True, 'False': False} |
| 11 | if isinstance(node_or_string, basestring): |
| 12 | node_or_string = ast.parse(node_or_string, filename=filename, mode='eval') |
| 13 | if isinstance(node_or_string, ast.Expression): |
| 14 | node_or_string = node_or_string.body |
| 15 | def _convert(node): |
| 16 | if isinstance(node, ast.Str): |
| 17 | return node.s |
| 18 | elif isinstance(node, ast.Tuple): |
| 19 | return tuple(map(_convert, node.elts)) |
| 20 | elif isinstance(node, ast.List): |
| 21 | return list(map(_convert, node.elts)) |
| 22 | elif isinstance(node, ast.Dict): |
| 23 | return dict((_convert(k), _convert(v)) |
| 24 | for k, v in zip(node.keys, node.values)) |
| 25 | elif isinstance(node, ast.Name): |
| 26 | if node.id not in _allowed_names: |
| 27 | raise ValueError( |
| 28 | 'invalid name %r (file %r, line %s)' % ( |
| 29 | node.id, filename, getattr(node, 'lineno', '<unknown>'))) |
| 30 | return _allowed_names[node.id] |
| 31 | elif isinstance(node, ast.Call): |
| 32 | if not isinstance(node.func, ast.Name): |
| 33 | raise ValueError( |
| 34 | 'invalid call: func should be a name (file %r, line %s)' % ( |
| 35 | filename, getattr(node, 'lineno', '<unknown>'))) |
| 36 | if node.keywords or node.starargs or node.kwargs: |
| 37 | raise ValueError( |
| 38 | 'invalid call: use only regular args (file %r, line %s)' % ( |
| 39 | filename, getattr(node, 'lineno', '<unknown>'))) |
| 40 | args = map(_convert, node.args) |
| 41 | return global_scope[node.func.id](*args) |
| 42 | elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): |
| 43 | return _convert(node.left) + _convert(node.right) |
| 44 | else: |
| 45 | raise ValueError( |
| 46 | 'unexpected AST node: %s (file %r, line %s)' % ( |
| 47 | node, filename, getattr(node, 'lineno', '<unknown>'))) |
| 48 | return _convert(node_or_string) |
| 49 | |
| 50 | |
| 51 | def _gclient_exec(node_or_string, global_scope, filename='<unknown>'): |
| 52 | """Safely execs a set of assignments. Returns resulting scope.""" |
| 53 | result_scope = {} |
| 54 | |
| 55 | if isinstance(node_or_string, basestring): |
| 56 | node_or_string = ast.parse(node_or_string, filename=filename, mode='exec') |
| 57 | if isinstance(node_or_string, ast.Expression): |
| 58 | node_or_string = node_or_string.body |
| 59 | |
| 60 | def _visit_in_module(node): |
| 61 | if isinstance(node, ast.Assign): |
| 62 | if len(node.targets) != 1: |
| 63 | raise ValueError( |
| 64 | 'invalid assignment: use exactly one target (file %r, line %s)' % ( |
| 65 | filename, getattr(node, 'lineno', '<unknown>'))) |
| 66 | target = node.targets[0] |
| 67 | if not isinstance(target, ast.Name): |
| 68 | raise ValueError( |
| 69 | 'invalid assignment: target should be a name (file %r, line %s)' % ( |
| 70 | filename, getattr(node, 'lineno', '<unknown>'))) |
| 71 | value = _gclient_eval(node.value, global_scope, filename=filename) |
| 72 | |
| 73 | if target.id in result_scope: |
| 74 | raise ValueError( |
| 75 | 'invalid assignment: overrides var %r (file %r, line %s)' % ( |
| 76 | target.id, filename, getattr(node, 'lineno', '<unknown>'))) |
| 77 | |
| 78 | result_scope[target.id] = value |
| 79 | else: |
| 80 | raise ValueError( |
| 81 | 'unexpected AST node: %s (file %r, line %s)' % ( |
| 82 | node, filename, getattr(node, 'lineno', '<unknown>'))) |
| 83 | |
| 84 | if isinstance(node_or_string, ast.Module): |
| 85 | for stmt in node_or_string.body: |
| 86 | _visit_in_module(stmt) |
| 87 | else: |
| 88 | raise ValueError( |
| 89 | 'unexpected AST node: %s (file %r, line %s)' % ( |
| 90 | node_or_string, |
| 91 | filename, |
| 92 | getattr(node_or_string, 'lineno', '<unknown>'))) |
| 93 | |
| 94 | return result_scope |
| 95 | |
| 96 | |
| 97 | class CheckFailure(Exception): |
| 98 | """Contains details of a check failure.""" |
| 99 | def __init__(self, msg, path, exp, act): |
| 100 | super(CheckFailure, self).__init__(msg) |
| 101 | self.path = path |
| 102 | self.exp = exp |
| 103 | self.act = act |
| 104 | |
| 105 | |
| 106 | def Check(content, path, global_scope, expected_scope): |
| 107 | """Cross-checks the old and new gclient eval logic. |
| 108 | |
| 109 | Safely execs |content| (backed by file |path|) using |global_scope|, |
| 110 | and compares with |expected_scope|. |
| 111 | |
| 112 | Throws CheckFailure if any difference between |expected_scope| and scope |
| 113 | returned by new gclient eval code is detected. |
| 114 | """ |
| 115 | def fail(prefix, exp, act): |
| 116 | raise CheckFailure( |
| 117 | 'gclient check for %s: %s exp %s, got %s' % ( |
| 118 | path, prefix, repr(exp), repr(act)), prefix, exp, act) |
| 119 | |
| 120 | def compare(expected, actual, var_path, actual_scope): |
| 121 | if isinstance(expected, dict): |
| 122 | exp = set(expected.keys()) |
| 123 | act = set(actual.keys()) |
| 124 | if exp != act: |
| 125 | fail(var_path, exp, act) |
| 126 | for k in expected: |
| 127 | compare(expected[k], actual[k], var_path + '["%s"]' % k, actual_scope) |
| 128 | return |
| 129 | elif isinstance(expected, list): |
| 130 | exp = len(expected) |
| 131 | act = len(actual) |
| 132 | if exp != act: |
| 133 | fail('len(%s)' % var_path, expected_scope, actual_scope) |
| 134 | for i in range(exp): |
| 135 | compare(expected[i], actual[i], var_path + '[%d]' % i, actual_scope) |
| 136 | else: |
| 137 | if expected != actual: |
| 138 | fail(var_path, expected_scope, actual_scope) |
| 139 | |
| 140 | result_scope = _gclient_exec(content, global_scope, filename=path) |
| 141 | |
| 142 | compare(expected_scope, result_scope, '', result_scope) |