diff --git a/cpp/ast.py b/cpp/ast.py index 6d9b5a8..8d61ecd 100644 --- a/cpp/ast.py +++ b/cpp/ast.py @@ -767,14 +767,13 @@ def _generate_one(self, token): if last_token.name == '(': # If there is an assignment before the paren, # this is an expression, not a method. - if ( - temp_tokens[-1].name == '=' and - temp_tokens[-2].name != 'operator' - ): - new_temp = self._get_tokens_up_to(tokenize.SYNTAX, ';') - temp_tokens.append(last_token) - temp_tokens.extend(new_temp) - last_token = tokenize.Token(tokenize.SYNTAX, ';', 0, 0) + for i, elt in reversed(list(enumerate(temp_tokens))): + if elt.name == '=' and temp_tokens[i - 1].name != 'operator': + new_temp = self._get_tokens_up_to(tokenize.SYNTAX, ';') + temp_tokens.append(last_token) + temp_tokens.extend(new_temp) + last_token = tokenize.Token(tokenize.SYNTAX, ';', 0, 0) + break if last_token.name == '[': # Handle array, this isn't a method, unless it's an operator. diff --git a/test_ast.py b/test_ast.py index ab8fce8..ae1bd31 100755 --- a/test_ast.py +++ b/test_ast.py @@ -480,6 +480,16 @@ class AstBuilderIntegrationTest(unittest.TestCase): """ + def test_variable_initialization_with_function(self): + nodes = list(MakeBuilder('int value = fct();').generate()) + self.assertEqual(1, len(nodes)) + self.assertEqual(VariableDeclaration('value', Type('int'), initial_value='fct()'), nodes[0]) + + def test_variable_initialization_with_complex_expression(self): + nodes = list(MakeBuilder('int value = fct() + 42;').generate()) + self.assertEqual(1, len(nodes)) + self.assertEqual(VariableDeclaration('value', Type('int'), initial_value='fct()+42'), nodes[0]) + def test_function_one_argument_with_name(self): for argument in ('Foo f', 'const Foo f', 'Foo& f', 'const Foo& f'): code = 'void fct(%s);' % argument