use of org.apache.groovy.parser.antlr4.GroovyLexer.TRY in project groovy by apache.
the class AstBuilder method visitUnaryAddExprAlt.
@Override
public Expression visitUnaryAddExprAlt(final UnaryAddExprAltContext ctx) {
ExpressionContext expressionCtx = ctx.expression();
Expression expression = (Expression) this.visit(expressionCtx);
switch(ctx.op.getType()) {
case ADD:
{
if (isNonStringConstantOutsideParentheses(expression)) {
return configureAST(expression, ctx);
}
return configureAST(new UnaryPlusExpression(expression), ctx);
}
case SUB:
{
if (isNonStringConstantOutsideParentheses(expression)) {
ConstantExpression constantExpression = (ConstantExpression) expression;
try {
String integerLiteralText = constantExpression.getNodeMetaData(INTEGER_LITERAL_TEXT);
if (null != integerLiteralText) {
ConstantExpression result = new ConstantExpression(Numbers.parseInteger(SUB_STR + integerLiteralText));
// reset the numberFormatError
this.numberFormatError = null;
return configureAST(result, ctx);
}
String floatingPointLiteralText = constantExpression.getNodeMetaData(FLOATING_POINT_LITERAL_TEXT);
if (null != floatingPointLiteralText) {
ConstantExpression result = new ConstantExpression(Numbers.parseDecimal(SUB_STR + floatingPointLiteralText));
// reset the numberFormatError
this.numberFormatError = null;
return configureAST(result, ctx);
}
} catch (Exception e) {
throw createParsingFailedException(e.getMessage(), ctx);
}
throw new GroovyBugError("Failed to find the original number literal text: " + constantExpression.getText());
}
return configureAST(new UnaryMinusExpression(expression), ctx);
}
case INC:
case DEC:
return configureAST(new PrefixExpression(this.createGroovyToken(ctx.op), expression), ctx);
default:
throw createParsingFailedException("Unsupported unary operation: " + ctx.getText(), ctx);
}
}
use of org.apache.groovy.parser.antlr4.GroovyLexer.TRY in project groovy by apache.
the class SemanticPredicates method isFollowingArgumentsOrClosure.
/**
* Check whether following a method name of command expression.
* Method name should not end with "2: arguments" and "3: closure"
*
* @param context the preceding expression
*/
public static boolean isFollowingArgumentsOrClosure(ExpressionContext context) {
if (context instanceof PostfixExprAltContext) {
List<ParseTree> peacChildren = ((PostfixExprAltContext) context).children;
try {
ParseTree peacChild = peacChildren.get(0);
List<ParseTree> pecChildren = ((PostfixExpressionContext) peacChild).children;
ParseTree pecChild = pecChildren.get(0);
PathExpressionContext pec = (PathExpressionContext) pecChild;
int t = pec.t;
return (2 == t || 3 == t);
} catch (IndexOutOfBoundsException | ClassCastException e) {
throw new GroovyBugError("Unexpected structure of expression context: " + context, e);
}
}
return false;
}
use of org.apache.groovy.parser.antlr4.GroovyLexer.TRY in project groovy by apache.
the class SmartDocumentFilter method parseDocument.
private void parseDocument() throws BadLocationException {
GroovyLangLexer lexer;
try {
lexer = createLexer(styledDocument.getText(0, styledDocument.getLength()));
} catch (IOException e) {
e.printStackTrace();
this.latest = false;
return;
}
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
try {
tokenStream.fill();
} catch (LexerNoViableAltException | GroovySyntaxError e) {
// ignore
this.latest = false;
return;
} catch (Exception e) {
e.printStackTrace();
this.latest = false;
return;
}
List<Token> tokenList = tokenStream.getTokens();
List<Token> tokenListToRender;
try {
tokenListToRender = findTokensToRender(tokenList);
} finally {
this.setRenderRange(null);
}
for (Token token : tokenListToRender) {
int tokenType = token.getType();
if (EOF == tokenType) {
continue;
}
int tokenStartIndex = token.getStartIndex();
int tokenStopIndex = token.getStopIndex();
int tokenLength = tokenStopIndex - tokenStartIndex + 1;
styledDocument.setCharacterAttributes(tokenStartIndex, tokenLength, findStyleByTokenType(tokenType), true);
if (GStringBegin == tokenType || GStringPart == tokenType) {
styledDocument.setCharacterAttributes(tokenStartIndex + tokenLength - 1, 1, defaultStyle, true);
}
}
this.latestTokenList = tokenList;
this.latest = true;
}
use of org.apache.groovy.parser.antlr4.GroovyLexer.TRY in project groovy by apache.
the class AstBuilder method visitTryCatchStatement.
@Override
public Statement visitTryCatchStatement(final TryCatchStatementContext ctx) {
boolean resourcesExists = asBoolean(ctx.resources());
boolean catchExists = asBoolean(ctx.catchClause());
boolean finallyExists = asBoolean(ctx.finallyBlock());
if (!(resourcesExists || catchExists || finallyExists)) {
throw createParsingFailedException("Either a catch or finally clause or both is required for a try-catch-finally statement", ctx);
}
TryCatchStatement tryCatchStatement = new TryCatchStatement((Statement) this.visit(ctx.block()), this.visitFinallyBlock(ctx.finallyBlock()));
if (resourcesExists) {
this.visitResources(ctx.resources()).forEach(tryCatchStatement::addResource);
}
ctx.catchClause().stream().map(this::visitCatchClause).reduce(new LinkedList<>(), (r, e) -> {
// merge several LinkedList<CatchStatement> instances into one LinkedList<CatchStatement> instance
r.addAll(e);
return r;
}).forEach(tryCatchStatement::addCatch);
return configureAST(tryWithResourcesASTTransformation.transform(configureAST(tryCatchStatement, ctx)), ctx);
}
use of org.apache.groovy.parser.antlr4.GroovyLexer.TRY in project groovy by apache.
the class AstBuilder method visitSwitchExpression.
/**
* <pre>
* switch(a) {
* case 0, 1 -> 'a';
* case 2 -> 'b';
* default -> 'z';
* }
* </pre>
* the above code will be transformed to:
* <pre>
* {->
* switch(a) {
* case 0:
* case 1: return 'a';
* case 2: return 'b';
* default: return 'z';
* }
* }()
* </pre>
*
* @param ctx the parse tree
* @return {@link MethodCallExpression} instance
*/
@Override
public MethodCallExpression visitSwitchExpression(SwitchExpressionContext ctx) {
switchExpressionRuleContextStack.push(ctx);
try {
validateSwitchExpressionLabels(ctx);
List<Tuple3<List<Statement>, Boolean, Boolean>> statementInfoList = ctx.switchBlockStatementExpressionGroup().stream().map(e -> this.visitSwitchBlockStatementExpressionGroup(e)).collect(Collectors.toList());
if (statementInfoList.isEmpty()) {
throw createParsingFailedException("`case` or `default` branches are expected", ctx.LBRACE());
}
Boolean isArrow = statementInfoList.get(0).getV2();
if (!isArrow && statementInfoList.stream().noneMatch(e -> {
Boolean hasYieldOrThrowStatement = e.getV3();
return hasYieldOrThrowStatement;
})) {
throw createParsingFailedException("`yield` or `throw` is expected", ctx);
}
List<Statement> statementList = statementInfoList.stream().map(e -> e.getV1()).reduce(new LinkedList<>(), (r, e) -> {
r.addAll(e);
return r;
});
List<CaseStatement> caseStatementList = new LinkedList<>();
List<Statement> defaultStatementList = new LinkedList<>();
statementList.forEach(e -> {
if (e instanceof CaseStatement) {
caseStatementList.add((CaseStatement) e);
} else if (isTrue(e, IS_SWITCH_DEFAULT)) {
defaultStatementList.add(e);
}
});
int defaultStatementListSize = defaultStatementList.size();
if (defaultStatementListSize > 1) {
throw createParsingFailedException("switch expression should have only one default case, which should appear at last", defaultStatementList.get(0));
}
if (defaultStatementListSize > 0 && last(statementList) instanceof CaseStatement) {
throw createParsingFailedException("default case should appear at last", defaultStatementList.get(0));
}
String variableName = "__$$sev" + switchExpressionVariableSeq++;
Statement declarationStatement = declS(localVarX(variableName), this.visitExpressionInPar(ctx.expressionInPar()));
SwitchStatement switchStatement = configureAST(new SwitchStatement(varX(variableName), caseStatementList, defaultStatementListSize == 0 ? EmptyStatement.INSTANCE : defaultStatementList.get(0)), ctx);
MethodCallExpression callClosure = callX(configureAST(closureX(null, createBlockStatement(declarationStatement, switchStatement)), ctx), "call");
callClosure.setImplicitThis(false);
return configureAST(callClosure, ctx);
} finally {
switchExpressionRuleContextStack.pop();
}
}
Aggregations