| 1 | n/a | """Check for errs in the AST. |
|---|
| 2 | n/a | |
|---|
| 3 | n/a | The Python parser does not catch all syntax errors. Others, like |
|---|
| 4 | n/a | assignments with invalid targets, are caught in the code generation |
|---|
| 5 | n/a | phase. |
|---|
| 6 | n/a | |
|---|
| 7 | n/a | The compiler package catches some errors in the transformer module. |
|---|
| 8 | n/a | But it seems clearer to write checkers that use the AST to detect |
|---|
| 9 | n/a | errors. |
|---|
| 10 | 2 | """ |
|---|
| 11 | n/a | |
|---|
| 12 | 2 | from compiler import ast, walk |
|---|
| 13 | n/a | |
|---|
| 14 | 2 | def check(tree, multi=None): |
|---|
| 15 | 31 | v = SyntaxErrorChecker(multi) |
|---|
| 16 | 31 | walk(tree, v) |
|---|
| 17 | 31 | return v.errors |
|---|
| 18 | n/a | |
|---|
| 19 | 4 | class SyntaxErrorChecker: |
|---|
| 20 | 2 | """A visitor to find syntax errors in the AST.""" |
|---|
| 21 | n/a | |
|---|
| 22 | 2 | def __init__(self, multi=None): |
|---|
| 23 | n/a | """Create new visitor object. |
|---|
| 24 | n/a | |
|---|
| 25 | n/a | If optional argument multi is not None, then print messages |
|---|
| 26 | n/a | for each error rather than raising a SyntaxError for the |
|---|
| 27 | n/a | first. |
|---|
| 28 | n/a | """ |
|---|
| 29 | 31 | self.multi = multi |
|---|
| 30 | 31 | self.errors = 0 |
|---|
| 31 | n/a | |
|---|
| 32 | 2 | def error(self, node, msg): |
|---|
| 33 | 0 | self.errors = self.errors + 1 |
|---|
| 34 | 0 | if self.multi is not None: |
|---|
| 35 | 0 | print "%s:%s: %s" % (node.filename, node.lineno, msg) |
|---|
| 36 | n/a | else: |
|---|
| 37 | 0 | raise SyntaxError, "%s (%s:%s)" % (msg, node.filename, node.lineno) |
|---|
| 38 | n/a | |
|---|
| 39 | 2 | def visitAssign(self, node): |
|---|
| 40 | n/a | # the transformer module handles many of these |
|---|
| 41 | 971 | pass |
|---|
| 42 | n/a | ## for target in node.nodes: |
|---|
| 43 | n/a | ## if isinstance(target, ast.AssList): |
|---|
| 44 | n/a | ## if target.lineno is None: |
|---|
| 45 | n/a | ## target.lineno = node.lineno |
|---|
| 46 | n/a | ## self.error(target, "can't assign to list comprehension") |
|---|