From 75b44b3437e3ff6686629cdbffc2368e43e38ae0 Mon Sep 17 00:00:00 2001 From: Mark Dickinson Date: Sun, 4 Jul 2010 16:47:56 +0000 Subject: [PATCH] Issue #9130: Fix validation of relative imports in parser module. --- Lib/test/test_parser.py | 20 ++++++++++++++++++++ Misc/NEWS | 2 ++ Modules/parsermodule.c | 7 ++++--- 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/Lib/test/test_parser.py b/Lib/test/test_parser.py index a964877e317..e208d53cb54 100644 --- a/Lib/test/test_parser.py +++ b/Lib/test/test_parser.py @@ -221,6 +221,12 @@ class RoundtripLegalSyntaxTestCase(unittest.TestCase): self.check_suite("import sys as system, math") self.check_suite("import sys, math as my_math") + def test_relative_imports(self): + self.check_suite("from . import name") + self.check_suite("from .. import name") + self.check_suite("from .pkg import name") + self.check_suite("from ..pkg import name") + def test_pep263(self): self.check_suite("# -*- coding: iso-8859-1 -*-\n" "pass\n") @@ -519,6 +525,20 @@ class IllegalSyntaxTestCase(unittest.TestCase): (0, '')) self.check_bad_tree(tree, "malformed global ast") + def test_missing_import_source(self): + # from import a + tree = \ + (257, + (267, + (268, + (269, + (281, + (283, (1, 'from'), (1, 'import'), + (286, (284, (1, 'fred')))))), + (4, ''))), + (4, ''), (0, '')) + self.check_bad_tree(tree, "from import a") + class CompileTestCase(unittest.TestCase): diff --git a/Misc/NEWS b/Misc/NEWS index 3a867a5d62b..5419617b0f0 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -16,6 +16,8 @@ Core and Builtins Library ------- +- Issue #9130: Fix validation of relative imports in parser module. + - Issue #9128: Fix validation of class decorators in parser module. Extension Modules diff --git a/Modules/parsermodule.c b/Modules/parsermodule.c index 4a581d75867..f0ac5e92906 100644 --- a/Modules/parsermodule.c +++ b/Modules/parsermodule.c @@ -1886,8 +1886,8 @@ count_from_dots(node *tree) return i-1; } -/* 'from' ('.'* dotted_name | '.') 'import' ('*' | '(' import_as_names ')' | - * import_as_names +/* import_from: ('from' ('.'* dotted_name | '.'+) + * 'import' ('*' | '(' import_as_names ')' | import_as_names)) */ static int validate_import_from(node *tree) @@ -1897,7 +1897,8 @@ validate_import_from(node *tree) int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name); int offset = ndots + havename; int res = validate_ntype(tree, import_from) - && (nch >= 4 + ndots) + && (offset >= 1) + && (nch >= 3 + offset) && validate_name(CHILD(tree, 0), "from") && (!havename || validate_dotted_name(CHILD(tree, ndots + 1))) && validate_name(CHILD(tree, offset + 1), "import");