예제 #1
0
 protected void exitRule(ParseTreeListener listener, RuleNode r) {
   ParserRuleContext ctx = (ParserRuleContext) r.getRuleContext();
   ctx.exitRule(listener);
   listener.exitEveryRule(ctx);
   GlobalInfo info = GlobalInfo.getInstance();
   info.exitRuleSetup();
 }
예제 #2
0
파일: Parser.java 프로젝트: antlr/antlr4
 /**
  * Consume and return the {@linkplain #getCurrentToken current symbol}.
  *
  * <p>E.g., given the following input with {@code A} being the current lookahead symbol, this
  * function moves the cursor to {@code B} and returns {@code A}.
  *
  * <pre>
  *  A B
  *  ^
  * </pre>
  *
  * If the parser is not in error recovery mode, the consumed symbol is added to the parse tree
  * using {@link ParserRuleContext#addChild(Token)}, and {@link ParseTreeListener#visitTerminal} is
  * called on any parse listeners. If the parser <em>is</em> in error recovery mode, the consumed
  * symbol is added to the parse tree using {@link ParserRuleContext#addErrorNode(Token)}, and
  * {@link ParseTreeListener#visitErrorNode} is called on any parse listeners.
  */
 public Token consume() {
   Token o = getCurrentToken();
   if (o.getType() != EOF) {
     getInputStream().consume();
   }
   boolean hasListener = _parseListeners != null && !_parseListeners.isEmpty();
   if (_buildParseTrees || hasListener) {
     if (_errHandler.inErrorRecoveryMode(this)) {
       ErrorNode node = _ctx.addErrorNode(o);
       if (_parseListeners != null) {
         for (ParseTreeListener listener : _parseListeners) {
           listener.visitErrorNode(node);
         }
       }
     } else {
       TerminalNode node = _ctx.addChild(o);
       if (_parseListeners != null) {
         for (ParseTreeListener listener : _parseListeners) {
           listener.visitTerminal(node);
         }
       }
     }
   }
   return o;
 }
  public void checkJParse(String filename) throws Exception {
    URL testFolderURL = TestParser.class.getClassLoader().getResource(SAMPLES_DIR);
    String testFolder = testFolderURL.getPath();

    String J_pathToFile = testFolder + "/" + filename;

    ANTLRInputStream input = new ANTLRFileStream(J_pathToFile);
    JLexer l = new JLexer(input);
    TokenStream tokens = new CommonTokenStream(l);

    JParser parser = new JParser(tokens);
    parser.removeErrorListeners();
    int[] errors = {0};
    parser.addErrorListener(
        new BaseErrorListener() {
          @Override
          public void syntaxError(
              Recognizer<?, ?> recognizer,
              Object offendingSymbol,
              int line,
              int charPositionInLine,
              String msg,
              RecognitionException e) {
            errors[0]++;
          }
        });
    ParserRuleContext tree = parser.file();
    assertTrue(tree != null);
    assertEquals(Token.EOF, tree.getStop().getType());
    assertEquals(0, errors[0]);
  }
예제 #4
0
 /**
  * A utility method to output consistent error messages.
  *
  * @param ctx The ANTLR node the error occurred in.
  * @return The error message with tacked on line number and character position.
  */
 static String error(final ParserRuleContext ctx) {
   return "Analyzer Error ["
       + ctx.getStart().getLine()
       + ":"
       + ctx.getStart().getCharPositionInLine()
       + "]: ";
 }
예제 #5
0
파일: Parser.java 프로젝트: antlr/antlr4
 protected void addContextToParseTree() {
   ParserRuleContext parent = (ParserRuleContext) _ctx.parent;
   // add current context to parent if we have a parent
   if (parent != null) {
     parent.addChild(_ctx);
   }
 }
예제 #6
0
파일: Parser.java 프로젝트: antlr/antlr4
 public ParserRuleContext getInvokingContext(int ruleIndex) {
   ParserRuleContext p = _ctx;
   while (p != null) {
     if (p.getRuleIndex() == ruleIndex) return p;
     p = (ParserRuleContext) p.parent;
   }
   return null;
 }
  @Override
  public void parse(DeclarationArrayInteger node, ParserRuleContext context) {
    // Get Symbol for line
    TerminalNodeImpl firstTerminal = (TerminalNodeImpl) context.getChild(1);
    Label label =
        new LabelLine(
            node.getClass(), firstTerminal.getSymbol().getText(), context.getStart().getLine());

    node.setL(label);
  }
  @Override
  public void parse(StatementSkip node, ParserRuleContext context) {
    // Get Symbol for line
    TerminalNodeImpl firstTerminal = (TerminalNodeImpl) context.getChild(0);
    Label label =
        new LabelLine(
            node.getClass(), firstTerminal.getSymbol().getText(), context.getStart().getLine());

    node.setL(label);
  }
예제 #9
0
파일: Parser.java 프로젝트: antlr/antlr4
 public void exitRule() {
   if (matchedEOF) {
     // if we have matched EOF, it cannot consume past EOF so we use LT(1) here
     _ctx.stop = _input.LT(1); // LT(1) will be end of file
   } else {
     _ctx.stop = _input.LT(-1); // stop node is what we just matched
   }
   // trigger event on _ctx, before it reverts to parent
   if (_parseListeners != null) triggerExitRuleEvent();
   setState(_ctx.invokingState);
   _ctx = (ParserRuleContext) _ctx.parent;
 }
예제 #10
0
 private void add(
     ParserRuleContext ctx,
     Boolean valid,
     Boolean print,
     GlobalInfo.nodeTypes type,
     ClassInfo value) {
   if (print) Logger.printValue(ctx, valid.toString() + " : " + ctx.getText());
   WalkInfo info = new WalkInfo(valid, ctx.getText());
   info.setClassType(value);
   info.setNodeType(type);
   globalInfo.getCurrentQueue().add(info);
 }
예제 #11
0
  public static ParserRuleContext findTopContext(
      ParserRuleContext context, IntervalSet values, boolean checkTop) {
    if (checkTop && values.contains(context.getRuleIndex())) {
      return context;
    }

    if (context.isEmpty()) {
      return null;
    }

    return findTopContext((ParserRuleContext) context.parent, values, true);
  }
예제 #12
0
 public void process(String[] args) throws IOException {
   handleArgs(args);
   ANTLRInputStream chars;
   if (inputFileName != null) chars = new ANTLRFileStream(inputFileName);
   else chars = new ANTLRInputStream(System.in);
   CharsAsTokens charTokens = new CharsAsTokens(chars, MarkdownParser.tokenNames);
   CommonTokenStream tokens = new CommonTokenStream(charTokens);
   MarkdownParser parser = new MarkdownParser(tokens);
   parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
   ParserRuleContext t = parser.file();
   if (showGUI) t.inspect(Arrays.asList(MarkdownParser.ruleNames));
   if (showTree) System.out.println(t.toStringTree(parser));
 }
예제 #13
0
파일: Parser.java 프로젝트: antlr/antlr4
 public void enterOuterAlt(ParserRuleContext localctx, int altNum) {
   localctx.setAltNumber(altNum);
   // if we have new localctx, make sure we replace existing ctx
   // that is previous child of parse tree
   if (_buildParseTrees && _ctx != localctx) {
     ParserRuleContext parent = (ParserRuleContext) _ctx.parent;
     if (parent != null) {
       parent.removeLastChild();
       parent.addChild(localctx);
     }
   }
   _ctx = localctx;
 }
예제 #14
0
  public static Token getStopSymbol(@NonNull ParserRuleContext context) {
    Parameters.notNull("context", context);
    if (context.stop != null) {
      return context.stop;
    }

    for (int i = context.getChildCount() - 1; i >= 0; i--) {
      Token symbol = getStopSymbol(context.getChild(i));
      if (symbol != null) {
        return symbol;
      }
    }

    return context.start;
  }
예제 #15
0
파일: Parser.java 프로젝트: antlr/antlr4
 /**
  * Always called by generated parsers upon entry to a rule. Access field {@link #_ctx} get the
  * current context.
  */
 public void enterRule(ParserRuleContext localctx, int state, int ruleIndex) {
   setState(state);
   _ctx = localctx;
   _ctx.start = _input.LT(1);
   if (_buildParseTrees) addContextToParseTree();
   if (_parseListeners != null) triggerEnterRuleEvent();
 }
예제 #16
0
파일: Parser.java 프로젝트: antlr/antlr4
 /**
  * Notify any parse listeners of an exit rule event.
  *
  * @see #addParseListener
  */
 protected void triggerExitRuleEvent() {
   // reverse order walk of listeners
   for (int i = _parseListeners.size() - 1; i >= 0; i--) {
     ParseTreeListener listener = _parseListeners.get(i);
     _ctx.exitRule(listener);
     listener.exitEveryRule(_ctx);
   }
 }
예제 #17
0
파일: Parser.java 프로젝트: antlr/antlr4
 public void enterRecursionRule(
     ParserRuleContext localctx, int state, int ruleIndex, int precedence) {
   setState(state);
   _precedenceStack.push(precedence);
   _ctx = localctx;
   _ctx.start = _input.LT(1);
   if (_parseListeners != null) {
     triggerEnterRuleEvent(); // simulates rule entry for left-recursive rules
   }
 }
    protected int getTypeDeclarationContextAccessFlag(ParserRuleContext ctx) {
      int access = 0;

      for (JavaParser.ClassOrInterfaceModifierContext coiModifierContext :
          ctx.getRuleContexts(JavaParser.ClassOrInterfaceModifierContext.class)) {
        access += getAccessFlag(coiModifierContext);
      }

      return access;
    }
  @Override
  public void enterStatement(JavaParser.StatementContext ctx) {
    ctx.getChildCount();
    String text = ctx.getStart().getText();
    if (!text.equals("if") && !text.equals("while") && !text.equals("for") && !text.equals("do")) {
      return;
    }

    int depth = 1;
    ParserRuleContext tempContext = ctx.getParent();
    while (!(tempContext instanceof JavaParser.MethodDeclarationContext)) {
      if (tempContext instanceof JavaParser.StatementContext) {
        text = tempContext.getStart().getText();
        if (text.equals("if") || text.equals("while") || text.equals("for") || text.equals("do")) {
          depth++;
        }
      }
      tempContext = tempContext.getParent();
    }
    report.setDepthOfConditionNesting(depth);
  }
예제 #20
0
  private void checkAndAdd(
      ParserRuleContext ctx, Boolean valid, Boolean print, GlobalInfo.nodeTypes type) {
    Boolean symbolExists;
    String code = ctx.getText();
    ClassInfo classType = null;
    if (globalInfo.getObjectContext() != null) {
      ClassInfo ci = globalInfo.getObjectContext();
      globalInfo.setPreviousObjectContext(ci);

      // this avoids issues in case one Class overwrites a method from it's parent
      if (globalInfo.isTopLevel() && globalInfo.isLeftSideAssignment())
        classType = ci.getPropertyExcludeParents(code);
      // we supose that inside a function we don't modify the prototype
      else {
        classType = ci.getProperty(code);
        // example: Object.keys will fail because we're checking
        // the function, instead of the class
        if (classType == null) {
          if (globalInfo.getClasses().get(ci.getName()) != null) {
            ci = globalInfo.getClasses().get(ci.getName());
            globalInfo.setPreviousObjectContext(ci);
            classType = ci.getProperty(code);
          }
        }
      }

      if (code.equals("prototype")) {
        symbolExists = true;
        classType = ci;
      } else if (classType != null) {
        symbolExists = true;
      } else symbolExists = false;

      // TODO add property automatically to all objects instead of hardcoding it here
      if (classType == null && code.equals("constructor")) {
        symbolExists = true;
        // TODO eventually we may need to support multiple parentClass
        ClassInfo constructor =
            globalInfo
                .getDocumentScope()
                .getSymbolOfStack(
                    globalInfo.getObjectContext().getParentClasses().getAllParents().get(0));
        globalInfo.setObjectContext(constructor);
        classType = constructor;
      }
    } else {
      classType = globalInfo.getCurrentScope().getSymbolOfStack(code);
      if (classType == null) classType = globalInfo.getClasses().get(code);
      symbolExists = classType != null;
    }
    if (classType != null) classType = new ClassInfo(classType);
    add(ctx, symbolExists, print, type, classType);
  }
    protected int getMemberDeclarationContextAccessFlag(ParserRuleContext ctx) {
      int access = 0;

      for (JavaParser.ModifierContext modifierContext :
          ctx.getRuleContexts(JavaParser.ModifierContext.class)) {
        JavaParser.ClassOrInterfaceModifierContext coiModifierContext =
            modifierContext.classOrInterfaceModifier();
        if (coiModifierContext != null) {
          access += getAccessFlag(coiModifierContext);
        }
      }

      return access;
    }
예제 #22
0
  public static boolean isInContexts(
      @NonNull ParserRuleContext context, boolean allowGaps, @NonNull int... stack) {
    Parameters.notNull("context", context);
    Parameters.notNull("stack", stack);

    if (allowGaps) {
      throw new UnsupportedOperationException("Not implemented yet.");
    }

    ParserRuleContext currentContext = context;
    for (int element : stack) {
      if (currentContext.getRuleIndex() != element) {
        return false;
      }

      currentContext = currentContext.getParent();
      if (currentContext == null) {
        return false;
      }
    }

    return true;
  }
    public void enterMethodDeclaration(
        ParserRuleContext ctx,
        TerminalNode identifier,
        JavaParser.FormalParametersContext formalParameters,
        JavaParser.TypeContext returnType) {

      int access = getClassBodyDeclarationAccessFlag(ctx.getParent().getParent());
      String name = identifier.getText();
      String paramDescriptors = createParamDescriptors(formalParameters.formalParameterList());
      String returnDescriptor = createDescriptor(returnType, 0);
      String descriptor = paramDescriptors + returnDescriptor;

      currentType.getMethods().add(new JavaMethod(currentType, access, name, descriptor));
    }
예제 #24
0
파일: Parser.java 프로젝트: antlr/antlr4
  public void unrollRecursionContexts(ParserRuleContext _parentctx) {
    _precedenceStack.pop();
    _ctx.stop = _input.LT(-1);
    ParserRuleContext retctx = _ctx; // save current ctx (return value)

    // unroll so _ctx is as it was before call to recursive method
    if (_parseListeners != null) {
      while (_ctx != _parentctx) {
        triggerExitRuleEvent();
        _ctx = (ParserRuleContext) _ctx.parent;
      }
    } else {
      _ctx = _parentctx;
    }

    // hook into tree
    retctx.parent = _parentctx;

    if (_buildParseTrees && _parentctx != null) {
      // add return ctx into invoking rule's tree
      _parentctx.addChild(retctx);
    }
  }
예제 #25
0
파일: XPath.java 프로젝트: antlr/antlr4
  /**
   * Return a list of all nodes starting at {@code t} as root that satisfy the path. The root {@code
   * /} is relative to the node passed to {@link #evaluate}.
   */
  public Collection<ParseTree> evaluate(final ParseTree t) {
    ParserRuleContext dummyRoot = new ParserRuleContext();
    dummyRoot.children = Collections.singletonList(t); // don't set t's parent.

    Collection<ParseTree> work = Collections.<ParseTree>singleton(dummyRoot);

    int i = 0;
    while (i < elements.length) {
      Collection<ParseTree> next = new LinkedHashSet<ParseTree>();
      for (ParseTree node : work) {
        if (node.getChildCount() > 0) {
          // only try to match next element if it has children
          // e.g., //func/*/stat might have a token node for which
          // we can't go looking for stat nodes.
          Collection<? extends ParseTree> matching = elements[i].evaluate(node);
          next.addAll(matching);
        }
      }
      i++;
      work = next;
    }

    return work;
  }
예제 #26
0
파일: Parser.java 프로젝트: antlr/antlr4
  /**
   * Match current input symbol as a wildcard. If the symbol type matches (i.e. has a value greater
   * than 0), {@link ANTLRErrorStrategy#reportMatch} and {@link #consume} are called to complete the
   * match process.
   *
   * <p>If the symbol type does not match, {@link ANTLRErrorStrategy#recoverInline} is called on the
   * current error strategy to attempt recovery. If {@link #getBuildParseTree} is {@code true} and
   * the token index of the symbol returned by {@link ANTLRErrorStrategy#recoverInline} is -1, the
   * symbol is added to the parse tree by calling {@link ParserRuleContext#addErrorNode}.
   *
   * @return the matched symbol
   * @throws RecognitionException if the current input symbol did not match a wildcard and the error
   *     strategy could not recover from the mismatched symbol
   */
  public Token matchWildcard() throws RecognitionException {
    Token t = getCurrentToken();
    if (t.getType() > 0) {
      _errHandler.reportMatch(this);
      consume();
    } else {
      t = _errHandler.recoverInline(this);
      if (_buildParseTrees && t.getTokenIndex() == -1) {
        // we must have conjured up a new token during single token insertion
        // if it's not the current symbol
        _ctx.addErrorNode(t);
      }
    }

    return t;
  }
    protected int getClassBodyDeclarationAccessFlag(ParserRuleContext ctx) {
      if ((currentType.access & JavaType.FLAG_INTERFACE) == 0) {
        int access = 0;

        for (JavaParser.ModifierContext modifierContext :
            ctx.getRuleContexts(JavaParser.ModifierContext.class)) {
          JavaParser.ClassOrInterfaceModifierContext coimc =
              modifierContext.classOrInterfaceModifier();

          if (coimc != null) {
            access += getAccessFlag(coimc);
          }
        }

        return access;
      } else {
        return JavaType.FLAG_PUBLIC;
      }
    }
예제 #28
0
파일: Parser.java 프로젝트: antlr/antlr4
  /**
   * Like {@link #enterRule} but for recursive rules. Make the current context the child of the
   * incoming localctx.
   */
  public void pushNewRecursionContext(ParserRuleContext localctx, int state, int ruleIndex) {
    ParserRuleContext previous = _ctx;
    previous.parent = localctx;
    previous.invokingState = state;
    previous.stop = _input.LT(-1);

    _ctx = localctx;
    _ctx.start = previous.start;
    if (_buildParseTrees) {
      _ctx.addChild(previous);
    }

    if (_parseListeners != null) {
      triggerEnterRuleEvent(); // simulates rule entry for left-recursive rules
    }
  }
예제 #29
0
  public static Interval getSourceInterval(@NonNull ParserRuleContext context) {
    Parameters.notNull("context", context);
    int startIndex = context.start.getStartIndex();
    Token stopSymbol = getStopSymbol(context);
    if (stopSymbol == null) {
      return new Interval(startIndex, startIndex - 1);
    }

    int stopIndex;
    if (stopSymbol.getType() != Token.EOF) {
      stopIndex = stopSymbol.getStopIndex();
    } else {
      TokenSource tokenSource = context.getStart().getTokenSource();
      CharStream inputStream = tokenSource != null ? tokenSource.getInputStream() : null;
      if (inputStream != null) {
        stopIndex = inputStream.size() - 1;
      } else {
        stopIndex = context.start.getStartIndex() - 1;
      }
    }

    stopIndex = Math.max(stopIndex, startIndex - 1);
    return new Interval(startIndex, stopIndex);
  }
예제 #30
0
 public void copyFrom(ExprContext ctx) {
   super.copyFrom(ctx);
 }