Esempio n. 1
0
 @NotNull
 private static String renderStackTrace(@NotNull Throwable cause) {
   StackTraceElement[] oldTrace = cause.getStackTrace();
   List<StackTraceElement> newTrace = new ArrayList<StackTraceElement>();
   boolean skip = true;
   for (int i = oldTrace.length - 1; i >= 0; i--) {
     StackTraceElement element = oldTrace[i];
     // All our code happens in the script constructor, and no reflection/native code happens in
     // constructors.
     // So we ignore everything in the stack trace until the first constructor
     if (element.getMethodName().equals("<init>")) {
       skip = false;
     }
     if (!skip) {
       newTrace.add(element);
     }
   }
   Collections.reverse(newTrace);
   cause.setStackTrace(newTrace.toArray(new StackTraceElement[newTrace.size()]));
   return Throwables.getStackTraceAsString(cause);
 }
Esempio n. 2
0
  @NotNull
  public LineResult eval(@NotNull String line) {
    ++lineNumber;

    FqName scriptFqName = new FqName("Line" + lineNumber);
    Type scriptClassType = asmTypeByFqNameWithoutInnerClasses(scriptFqName);

    StringBuilder fullText = new StringBuilder();
    for (String prevLine : previousIncompleteLines) {
      fullText.append(prevLine).append("\n");
    }
    fullText.append(line);

    LightVirtualFile virtualFile =
        new LightVirtualFile(
            "line" + lineNumber + JetParserDefinition.STD_SCRIPT_EXT,
            JetLanguage.INSTANCE,
            fullText.toString());
    virtualFile.setCharset(CharsetToolkit.UTF8_CHARSET);
    JetFile psiFile =
        (JetFile) psiFileFactory.trySetupPsiForFile(virtualFile, JetLanguage.INSTANCE, true, false);
    assert psiFile != null : "Script file not analyzed at line " + lineNumber + ": " + fullText;

    ReplMessageCollectorWrapper errorCollector = new ReplMessageCollectorWrapper();

    AnalyzerWithCompilerReport.SyntaxErrorReport syntaxErrorReport =
        AnalyzerWithCompilerReport.reportSyntaxErrors(
            psiFile, errorCollector.getMessageCollector());

    if (syntaxErrorReport.isHasErrors() && syntaxErrorReport.isAllErrorsAtEof()) {
      previousIncompleteLines.add(line);
      return LineResult.incomplete();
    }

    previousIncompleteLines.clear();

    if (syntaxErrorReport.isHasErrors()) {
      return LineResult.error(errorCollector.getString());
    }

    prepareForTheNextReplLine(topDownAnalysisContext);
    trace.clearDiagnostics();

    //noinspection ConstantConditions
    psiFile.getScript().putUserData(ScriptPriorities.PRIORITY_KEY, lineNumber);

    ScriptDescriptor scriptDescriptor = doAnalyze(psiFile, errorCollector);
    if (scriptDescriptor == null) {
      return LineResult.error(errorCollector.getString());
    }

    List<Pair<ScriptDescriptor, Type>> earlierScripts = Lists.newArrayList();

    for (EarlierLine earlierLine : earlierLines) {
      earlierScripts.add(
          Pair.create(earlierLine.getScriptDescriptor(), earlierLine.getClassType()));
    }

    GenerationState state =
        new GenerationState(
            psiFile.getProject(),
            ClassBuilderFactories.BINARIES,
            module,
            trace.getBindingContext(),
            Collections.singletonList(psiFile));

    compileScript(
        psiFile.getScript(),
        scriptClassType,
        earlierScripts,
        state,
        CompilationErrorHandler.THROW_EXCEPTION);

    for (OutputFile outputFile : state.getFactory().asList()) {
      classLoader.addClass(
          JvmClassName.byInternalName(outputFile.getRelativePath().replaceFirst("\\.class$", "")),
          outputFile.asByteArray());
    }

    try {
      Class<?> scriptClass = classLoader.loadClass(scriptFqName.asString());

      Class<?>[] constructorParams = new Class<?>[earlierLines.size()];
      Object[] constructorArgs = new Object[earlierLines.size()];

      for (int i = 0; i < earlierLines.size(); ++i) {
        constructorParams[i] = earlierLines.get(i).getScriptClass();
        constructorArgs[i] = earlierLines.get(i).getScriptInstance();
      }

      Constructor<?> scriptInstanceConstructor = scriptClass.getConstructor(constructorParams);
      Object scriptInstance;
      try {
        scriptInstance = scriptInstanceConstructor.newInstance(constructorArgs);
      } catch (Throwable e) {
        return LineResult.error(renderStackTrace(e.getCause()));
      }
      Field rvField = scriptClass.getDeclaredField("rv");
      rvField.setAccessible(true);
      Object rv = rvField.get(scriptInstance);

      earlierLines.add(
          new EarlierLine(line, scriptDescriptor, scriptClass, scriptInstance, scriptClassType));

      JetType returnType = scriptDescriptor.getScriptCodeDescriptor().getReturnType();
      return LineResult.successful(rv, returnType != null && KotlinBuiltIns.isUnit(returnType));
    } catch (Throwable e) {
      @SuppressWarnings("UseOfSystemOutOrSystemErr")
      PrintWriter writer = new PrintWriter(System.err);
      classLoader.dumpClasses(writer);
      writer.flush();
      throw UtilsPackage.rethrow(e);
    }
  }