Esempio n. 1
0
  protected void consumeMethodInvocationName() {
    // MethodInvocation ::= Name '(' ArgumentListopt ')'

    if (this.scanner.startPosition >= this.codeSnippetStart
        && this.scanner.startPosition <= this.codeSnippetEnd + 1 + this.lineSeparatorLength // 14838
        && isTopLevelType()) {

      // when the name is only an identifier...we have a message send to "this" (implicit)

      MessageSend m = newMessageSend();
      m.sourceEnd = this.rParenPos;
      m.sourceStart =
          (int) ((m.nameSourcePosition = this.identifierPositionStack[this.identifierPtr]) >>> 32);
      m.selector = this.identifierStack[this.identifierPtr--];
      if (this.identifierLengthStack[this.identifierLengthPtr] == 1) {
        m.receiver = new CodeSnippetThisReference(0, 0, this.evaluationContext, true);
        this.identifierLengthPtr--;
      } else {
        this.identifierLengthStack[this.identifierLengthPtr]--;
        m.receiver = getUnspecifiedReference();
        m.sourceStart = m.receiver.sourceStart;
      }
      pushOnExpressionStack(m);
    } else {
      super.consumeMethodInvocationName();
    }
  }
Esempio n. 2
0
 protected void reportSyntaxErrors(boolean isDietParse, int oldFirstToken) {
   if (!isDietParse) {
     this.scanner.initialPosition = this.lastStatement;
     this.scanner.eofPosition = this.codeSnippetEnd + 1; // stop after expression
     oldFirstToken = TokenNameTWIDDLE; // TokenNameREMAINDER; // first token of th expression parse
   }
   super.reportSyntaxErrors(isDietParse, oldFirstToken);
 }
  public void checkParse(char[] source, String expectedSyntaxErrorDiagnosis, String testName) {

    /* using regular parser in DIET mode */
    Parser parser =
        new Parser(
            new ProblemReporter(
                DefaultErrorHandlingPolicies.proceedWithAllProblems(),
                new CompilerOptions(getCompilerOptions()),
                new DefaultProblemFactory(Locale.getDefault())),
            optimizeStringLiterals);
    ICompilationUnit sourceUnit = new CompilationUnit(source, testName, null);
    CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0);

    parser.parse(sourceUnit, compilationResult);

    StringBuffer buffer = new StringBuffer(100);
    if (compilationResult.hasProblems() || compilationResult.hasTasks()) {
      CategorizedProblem[] problems = compilationResult.getAllProblems();
      int count = problems.length;
      int problemCount = 0;
      char[] unitSource = compilationResult.compilationUnit.getContents();
      for (int i = 0; i < count; i++) {
        if (problems[i] != null) {
          if (problemCount == 0) buffer.append("----------\n");
          problemCount++;
          buffer.append(problemCount + (problems[i].isError() ? ". ERROR" : ". WARNING"));
          buffer.append(
              " in " + new String(problems[i].getOriginatingFileName()).replace('/', '\\'));
          try {
            buffer.append(((DefaultProblem) problems[i]).errorReportSource(unitSource));
            buffer.append("\n");
            buffer.append(problems[i].getMessage());
            buffer.append("\n");
          } catch (Exception e) {
          }
          buffer.append("----------\n");
        }
      }
    }
    String computedSyntaxErrorDiagnosis = buffer.toString();
    // System.out.println(Util.displayString(computedSyntaxErrorDiagnosis));
    assertEquals(
        "Invalid syntax error diagnosis" + testName,
        Util.convertToIndependantLineDelimiter(expectedSyntaxErrorDiagnosis),
        Util.convertToIndependantLineDelimiter(computedSyntaxErrorDiagnosis));
  }
Esempio n. 4
0
 public void reset() {
   this.lookupEnvironment.reset();
   // GROOVY start: give the parser a chance to reset as well
   parser.reset();
   // GROOVY end
   this.parser.scanner.source = null;
   this.unitsToProcess = null;
   if (DebugRequestor != null) DebugRequestor.reset();
   this.problemReporter.reset();
 }
Esempio n. 5
0
  protected void consumePrimaryNoNewArrayThis() {
    // PrimaryNoNewArray ::= 'this'

    if (this.scanner.startPosition >= this.codeSnippetStart
        && this.scanner.startPosition <= this.codeSnippetEnd + 1 + this.lineSeparatorLength // 14838
        && isTopLevelType()) {
      pushOnExpressionStack(
          new CodeSnippetThisReference(
              this.intStack[this.intPtr--], this.endPosition, this.evaluationContext, false));
    } else {
      super.consumePrimaryNoNewArrayThis();
    }
  }
Esempio n. 6
0
 public void runConformTest(
     String fileName, String fileContents, Parser parser, ASTCollector visitor, String expected) {
   CompilationUnit source = new CompilationUnit(fileContents.toCharArray(), fileName, null);
   CompilationResult compilationResult = new CompilationResult(source, 1, 1, 10);
   CompilationUnitDeclaration unit = parser.parse(source, compilationResult);
   assertEquals(0, compilationResult.problemCount);
   unit.traverse(visitor, unit.scope);
   String result = visitor.result();
   if (!expected.equals(result)) {
     System.out.println(getClass().getName() + '#' + getName());
     System.out.println("Expected:");
     System.out.println(expected);
     System.out.println("But was:");
     System.out.println(result);
     System.out.println("Cut and paste:");
     System.out.println(Util.displayString(result, INDENT, SHIFT));
   }
   assertEquals(expected, result);
 }
Esempio n. 7
0
  protected void consumeStatementReturn() {
    // ReturnStatement ::= 'return' Expressionopt ';'

    // returned value intercepted by code snippet
    // support have to be defined at toplevel only
    if ((this.hasRecoveredOnExpression
            || (this.scanner.startPosition >= this.codeSnippetStart
                && this.scanner.startPosition
                    <= this.codeSnippetEnd + 1 + this.lineSeparatorLength /* 14838*/))
        && this.expressionLengthStack[this.expressionLengthPtr] != 0
        && isTopLevelType()) {
      this.expressionLengthPtr--;
      Expression expression = this.expressionStack[this.expressionPtr--];
      pushOnAstStack(
          new CodeSnippetReturnStatement(expression, expression.sourceStart, expression.sourceEnd));
    } else {
      super.consumeStatementReturn();
    }
    /* recovery */
    recordLastStatementIfNeeded();
  }
 /* (non-Javadoc)
  * @see org.eclipse.jdt.internal.compiler.parser.Parser#initialize()
  */
 public void initialize() {
   super.initialize();
   this.commentPtr = -1;
 }
 /* (non-Javadoc)
  * @see org.eclipse.jdt.internal.compiler.parser.Parser#consumeEmptyTypeDeclaration()
  */
 protected void consumeEmptyTypeDeclaration() {
   pushOnCommentsStack(0, this.scanner.commentPtr);
   super.consumeEmptyTypeDeclaration();
 }
 /* (non-Javadoc)
  * Save all source comments currently stored before flushing them.
  * this.scanner.commentPtr is expected *not* yet being reset before calling this method.
  * @see org.eclipse.jdt.internal.compiler.parser.Parser#resetModifiers()
  */
 protected void resetModifiers() {
   pushOnCommentsStack(0, this.scanner.commentPtr);
   super.resetModifiers();
 }
Esempio n. 11
0
 protected void consumeClassDeclaration() {
   super.consumeClassDeclaration();
   /* recovery */
   recordLastStatementIfNeeded();
 }
Esempio n. 12
0
 protected void consumeStatementWhile() {
   super.consumeStatementWhile();
   /* recovery */
   recordLastStatementIfNeeded();
 }
Esempio n. 13
0
 protected void ignoreExpressionAssignment() {
   super.ignoreExpressionAssignment();
   /* recovery */
   recordLastStatementIfNeeded();
 }
Esempio n. 14
0
 protected void consumeStatementSynchronized() {
   super.consumeStatementSynchronized();
   /* recovery */
   recordLastStatementIfNeeded();
 }
Esempio n. 15
0
 protected void consumeStatementTry(boolean arg_0) {
   super.consumeStatementTry(arg_0);
   /* recovery */
   recordLastStatementIfNeeded();
 }
Esempio n. 16
0
 protected void consumeStatementContinueWithLabel() {
   super.consumeStatementContinueWithLabel();
   /* recovery */
   recordLastStatementIfNeeded();
 }
Esempio n. 17
0
 protected void consumeEnhancedForStatement() {
   super.consumeEnhancedForStatement();
   /* recovery */
   recordLastStatementIfNeeded();
 }
 /* (non-Javadoc)
  * @see org.eclipse.jdt.internal.compiler.parser.Parser#initialize()
  */
 public void initialize(boolean initializeNLS) {
   super.initialize(initializeNLS);
   this.commentPtr = -1;
 }
 /* (non-Javadoc)
  * @see org.eclipse.jdt.internal.compiler.parser.Parser#consumeClassHeader()
  */
 protected void consumeClassHeader() {
   pushOnCommentsStack(0, this.scanner.commentPtr);
   super.consumeClassHeader();
 }
Esempio n. 20
0
  /**
   * In case emulating local variables, wrap the (recovered) statements inside a try statement so as
   * to achieve local state commiting (copy local vars back to fields). The CSToCuMapper could not
   * be used, since it could have interfered with the syntax recovery specific to code snippets.
   */
  protected void consumeMethodDeclaration(boolean isNotAbstract) {
    // MethodDeclaration ::= MethodHeader MethodBody
    // AbstractMethodDeclaration ::= MethodHeader ';'

    super.consumeMethodDeclaration(isNotAbstract);

    // now we know that we have a method declaration at the top of the ast stack
    MethodDeclaration methodDecl = (MethodDeclaration) this.astStack[this.astPtr];

    // automatically wrap the last statement inside a return statement, if it is an expression
    // support have to be defined at toplevel only
    if (this.isTopLevelType()) {
      int last = methodDecl.statements == null ? -1 : methodDecl.statements.length - 1;
      if (last >= 0 && methodDecl.statements[last] instanceof Expression) {
        Expression lastExpression = (Expression) methodDecl.statements[last];
        methodDecl.statements[last] =
            new CodeSnippetReturnStatement(
                lastExpression, lastExpression.sourceStart, lastExpression.sourceEnd);
      }
    }

    int start = methodDecl.bodyStart - 1, end = start;
    long position = ((long) start << 32) + end;
    long[] positions = new long[] {position};
    if (this.evaluationContext.localVariableNames != null) {

      int varCount =
          this.evaluationContext.localVariableNames.length; // n local decls+ try statement

      // generate n local variable declarations: [type] [name] = val$[name];
      Statement[] newStatements = new Statement[varCount + 1];
      for (int i = 0; i < varCount; i++) {
        char[] trimmedTypeName = this.evaluationContext.localVariableTypeNames[i];
        int nameEnd = CharOperation.indexOf('[', trimmedTypeName);
        if (nameEnd >= 0) {
          trimmedTypeName = CharOperation.subarray(trimmedTypeName, 0, nameEnd);
        }
        nameEnd = CharOperation.indexOf(' ', trimmedTypeName);
        if (nameEnd >= 0) {
          trimmedTypeName = CharOperation.subarray(trimmedTypeName, 0, nameEnd);
        }
        TypeReference typeReference =
            new QualifiedTypeReference(CharOperation.splitOn('.', trimmedTypeName), positions);
        int dimCount =
            CharOperation.occurencesOf('[', this.evaluationContext.localVariableTypeNames[i]);
        if (dimCount > 0) {
          typeReference = this.copyDims(typeReference, dimCount);
        }
        NameReference init =
            new SingleNameReference(
                CharOperation.concat(
                    LOCAL_VAR_PREFIX, this.evaluationContext.localVariableNames[i]),
                position);
        LocalDeclaration declaration =
            new LocalDeclaration(this.evaluationContext.localVariableNames[i], start, end);
        declaration.initialization = init;
        declaration.type = typeReference;
        declaration.modifiers = this.evaluationContext.localVariableModifiers[i];
        newStatements[i] = declaration;
      }

      // generate try { [snippet] } finally { [save locals to fields] }
      // try block
      TryStatement tryStatement = new TryStatement();
      Block tryBlock = new Block(methodDecl.explicitDeclarations);
      tryBlock.sourceStart = start;
      tryBlock.sourceEnd = end;
      tryBlock.statements = methodDecl.statements; // snippet statements
      tryStatement.tryBlock = tryBlock;
      // finally block
      Block finallyBlock = new Block(0);
      finallyBlock.sourceStart = start;
      finallyBlock.sourceEnd = end;
      finallyBlock.statements = new Statement[varCount];
      for (int i = 0; i < varCount; i++) {
        finallyBlock.statements[i] =
            new Assignment(
                new SingleNameReference(
                    CharOperation.concat(
                        LOCAL_VAR_PREFIX, this.evaluationContext.localVariableNames[i]),
                    position),
                new SingleNameReference(this.evaluationContext.localVariableNames[i], position),
                (int) position);
      }
      tryStatement.finallyBlock = finallyBlock;

      newStatements[varCount] = tryStatement;
      methodDecl.statements = newStatements;
    }
  }
Esempio n. 21
0
 protected void consumeLocalVariableDeclarationStatement() {
   super.consumeLocalVariableDeclarationStatement();
   /* recovery */
   recordLastStatementIfNeeded();
 }
Esempio n. 22
0
 protected void consumeExpressionStatement() {
   super.consumeExpressionStatement();
   /* recovery */
   recordLastStatementIfNeeded();
 }