예제 #1
0
  public static PyString SyntaxError__str__(PyObject self, PyObject[] arg, String[] kwargs) {
    PyObject msg = self.__getattr__("msg");
    PyObject str = msg.__str__();
    if (!(msg instanceof PyString)) {
      return Py.newString(str.toString());
    }

    PyObject filename = self.__findattr__("filename");
    PyObject lineno = self.__findattr__("lineno");
    boolean haveFilename = filename instanceof PyString;
    boolean haveLieno = lineno instanceof PyInteger;
    if (!haveFilename && !haveLieno) {
      return (PyString) str;
    }

    String result;
    if (haveFilename && haveLieno) {
      result =
          String.format("%s (%s, line %d)", str, basename(filename.toString()), lineno.asInt());
    } else if (haveFilename) {
      result = String.format("%s (%s)", str, basename(filename.toString()));
    } else {
      result = String.format("%s (line %d)", str, lineno.asInt());
    }

    return Py.newString(result);
  }
  public void run() {
    boolean eof = false;
    JavaCharStream stream = new JavaCharStream(in, 1, 1);

    exec("_ps1 = sys.ps1");
    PyObject ps1Obj = get("_ps1");
    String ps1 = ps1Obj.toString();

    exec("_ps2 = sys.ps2");
    PyObject ps2Obj = get("_ps2");
    String ps2 = ps2Obj.toString();
    out.print(getDefaultBanner() + "\n");

    out.print(ps1);
    String line = "";

    while (!eof) {
      // try to sync up the console
      System.out.flush();
      System.err.flush();
      Thread.yield(); // this helps a little

      try {
        boolean eol = false;
        line = "";

        while (!eol) {
          char aChar = stream.readChar();
          eol = (aChar == '\n');
          if (!eol) line = line + aChar;
        }

        // hitting Enter at prompt returns a semicolon
        // get rid of it since it returns an error when executed
        if (line.equals(";")) line = "";

        {
          boolean retVal = push(line);

          if (retVal) {
            out.print(ps2);
          } else {
            out.print(ps1);
          }
        }
      } catch (IOException ex) {
      }
    }
  }
예제 #3
0
 @Override
 protected Class<?> findClass(String name) throws ClassNotFoundException {
   PySystemState sys = Py.getSystemState();
   ClassLoader sysClassLoader = sys.getClassLoader();
   if (sysClassLoader != null) {
     // sys.classLoader overrides this class loader!
     return sysClassLoader.loadClass(name);
   }
   // Search the sys.path for a .class file matching the named class.
   PyList path = sys.path;
   for (int i = 0; i < path.__len__(); i++) {
     byte[] buffer;
     PyObject entry = replacePathItem(sys, i, path);
     if (entry instanceof SyspathArchive) {
       SyspathArchive archive = (SyspathArchive) entry;
       buffer = getBytesFromArchive(archive, name);
     } else {
       if (!(entry instanceof PyUnicode)) {
         entry = entry.__str__();
       }
       String dir = entry.toString();
       buffer = getBytesFromDir(dir, name);
     }
     if (buffer != null) {
       definePackageForClass(name);
       return defineClass(name, buffer, 0, buffer.length);
     }
   }
   // couldn't find the .class file on sys.path
   throw new ClassNotFoundException(name);
 }
예제 #4
0
  public static PyString UnicodeTranslateError__str__(
      PyObject self, PyObject[] args, String[] kwargs) {
    int start = self.__getattr__("start").asInt();
    int end = self.__getattr__("end").asInt();
    // Get reason as a string, which it might not be if it's been modified after we
    // were contructed
    PyObject reason = self.__getattr__("reason").__str__();
    PyObject object = getUnicode(self.__getattr__("object"), "object");

    String result;
    if (start < object.__len__() && end == (start + 1)) {
      int badchar = object.toString().codePointAt(start);
      String badCharStr;
      if (badchar <= 0xff) {
        badCharStr = String.format("x%02x", badchar);
      } else if (badchar <= 0xffff) {
        badCharStr = String.format("u%04x", badchar);
      } else {
        badCharStr = String.format("U%08x", badchar);
      }
      result =
          String.format(
              "can't translate character u'\\%s' in position %d: %.400s",
              badCharStr, start, reason);
    } else {
      result =
          String.format(
              "can't translate characters in position %d-%d: %.400s", start, end - 1, reason);
    }
    return Py.newString(result);
  }
예제 #5
0
  public static PyString UnicodeDecodeError__str__(
      PyObject self, PyObject[] args, String[] kwargs) {
    int start = self.__getattr__("start").asInt();
    int end = self.__getattr__("end").asInt();
    // Get reason and encoding as strings, which they might not be if they've been
    // modified after we were contructed
    PyObject reason = self.__getattr__("reason").__str__();
    PyObject encoding = self.__getattr__("encoding").__str__();
    PyObject object = getString(self.__getattr__("object"), "object");

    String result;
    if (start < object.__len__() && end == (start + 1)) {
      int badByte = (object.toString().charAt(start)) & 0xff;
      result =
          String.format(
              "'%.400s' codec can't decode byte 0x%x in position %d: %.400s",
              encoding, badByte, start, reason);
    } else {
      result =
          String.format(
              "'%.400s' codec can't decode bytes in position %d-%d: %.400s",
              encoding, start, end - 1, reason);
    }
    return Py.newString(result);
  }
예제 #6
0
  final void file_writelines(PyObject a) {
    PyObject iter = Py.iter(a, "writelines() requires an iterable argument");

    PyObject item = null;
    while ((item = iter.__iternext__()) != null) {
      if (!(item instanceof PyString))
        throw Py.TypeError("writelines() argument must be a " + "sequence of strings");
      write(item.toString());
    }
  }
예제 #7
0
 /** Evaluate a boolean expression. */
 protected synchronized boolean evalBoolean(String expression) {
   try {
     this.exec("retval = " + expression);
     PyObject pyObj = this.get("retval");
     String retString = pyObj.toString();
     Debug.println("retString = " + retString);
     if (retString.equals("1")) return true;
     else return false;
   } catch (PyException ex) {
     ex.printStackTrace();
     System.exit(0);
     return false;
   }
 }
예제 #8
0
 /**
  * Run this filter on the given SIP message (represented as an array canonical headers) and return
  * true or false.
  */
 protected synchronized boolean match(SIPMessage sipMsg) {
   this.set("sipMessage", sipMsg);
   try {
     this.exec("retval = match(sipMessage)");
     PyObject pyObj = this.get("retval");
     String retString = pyObj.toString();
     if (retString.equals("1")) return true;
     else return false;
   } catch (PyException ex) {
     ex.printStackTrace();
     System.out.println("Error in filter spec. " + ex.getMessage());
     System.exit(0);
   }
   return false;
 }
예제 #9
0
  static PyObject replacePathItem(PySystemState sys, int idx, PyList paths) {
    PyObject path = paths.__getitem__(idx);
    if (path instanceof SyspathArchive) {
      // already an archive
      return path;
    }

    try {
      // this has the side affect of adding the jar to the PackageManager during the
      // initialization of the SyspathArchive
      path = new SyspathArchive(sys.getPath(path.toString()));
    } catch (Exception e) {
      return path;
    }
    paths.__setitem__(idx, path);
    return path;
  }
예제 #10
0
  @Override
  protected Enumeration<URL> findResources(String res) throws IOException {
    List<URL> resources = new ArrayList<URL>();

    PySystemState sys = Py.getSystemState();

    if (res.charAt(0) == SLASH_CHAR) {
      res = res.substring(1);
    }
    String entryRes = res;
    if (File.separatorChar != SLASH_CHAR) {
      res = res.replace(SLASH_CHAR, File.separatorChar);
      entryRes = entryRes.replace(File.separatorChar, SLASH_CHAR);
    }

    PyList path = sys.path;
    for (int i = 0; i < path.__len__(); i++) {
      PyObject entry = replacePathItem(sys, i, path);
      if (entry instanceof SyspathArchive) {
        SyspathArchive archive = (SyspathArchive) entry;
        ZipEntry ze = archive.getEntry(entryRes);
        if (ze != null) {
          try {
            resources.add(new URL("jar:file:" + archive.asUriCompatibleString() + "!/" + entryRes));
          } catch (MalformedURLException e) {
            throw new RuntimeException(e);
          }
        }
        continue;
      }
      if (!(entry instanceof PyUnicode)) {
        entry = entry.__str__();
      }
      String dir = sys.getPath(entry.toString());
      try {
        File resource = new File(dir, res);
        if (!resource.exists()) {
          continue;
        }
        resources.add(resource.toURI().toURL());
      } catch (MalformedURLException e) {
        throw new RuntimeException(e);
      }
    }
    return Collections.enumeration(resources);
  }
예제 #11
0
  @ExposedNew
  static final PyObject function___new__(
      PyNewWrapper new_, boolean init, PyType subtype, PyObject[] args, String[] keywords) {
    ArgParser ap =
        new ArgParser(
            "function",
            args,
            keywords,
            new String[] {"code", "globals", "name", "argdefs", "closure"},
            0);
    PyObject code = ap.getPyObject(0);
    PyObject globals = ap.getPyObject(1);
    PyObject name = ap.getPyObject(2, Py.None);
    PyObject defaults = ap.getPyObject(3, Py.None);
    PyObject closure = ap.getPyObject(4, Py.None);

    if (!(code instanceof PyBaseCode)) {
      throw Py.TypeError("function() argument 1 must be code, not " + code.getType().fastGetName());
    }
    if (name != Py.None && !Py.isInstance(name, PyString.TYPE)) {
      throw Py.TypeError("arg 3 (name) must be None or string");
    }
    if (defaults != Py.None && !(defaults instanceof PyTuple)) {
      throw Py.TypeError("arg 4 (defaults) must be None or tuple");
    }

    PyBaseCode tcode = (PyBaseCode) code;
    int nfree = tcode.co_freevars == null ? 0 : tcode.co_freevars.length;
    if (!(closure instanceof PyTuple)) {
      if (nfree > 0 && closure == Py.None) {
        throw Py.TypeError("arg 5 (closure) must be tuple");
      } else if (closure != Py.None) {
        throw Py.TypeError("arg 5 (closure) must be None or tuple");
      }
    }

    int nclosure = closure == Py.None ? 0 : closure.__len__();
    if (nfree != nclosure) {
      throw Py.ValueError(
          String.format(
              "%s requires closure of length %d, not %d", tcode.co_name, nfree, nclosure));
    }
    if (nclosure > 0) {
      for (PyObject o : ((PyTuple) closure).asIterable()) {
        if (!(o instanceof PyCell)) {
          throw Py.TypeError(
              String.format("arg 5 (closure) expected cell, found %s", o.getType().fastGetName()));
        }
      }
    }

    PyFunction function =
        new PyFunction(
            globals,
            defaults == Py.None ? null : ((PyTuple) defaults).getArray(),
            tcode,
            null,
            closure == Py.None ? null : ((PyTuple) closure).getArray());
    if (name != Py.None) {
      function.__name__ = name.toString();
    }
    return function;
  }