1 3 package org.python.compiler; 4 5 import org.python.parser.*; 6 import org.python.parser.ast.*; 7 import org.python.parser.ast.Module; 8 9 public class Future extends Object implements PythonGrammarTreeConstants { 10 11 private boolean division; 12 private boolean generators; 13 14 private static final String FUTURE = "__future__"; 15 16 private boolean check(ImportFrom cand) throws Exception { 17 if (!cand.module.equals(FUTURE)) 18 return false; 19 int n = cand.names.length; 20 if (n == 0) { 21 throw new ParseException( 22 "future statement does not support import *",cand); 23 } 24 for (int i = 0; i < n; i++) { 25 String feature = cand.names[i].name; 26 if (feature.equals("nested_scopes")) { 28 continue; 29 } 30 if (feature.equals("division")) { 31 division = true; 32 continue; 33 } 34 if (feature.equals("generators")) { 35 generators = true; 36 continue; 37 } 38 throw new ParseException("future feature "+feature+ 39 " is not defined",cand); 40 } 41 return true; 42 } 43 44 public void preprocessFutures(modType node, 45 org.python.core.CompilerFlags cflags) 46 throws Exception 47 { 48 if (cflags != null) { 49 division = cflags.division; 50 } 51 int beg = 0; 52 stmtType[] suite = null; 53 if (node instanceof Module) { 54 suite = ((Module) node).body; 55 if (suite.length > 0 && suite[0] instanceof Expr && 56 ((Expr) suite[0]).value instanceof Str) { 57 beg++; 58 } 59 } else if (node instanceof Interactive) { 60 suite = ((Interactive) node).body; 61 } else { 62 return; 63 } 64 65 for (int i = beg; i < suite.length; i++) { 66 stmtType stmt = suite[i]; 67 if (!(stmt instanceof ImportFrom)) 68 break; 69 stmt.from_future_checked = true; 70 if (!check((ImportFrom) stmt)) 71 break; 72 } 73 74 if (cflags != null) { 75 cflags.division = cflags.division || division; 76 } 77 if (cflags != null) { 78 cflags.generator_allowed = cflags.generator_allowed || generators; 79 } 80 } 81 82 83 public static void checkFromFuture(ImportFrom node) throws Exception { 84 if (node.from_future_checked) 85 return; 86 if (node.module.equals(FUTURE)) { 87 throw new ParseException("from __future__ imports must occur " + 88 "at the beginning of the file",node); 89 } 90 node.from_future_checked = true; 91 } 92 93 public boolean areDivisionOn() { 94 return division; 95 } 96 97 } 98 | Popular Tags |