示例#1
0
 public void popTemporaryModule(String moduleName) {
   synchronized (lockTemporaryModules) {
     if (temporaryModules == null) {
       return;
     }
     FastStack<IModule> stack = temporaryModules.get(moduleName);
     if (stack == null) {
       // try to make it null when possible
       temporaryModules = null;
       return;
     }
     try {
       stack.pop();
       if (stack.size() == 0) {
         temporaryModules.remove(moduleName);
       }
       if (temporaryModules.size() == 0) {
         // try to make it null when possible (so that we don't have to sync later on)
         temporaryModules = null;
       }
     } catch (Exception e) {
       Log.log(e);
     }
   }
 }
示例#2
0
  /**
   * @param request this is the request for the completion
   * @param theList OUT - returned completions are added here. (IToken instances)
   * @param getOnlySupers whether we should only get things from super classes (in this case, we
   *     won't get things from the current class)
   * @param checkIfInCorrectScope if true, we'll first check if we're in a scope that actually has a
   *     method with 'self' or 'cls'
   * @return true if we actually tried to get the completions for self or cls.
   * @throws MisconfigurationException
   */
  @SuppressWarnings("unchecked")
  public static boolean getSelfOrClsCompletions(
      CompletionRequest request,
      List theList,
      ICompletionState state,
      boolean getOnlySupers,
      boolean checkIfInCorrectScope,
      String lookForRep)
      throws MisconfigurationException {

    SimpleNode s =
        PyParser.reparseDocument(
                new PyParser.ParserInfo(request.doc, true, request.nature, state.getLine()))
            .o1;
    if (s != null) {
      FindScopeVisitor visitor = new FindScopeVisitor(state.getLine(), 0);
      try {
        s.accept(visitor);
        if (checkIfInCorrectScope) {
          boolean scopeCorrect = false;

          FastStack<SimpleNode> scopeStack = visitor.scope.getScopeStack();
          for (Iterator<SimpleNode> it = scopeStack.topDownIterator();
              scopeCorrect == false && it.hasNext(); ) {
            SimpleNode node = it.next();
            if (node instanceof FunctionDef) {
              FunctionDef funcDef = (FunctionDef) node;
              if (funcDef.args != null
                  && funcDef.args.args != null
                  && funcDef.args.args.length > 0) {
                // ok, we have some arg, let's check for self or cls
                String rep = NodeUtils.getRepresentationString(funcDef.args.args[0]);
                if (rep != null && (rep.equals("self") || rep.equals("cls"))) {
                  scopeCorrect = true;
                }
              }
            }
          }
          if (!scopeCorrect) {
            return false;
          }
        }
        if (lookForRep.equals("self")) {
          state.setLookingFor(ICompletionState.LOOKING_FOR_INSTANCED_VARIABLE);
        } else {
          state.setLookingFor(ICompletionState.LOOKING_FOR_CLASSMETHOD_VARIABLE);
        }
        getSelfOrClsCompletions(visitor.scope, request, theList, state, getOnlySupers);
      } catch (Exception e1) {
        PydevPlugin.log(e1);
      }
      return true;
    }
    return false;
  }
  /**
   * @see
   *     org.python.pydev.parser.jython.ast.VisitorBase#visitClassDef(org.python.pydev.parser.jython.ast.ClassDef)
   */
  public Object visitClassDef(ClassDef node) throws Exception {
    globalDeclarationsStack.push(new HashSet<String>());
    defsStack.push(node);

    node.traverse(this);

    defsStack.pop();
    globalDeclarationsStack.pop();

    checkDeclaration(node, (NameTok) node.name);
    return null;
  }
示例#4
0
 public void pushTemporaryModule(String moduleName, IModule module) {
   synchronized (lockTemporaryModules) {
     if (temporaryModules == null) {
       temporaryModules = new HashMap<String, FastStack<IModule>>();
     }
     FastStack<IModule> stack = temporaryModules.get(moduleName);
     if (stack == null) {
       stack = new FastStack<IModule>(3); // small initial size!
       temporaryModules.put(moduleName, stack);
     }
     stack.push(module);
   }
 }
  /**
   * @see
   *     org.python.pydev.parser.jython.ast.VisitorBase#visitFunctionDef(org.python.pydev.parser.jython.ast.FunctionDef)
   */
  public Object visitFunctionDef(FunctionDef node) throws Exception {
    globalDeclarationsStack.push(new HashSet<String>());
    defsStack.push(node);

    if (node.args != null && node.args.args != null) {
      for (exprType arg : node.args.args) {
        if (arg instanceof Name) {
          checkParam((Name) arg);
        }
      }
    }
    node.traverse(this);

    defsStack.pop();
    globalDeclarationsStack.pop();

    checkDeclaration(node, (NameTok) node.name);
    return null;
  }
  public AbstractContextVisitor(
      ModuleAdapter module, AbstractNodeAdapter<? extends SimpleNode> parent) {
    super();
    assert (module != null);

    this.moduleAdapter = module;

    nodeHelper = new NodeHelper(module.getAdapterPrefs());

    stack = new FastStack<SimpleNode>();
    parents = new FastStack<AbstractScopeNode<?>>();
    parents.push(moduleAdapter);
    stack.push(module.getASTNode());

    nodes = new ArrayList<T>();
  }
  /**
   * @param lastMayBeMethod if true, it gets the path and accepts a method (if it is the last in the
   *     stack) if false, null is returned if a method is found.
   * @param tempStack is a temporary stack object (which may be cleared)
   * @return a tuple, where the first element is the path where the entry is located (may return
   *     null). and the second element is a boolen that indicates if the last was actually a method
   *     or not.
   */
  private Tuple<String, Boolean> getPathToRoot(
      ASTEntry entry, boolean lastMayBeMethod, boolean acceptAny, FastStack<SimpleNode> tempStack) {
    if (entry.parent == null) {
      return null;
    }
    // just to be sure that it's empty
    tempStack.clear();

    boolean lastIsMethod = false;
    // if the last 'may be a method', in this case, we have to remember that it will actually be the
    // first one
    // to be analyzed.

    // let's get the stack
    while (entry.parent != null) {
      if (entry.parent.node instanceof ClassDef) {
        tempStack.push(entry.parent.node);

      } else if (entry.parent.node instanceof FunctionDef) {
        if (!acceptAny) {
          if (lastIsMethod) {
            // already found a method
            return null;
          }

          if (!lastMayBeMethod) {
            return null;
          }

          // ok, the last one may be a method... (in this search, it MUST be the first one...)
          if (tempStack.size() != 0) {
            return null;
          }
        }

        // ok, there was a class, so, let's go and set it
        tempStack.push(entry.parent.node);
        lastIsMethod = true;

      } else {
        return null;
      }
      entry = entry.parent;
    }

    // now that we have the stack, let's make it into a path...
    FastStringBuffer buf = new FastStringBuffer();
    while (tempStack.size() > 0) {
      if (buf.length() > 0) {
        buf.append(".");
      }
      buf.append(NodeUtils.getRepresentationString(tempStack.pop()));
    }
    return new Tuple<String, Boolean>(buf.toString(), lastIsMethod);
  }
 protected AbstractNodeAdapter<? extends SimpleNode> before(SimpleNode node) {
   AbstractNodeAdapter<? extends SimpleNode> context = createContext(node);
   stack.push(node);
   return context;
 }
 protected void after() {
   stack.pop();
 }
示例#10
0
  /**
   * This method returns the module that corresponds to the path passed as a parameter.
   *
   * @param name the name of the module we're looking for (e.g.: mod1.mod2)
   * @param dontSearchInit is used in a negative form because initially it was isLookingForRelative,
   *     but it actually defines if we should look in __init__ modules too, so, the name matches the
   *     old signature.
   *     <p>NOTE: isLookingForRelative description was: when looking for relative imports, we don't
   *     check for __init__
   * @return the module represented by this name
   */
  protected IModule getModule(
      boolean acceptCompiledModule, String name, IPythonNature nature, boolean dontSearchInit) {
    if (temporaryModules != null) {
      synchronized (lockTemporaryModules) {
        if (temporaryModules != null) {
          // who knows, maybe it became null at that point.
          FastStack<IModule> stack = temporaryModules.get(name);
          if (stack != null && stack.size() > 0) {
            if (DEBUG_TEMPORARY_MODULES) {
              System.out.println("Returning temporary module: " + name);
            }
            return stack.peek();
          }
        }
      }
    }
    AbstractModule n = null;
    ModulesKey keyForCacheAccess = new ModulesKey(null, null);

    if (!dontSearchInit) {
      if (n == null) {
        keyForCacheAccess.name = new StringBuffer(name).append(".__init__").toString();
        n = cache.getObj(keyForCacheAccess, this);
        if (n != null) {
          name += ".__init__";
        }
      }
    }
    if (n == null) {
      keyForCacheAccess.name = name;
      n = cache.getObj(keyForCacheAccess, this);
    }

    if (n instanceof SourceModule) {
      // ok, module exists, let's check if it is synched with the filesystem version...
      SourceModule s = (SourceModule) n;
      if (!s.isSynched()) {
        // change it for an empty and proceed as usual.
        n = (AbstractModule) addModule(createModulesKey(s.getName(), s.getFile()));
      }
    }

    if (n instanceof EmptyModule) {
      EmptyModule e = (EmptyModule) n;

      boolean found = false;

      if (!found && e.f != null) {

        if (!e.f.exists()) {
          // if the file does not exist anymore, just remove it.
          keyForCacheAccess.name = name;
          keyForCacheAccess.file = e.f;
          doRemoveSingleModule(keyForCacheAccess);
          n = null;

        } else {
          // file exists
          n = checkOverride(name, nature, n);

          if (n instanceof EmptyModule) {
            // ok, handle case where the file is actually from a zip file...
            if (e instanceof EmptyModuleForZip) {
              EmptyModuleForZip emptyModuleForZip = (EmptyModuleForZip) e;

              if (emptyModuleForZip.pathInZip.endsWith(".class") || !emptyModuleForZip.isFile) {
                // handle java class... (if it's a class or a folder in a jar)
                n = JythonModulesManagerUtils.createModuleFromJar(emptyModuleForZip);
                n = decorateModule(n, nature);

              } else if (FileTypesPreferencesPage.isValidDll(emptyModuleForZip.pathInZip)) {
                // .pyd
                n = new CompiledModule(name, IToken.TYPE_BUILTIN, nature.getAstManager());
                n = decorateModule(n, nature);

              } else if (PythonPathHelper.isValidSourceFile(emptyModuleForZip.pathInZip)) {
                // handle python file from zip... we have to create it getting the contents from the
                // zip file
                try {
                  IDocument doc =
                      REF.getDocFromZip(emptyModuleForZip.f, emptyModuleForZip.pathInZip);
                  // NOTE: The nature (and so the grammar to be used) must be defined by this
                  // modules
                  // manager (and not by the initial caller)!!
                  n =
                      AbstractModule.createModuleFromDoc(
                          name, emptyModuleForZip.f, doc, this.getNature(), -1, false);
                  SourceModule zipModule = (SourceModule) n;
                  zipModule.zipFilePath = emptyModuleForZip.pathInZip;
                  n = decorateModule(n, nature);
                } catch (Exception exc1) {
                  PydevPlugin.log(exc1);
                  n = null;
                }
              }

            } else {
              // regular case... just go on and create it.
              try {
                // NOTE: The nature (and so the grammar to be used) must be defined by this modules
                // manager (and not by the initial caller)!!
                n = AbstractModule.createModule(name, e.f, this.getNature(), -1);
                n = decorateModule(n, nature);
              } catch (IOException exc) {
                keyForCacheAccess.name = name;
                keyForCacheAccess.file = e.f;
                doRemoveSingleModule(keyForCacheAccess);
                n = null;
              } catch (MisconfigurationException exc) {
                PydevPlugin.log(exc);
                n = null;
              }
            }
          }
        }

      } else { // ok, it does not have a file associated, so, we treat it as a builtin (this can
               // happen in java jars)
        n = checkOverride(name, nature, n);
        if (n instanceof EmptyModule) {
          if (acceptCompiledModule) {
            n = new CompiledModule(name, IToken.TYPE_BUILTIN, nature.getAstManager());
            n = decorateModule(n, nature);
          } else {
            return null;
          }
        }
      }

      if (n != null) {
        doAddSingleModule(createModulesKey(name, e.f), n);
      } else {
        System.err.println("The module " + name + " could not be found nor created!");
      }
    }

    if (n instanceof EmptyModule) {
      throw new RuntimeException("Should not be an empty module anymore!");
    }
    if (n instanceof SourceModule) {
      SourceModule sourceModule = (SourceModule) n;
      // now, here's a catch... it may be a bootstrap module...
      if (sourceModule.isBootstrapModule()) {
        // if it's a bootstrap module, we must replace it for the related compiled module.
        n = new CompiledModule(name, IToken.TYPE_BUILTIN, nature.getAstManager());
        n = decorateModule(n, nature);
      }
    }

    return n;
  }