org.codehaus.groovy.syntax.SyntaxException Java Examples

The following examples show how to use org.codehaus.groovy.syntax.SyntaxException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MacroGroovyMethods.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected static ClosureExpression getClosureArgument(SourceUnit source, MethodCallExpression call) {
    TupleExpression tupleArguments = getMacroArguments(source, call);

    int size = tupleArguments == null ? -1 : tupleArguments.getExpressions().size();
    if (size < 1) {
        source.addError(new SyntaxException("Call arguments should have at least one argument" + '\n', tupleArguments));
        return null;
    }

    Expression result = tupleArguments.getExpression(size - 1);
    if (!(result instanceof ClosureExpression)) {
        source.addError(new SyntaxException("Last call argument should be a closure" + '\n', result));
        return null;
    }

    return (ClosureExpression) result;
}
 
Example #2
Source File: CpsTransformer.java    From groovy-cps with Apache License 2.0 6 votes vote down vote up
@Override
public void visitMethodCallExpression(final MethodCallExpression call) {
    makeNode("functionCall", new Runnable() {
        @Override
        public void run() {
            loc(call);

            // isImplicitThis==true even when objectExpression is not 'this'.
            // See InvocationWriter.makeCall,
            if (call.isImplicitThis() && AsmClassGenerator.isThisExpression(call.getObjectExpression())) {
                makeNode("javaThis_");
            } else {
                visit(call.getObjectExpression());
            }
            if (call.isSpreadSafe()) {
                sourceUnit.addError(new SyntaxException("spread not yet supported for CPS transformation",
                        call.getLineNumber(), call.getColumnNumber()));
            }
            visit(call.getMethod());
            literal(call.isSafe());
            visit(((TupleExpression) call.getArguments()).getExpressions());
        }
    });
}
 
Example #3
Source File: CpsTransformer.java    From groovy-cps with Apache License 2.0 6 votes vote down vote up
/**
 * @see
 * org.codehaus.groovy.classgen.asm.BinaryExpressionHelper#eval(BinaryExpression)
 */
@Override
public void visitBinaryExpression(final BinaryExpression exp) {
    String name = BINARY_OP_TO_BUILDER_METHOD.get(exp.getOperation().getType());
    if (name != null) {
        if (name.equals("assign") &&
                exp.getLeftExpression() instanceof TupleExpression) {
            multipleAssignment(exp,
                    (TupleExpression)exp.getLeftExpression(),
                    exp.getRightExpression());
        } else {
            makeNode(name, new Runnable() {
                @Override
                public void run() {
                    loc(exp);
                    visit(exp.getLeftExpression());
                    visit(exp.getRightExpression());
                }
            });
        }
        return;
    }

    sourceUnit.addError(new SyntaxException("Unsupported operation in this context",
            exp.getLineNumber(), exp.getColumnNumber()));
}
 
Example #4
Source File: SourceUnit.java    From groovy with Apache License 2.0 6 votes vote down vote up
public ModuleNode buildAST() {
    if (null != this.ast) {
        return this.ast;
    }

    try {
        this.ast = parserPlugin.buildAST(this, this.classLoader, this.cst);
        this.ast.setDescription(this.name);
    } catch (SyntaxException e) {
        if (this.ast == null) {
            // Create a dummy ModuleNode to represent a failed parse - in case a later phase attempts to use the ast
            this.ast = new ModuleNode(this);
        }
        getErrorCollector().addError(new SyntaxErrorMessage(e, this));
    }

    return this.ast;
}
 
Example #5
Source File: CpsTransformer.java    From groovy-cps with Apache License 2.0 6 votes vote down vote up
@Override
public void visitMapExpression(final MapExpression exp) {
    if (exp.getMapEntryExpressions().size() > 125) {
        sourceUnit.addError(new SyntaxException("Map expressions can only contain up to 125 entries",
                exp.getLineNumber(), exp.getColumnNumber()));
    } else {
        makeNode("map", new Runnable() {
            @Override
            public void run() {
                for (MapEntryExpression e : exp.getMapEntryExpressions()) {
                    visit(e.getKeyExpression());
                    visit(e.getValueExpression());
                }
            }
        });
    }
}
 
Example #6
Source File: CpsTransformer.java    From groovy-cps with Apache License 2.0 6 votes vote down vote up
@Override
public void visitArrayExpression(final ArrayExpression exp) {
    if (exp.getSizeExpression() != null) {
        // array instanation like new String[1][2][3]
        makeNode("newArray", new Runnable() {
            @Override
            public void run() {
                loc(exp);
                literal(exp.getElementType());
                visit(exp.getSizeExpression());
            }
        });
    } else {
        // Note - it does not appear this path is actually reachable.
        sourceUnit.addError(new SyntaxException("Unsupported array expression for CPS transformation in this context",
                exp.getLineNumber(), exp.getColumnNumber()));
    }
}
 
Example #7
Source File: MacroGroovyMethods.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected static TupleExpression getMacroArguments(SourceUnit source, MethodCallExpression call) {
    Expression macroCallArguments = call.getArguments();
    if (macroCallArguments == null) {
        source.addError(new SyntaxException("Call should have arguments" + '\n', call));
        return null;
    }

    if (!(macroCallArguments instanceof TupleExpression)) {
        source.addError(new SyntaxException("Call should have TupleExpression as arguments" + '\n', macroCallArguments));
        return null;
    }

    TupleExpression tupleArguments = (TupleExpression) macroCallArguments;

    if (tupleArguments.getExpressions() == null) {
        source.addError(new SyntaxException("Call arguments should have expressions" + '\n', tupleArguments));
        return null;
    }

    return tupleArguments;
}
 
Example #8
Source File: FixImportsAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void collectMissingImports(List errors) {
    for (Object error : errors) {
        if (error instanceof SyntaxErrorMessage) {
            SyntaxException se = ((SyntaxErrorMessage) error).getCause();

            if (se != null) {
                String missingClassName = ImportHelper.getMissingClassName(se.getMessage());

                if (missingClassName != null) {
                    if (!missingNames.contains(missingClassName)) {
                        missingNames.add(missingClassName);
                    }
                }
            }
        }
    }
}
 
Example #9
Source File: DefaultScriptCompilationHandler.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void wrapCompilationFailure(ScriptSource source, MultipleCompilationErrorsException e) {
    // Fix the source file name displayed in the error messages
    for (Object message : e.getErrorCollector().getErrors()) {
        if (message instanceof SyntaxErrorMessage) {
            try {
                SyntaxErrorMessage syntaxErrorMessage = (SyntaxErrorMessage) message;
                Field sourceField = SyntaxErrorMessage.class.getDeclaredField("source");
                sourceField.setAccessible(true);
                SourceUnit sourceUnit = (SourceUnit) sourceField.get(syntaxErrorMessage);
                Field nameField = SourceUnit.class.getDeclaredField("name");
                nameField.setAccessible(true);
                nameField.set(sourceUnit, source.getDisplayName());
            } catch (Exception failure) {
                throw UncheckedException.throwAsUncheckedException(failure);
            }
        }
    }

    SyntaxException syntaxError = e.getErrorCollector().getSyntaxError(0);
    Integer lineNumber = syntaxError == null ? null : syntaxError.getLine();
    throw new ScriptCompilationException(String.format("Could not compile %s.", source.getDisplayName()), e, source,
            lineNumber);
}
 
Example #10
Source File: DefaultScriptCompilationHandler.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void wrapCompilationFailure(ScriptSource source, MultipleCompilationErrorsException e) {
    // Fix the source file name displayed in the error messages
    for (Object message : e.getErrorCollector().getErrors()) {
        if (message instanceof SyntaxErrorMessage) {
            try {
                SyntaxErrorMessage syntaxErrorMessage = (SyntaxErrorMessage) message;
                Field sourceField = SyntaxErrorMessage.class.getDeclaredField("source");
                sourceField.setAccessible(true);
                SourceUnit sourceUnit = (SourceUnit) sourceField.get(syntaxErrorMessage);
                Field nameField = SourceUnit.class.getDeclaredField("name");
                nameField.setAccessible(true);
                nameField.set(sourceUnit, source.getDisplayName());
            } catch (Exception failure) {
                throw UncheckedException.throwAsUncheckedException(failure);
            }
        }
    }

    SyntaxException syntaxError = e.getErrorCollector().getSyntaxError(0);
    Integer lineNumber = syntaxError == null ? null : syntaxError.getLine();
    throw new ScriptCompilationException(String.format("Could not compile %s.", source.getDisplayName()), e, source,
            lineNumber);
}
 
Example #11
Source File: DefaultScriptCompilationHandler.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void wrapCompilationFailure(ScriptSource source, MultipleCompilationErrorsException e) {
    // Fix the source file name displayed in the error messages
    for (Object message : e.getErrorCollector().getErrors()) {
        if (message instanceof SyntaxErrorMessage) {
            try {
                SyntaxErrorMessage syntaxErrorMessage = (SyntaxErrorMessage) message;
                Field sourceField = SyntaxErrorMessage.class.getDeclaredField("source");
                sourceField.setAccessible(true);
                SourceUnit sourceUnit = (SourceUnit) sourceField.get(syntaxErrorMessage);
                Field nameField = SourceUnit.class.getDeclaredField("name");
                nameField.setAccessible(true);
                nameField.set(sourceUnit, source.getDisplayName());
            } catch (Exception failure) {
                throw UncheckedException.throwAsUncheckedException(failure);
            }
        }
    }

    SyntaxException syntaxError = e.getErrorCollector().getSyntaxError(0);
    Integer lineNumber = syntaxError == null ? null : syntaxError.getLine();
    throw new ScriptCompilationException(String.format("Could not compile %s.", source.getDisplayName()), e, source,
            lineNumber);
}
 
Example #12
Source File: DefaultScriptCompilationHandler.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void wrapCompilationFailure(ScriptSource source, MultipleCompilationErrorsException e) {
    // Fix the source file name displayed in the error messages
    for (Object message : e.getErrorCollector().getErrors()) {
        if (message instanceof SyntaxErrorMessage) {
            try {
                SyntaxErrorMessage syntaxErrorMessage = (SyntaxErrorMessage) message;
                Field sourceField = SyntaxErrorMessage.class.getDeclaredField("source");
                sourceField.setAccessible(true);
                SourceUnit sourceUnit = (SourceUnit) sourceField.get(syntaxErrorMessage);
                Field nameField = SourceUnit.class.getDeclaredField("name");
                nameField.setAccessible(true);
                nameField.set(sourceUnit, source.getDisplayName());
            } catch (Exception failure) {
                throw UncheckedException.throwAsUncheckedException(failure);
            }
        }
    }

    SyntaxException syntaxError = e.getErrorCollector().getSyntaxError(0);
    Integer lineNumber = syntaxError == null ? null : syntaxError.getLine();
    throw new ScriptCompilationException(String.format("Could not compile %s.", source.getDisplayName()), e, source,
            lineNumber);
}
 
Example #13
Source File: TraitASTTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkInnerClasses(final ClassNode cNode) {
    Iterator<InnerClassNode> it = cNode.getInnerClasses();
    while (it.hasNext()) {
        InnerClassNode origin = it.next();
        if ((origin.getModifiers() & ACC_STATIC) == 0) {
            unit.addError(new SyntaxException("Cannot have non-static inner class inside a trait ("+origin.getName()+")", origin.getLineNumber(), origin.getColumnNumber()));
        }
    }
}
 
Example #14
Source File: NAryOperationRewriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression transformPrefixExpression(final PrefixExpression exp) {
    if (isInternalFieldAccess(exp.getExpression())) {
        Token operation = exp.getOperation();
        sourceUnit.addError(new SyntaxException("Prefix expressions on trait fields/properties are not supported in traits.", operation.getStartLine(), operation.getStartColumn()));
        return exp;
    } else {
        return super.transform(exp);
    }
}
 
Example #15
Source File: SyntaxErrorMessageTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void testSetsTheSourceLocatorOfItsSyntaxExceptionAsTheNameOfTheCorrespondingSourceUnitWhenInstantiated() {
    SyntaxException syntaxException = new SyntaxException(someString(), -1, -1);
    assertEquals("source locator", null, syntaxException.getSourceLocator());

    String sourceUnitName = someString();
    SourceUnit sourceUnit = SourceUnit.create(sourceUnitName, someString());

    new SyntaxErrorMessage(syntaxException, sourceUnit);
    assertEquals("source locator", sourceUnitName, syntaxException.getSourceLocator());
}
 
Example #16
Source File: EnumVisitor.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void addError(final AnnotatedNode exp, final String msg) {
    getSourceUnit().getErrorCollector().addErrorAndContinue(
            new SyntaxErrorMessage(
                    new SyntaxException(msg + '\n', exp),
                    getSourceUnit()
            )
    );
}
 
Example #17
Source File: NAryOperationRewriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Expression transformPostfixExpression(final PostfixExpression exp) {
    if (isInternalFieldAccess(exp.getExpression())) {
        Token operation = exp.getOperation();
        sourceUnit.addError(new SyntaxException("Postfix expressions on trait fields/properties  are not supported in traits.", operation.getStartLine(), operation.getStartColumn()));
        return exp;
    } else {
        return super.transform(exp);
    }
}
 
Example #18
Source File: TraitComposer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static void checkTraitAllowed(final ClassNode bottomTrait, final SourceUnit unit) {
    ClassNode superClass = bottomTrait.getSuperClass();
    if (superClass==null || ClassHelper.OBJECT_TYPE.equals(superClass)) return;
    if (!Traits.isTrait(superClass)) {
        unit.addError(new SyntaxException("A trait can only inherit from another trait", superClass.getLineNumber(), superClass.getColumnNumber()));
    }
}
 
Example #19
Source File: TraitComposer.java    From groovy with Apache License 2.0 5 votes vote down vote up
private static SyntaxException createException(ClassNode trait, ClassNode targetNode, MethodNode forwarder, MethodNode existingMethod) {
    String middle;
    ASTNode errorTarget;
    if (existingMethod.getLineNumber() == -1) {
        // came from a trait
        errorTarget = targetNode;
        List<AnnotationNode> allAnnos = existingMethod.getAnnotations(Traits.TRAITBRIDGE_CLASSNODE);
        AnnotationNode bridgeAnno = allAnnos == null ? null : allAnnos.get(0);
        String fromTrait = null;
        if (bridgeAnno != null) {
            Expression traitClass = bridgeAnno.getMember("traitClass");
            if (traitClass instanceof ClassExpression) {
                ClassExpression ce = (ClassExpression) traitClass;
                fromTrait = ce.getType().getNameWithoutPackage();
            }
        }
        middle = "in '" + targetNode.getNameWithoutPackage();
        if (fromTrait != null) {
            middle += "' from trait '" + fromTrait;
        }
    } else {
        errorTarget = existingMethod;
        middle = "declared in '" + targetNode.getNameWithoutPackage();
    }
    String message = "The static '" + forwarder.getName() + "' method " + middle +
            "' conflicts with the instance method having the same signature from trait '" + trait.getNameWithoutPackage() + "'";
    return new SyntaxException(message, errorTarget);
}
 
Example #20
Source File: GroovyScriptEngineImpl.java    From hasor with Apache License 2.0 5 votes vote down vote up
Class getScriptClass(String script) throws SyntaxException, CompilationFailedException, IOException {
    Class clazz = classMap.get(script);
    if (clazz != null) {
        return clazz;
    }
    clazz = loader.parseClass(script, generateScriptName());
    classMap.put(script, clazz);
    return clazz;
}
 
Example #21
Source File: StaticInvocationWriter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void checkAndAddCannotCallPrivateMethodError(final MethodNode target, final Expression receiver, final ClassNode classNode, final ClassNode declaringClass) {
    if (declaringClass != classNode) {
        controller.getSourceUnit().addError(new SyntaxException(
                "Cannot call private method " + (target.isStatic() ? "static " : "") + declaringClass.toString(false) + "#" + target.getName() + " from class " + classNode.toString(false),
                receiver
        ));
    }
}
 
Example #22
Source File: StaticTypesTransformation.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void visit(ASTNode[] nodes, SourceUnit source) {
    AnnotationNode annotationInformation = (AnnotationNode) nodes[0];
    Map<String,Expression> members = annotationInformation.getMembers();
    Expression extensions = members.get("extensions");
    AnnotatedNode node = (AnnotatedNode) nodes[1];
    StaticTypeCheckingVisitor visitor = null;
    if (node instanceof ClassNode) {
        ClassNode classNode = (ClassNode) node;
        visitor = newVisitor(source, classNode);
        visitor.setCompilationUnit(compilationUnit);
        addTypeCheckingExtensions(visitor, extensions);
        visitor.initialize();
        visitor.visitClass(classNode);
    } else if (node instanceof MethodNode) {
        MethodNode methodNode = (MethodNode) node;
        visitor = newVisitor(source, methodNode.getDeclaringClass());
        visitor.setCompilationUnit(compilationUnit);
        addTypeCheckingExtensions(visitor, extensions);
        visitor.setMethodsToBeVisited(Collections.singleton(methodNode));
        visitor.initialize();
        visitor.visitMethod(methodNode);
    } else {
        source.addError(new SyntaxException(STATIC_ERROR_PREFIX + "Unimplemented node type",
                node.getLineNumber(), node.getColumnNumber(), node.getLastLineNumber(), node.getLastColumnNumber()));
    }
    if (visitor != null) {
        visitor.performSecondPass();
    }
}
 
Example #23
Source File: ModelBlockTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void call(SourceUnit source) throws CompilationFailedException {
    if (!isEnabled()) {
        return;
    }

    List<Statement> statements = source.getAST().getStatementBlock().getStatements();
    for (Statement statement : statements) {
        ScriptBlock scriptBlock = AstUtils.detectScriptBlock(statement, SCRIPT_BLOCK_NAMES);
        if (scriptBlock == null) {
            // Look for model(«») (i.e. call to model with anything other than non literal closure)
            MethodCallExpression methodCall = AstUtils.extractBareMethodCall(statement);
            if (methodCall == null) {
                continue;
            }

            String methodName = AstUtils.extractConstantMethodName(methodCall);
            if (methodName == null) {
                continue;
            }

            if (methodName.equals(MODEL)) {
                source.getErrorCollector().addError(
                        new SyntaxException(NON_LITERAL_CLOSURE_TO_TOP_LEVEL_MODEL_MESSAGE, statement.getLineNumber(), statement.getColumnNumber()),
                        source
                );
            }
        } else {
            RuleVisitor ruleVisitor = new RuleVisitor(source);
            RulesVisitor rulesVisitor = new RulesVisitor(source, ruleVisitor);
            scriptBlock.getClosureExpression().getCode().visit(rulesVisitor);
        }
    }
}
 
Example #24
Source File: CompileUnit.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a class to the unit.
 */
public void addClass(ClassNode node) {
    node = node.redirect();
    String name = node.getName();
    ClassNode stored = classes.get(name);
    if (stored != null && stored != node) {
        // we have a duplicate class!
        // One possibility for this is, that we declared a script and a
        // class in the same file and named the class like the file
        SourceUnit nodeSource = node.getModule().getContext();
        SourceUnit storedSource = stored.getModule().getContext();
        String txt = "Invalid duplicate class definition of class " + node.getName() + " : ";
        if (nodeSource == storedSource) {
            // same class in same source
            txt += "The source " + nodeSource.getName() + " contains at least two definitions of the class " + node.getName() + ".\n";
            if (node.isScriptBody() || stored.isScriptBody()) {
                txt += "One of the classes is an explicit generated class using the class statement, the other is a class generated from" +
                        " the script body based on the file name. Solutions are to change the file name or to change the class name.\n";
            }
        } else {
            txt += "The sources " + nodeSource.getName() + " and " + storedSource.getName() + " each contain a class with the name " + node.getName() + ".\n";
        }
        nodeSource.getErrorCollector().addErrorAndContinue(
                new SyntaxErrorMessage(new SyntaxException(txt, node.getLineNumber(), node.getColumnNumber(), node.getLastLineNumber(), node.getLastColumnNumber()), nodeSource)
        );
    }
    classes.put(name, node);

    ClassNode cn = classesToCompile.get(name);
    if (null != cn) {
        cn.setRedirect(node);
        classesToCompile.remove(name);
    }
}
 
Example #25
Source File: ClassCodeVisitorSupport.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void addError(String error, ASTNode node) {
    SourceUnit source = getSourceUnit();
    source.getErrorCollector().addErrorAndContinue(
            new SyntaxErrorMessage(new SyntaxException(error + '\n', node.getLineNumber(), node.getColumnNumber(), node.getLastLineNumber(), node.getLastColumnNumber()), source)
    );
}
 
Example #26
Source File: SourceUnit.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Convenience wrapper for {@link ErrorCollector#addFatalError(org.codehaus.groovy.control.messages.Message)}.
 *
 * @param msg the error message
 * @param node the AST node
 * @throws CompilationFailedException on error
 * @since 3.0.0
 */
public void addFatalError(String msg, ASTNode node) throws CompilationFailedException {
    getErrorCollector().addFatalError(
            new SyntaxErrorMessage(
                    new SyntaxException(
                            msg,
                            node.getLineNumber(),
                            node.getColumnNumber(),
                            node.getLastLineNumber(),
                            node.getLastColumnNumber()
                    ),
                    this
            )
    );
}
 
Example #27
Source File: ModelBlockTransformer.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void call(SourceUnit source) throws CompilationFailedException {
    if (!isEnabled()) {
        return;
    }

    List<Statement> statements = source.getAST().getStatementBlock().getStatements();
    for (Statement statement : statements) {
        ScriptBlock scriptBlock = AstUtils.detectScriptBlock(statement, SCRIPT_BLOCK_NAMES);
        if (scriptBlock == null) {
            // Look for model(«») (i.e. call to model with anything other than non literal closure)
            MethodCallExpression methodCall = AstUtils.extractBareMethodCall(statement);
            if (methodCall == null) {
                continue;
            }

            String methodName = AstUtils.extractConstantMethodName(methodCall);
            if (methodName == null) {
                continue;
            }

            if (methodName.equals(MODEL)) {
                source.getErrorCollector().addError(
                        new SyntaxException(NON_LITERAL_CLOSURE_TO_TOP_LEVEL_MODEL_MESSAGE, statement.getLineNumber(), statement.getColumnNumber()),
                        source
                );
            }
        } else {
            RuleVisitor ruleVisitor = new RuleVisitor(source);
            RulesVisitor rulesVisitor = new RulesVisitor(source, ruleVisitor);
            scriptBlock.getClosureExpression().getCode().visit(rulesVisitor);
        }
    }
}
 
Example #28
Source File: StreamingTemplateEngine.java    From groovy with Apache License 2.0 5 votes vote down vote up
private RuntimeException mangleMultipleCompilationErrorsException(MultipleCompilationErrorsException e, List<StringSection> sections) {
    RuntimeException result = e;

    ErrorCollector collector = e.getErrorCollector();
    @SuppressWarnings({"unchecked"})
    List<Message> errors = (List<Message>) collector.getErrors();
    if (!errors.isEmpty()) {
        Message firstMessage = errors.get(0);
        if (firstMessage instanceof SyntaxErrorMessage) {
            @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"})
            SyntaxException syntaxException = ((SyntaxErrorMessage) firstMessage).getCause();
            Position errorPosition = new Position(syntaxException.getLine(), syntaxException.getStartColumn());

            //find the string section which precedes the row/col of the thrown exception
            StringSection precedingSection = findPrecedingSection(errorPosition, sections);

            //and now use the string section to mangle the line numbers so that they refer to the
            //appropriate line in the source template data
            if (precedingSection != null) {
                //if the error was thrown on the same row as where the last string section
                //ended, fix column value
                offsetPositionFromSection(errorPosition, precedingSection);
                //the below being true indicates that we had an unterminated ${ or <% sequence and
                //the column is thus meaningless, we reset it to where the %{ or <% starts to at
                //least give the user a sporting chance
                if (sections.get(sections.size() - 1) == precedingSection) {
                    errorPosition.column = precedingSection.lastSourcePosition.column;
                }

                String message = mangleExceptionMessage(e.getMessage(), errorPosition);
                result = new TemplateParseException(message, e, errorPosition.row, errorPosition.column);
            }
        }
    }

    return result;
}
 
Example #29
Source File: MacroGroovyMethods.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Macro
public static Expression macro(MacroContext macroContext, PropertyExpression phaseExpression, ConstantExpression asIsConstantExpression, ClosureExpression closureExpression) {
    if (closureExpression.getParameters() != null && closureExpression.getParameters().length > 0) {
        macroContext.getSourceUnit().addError(new SyntaxException("Macro closure arguments are not allowed" + '\n', closureExpression));
        return macroContext.getCall();
    }

    final String source;
    try {
        source = ClosureUtils.convertClosureToSource(macroContext.getSourceUnit().getSource(), closureExpression);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    BlockStatement closureBlock = (BlockStatement) closureExpression.getCode();

    Boolean asIs = (Boolean) asIsConstantExpression.getValue();

    return callX(
            propX(classX(ClassHelper.makeWithoutCaching(MacroBuilder.class, false)), "INSTANCE"),
            "macro",
            args(
                    phaseExpression != null ? phaseExpression : constX(null),
                    asIsConstantExpression,
                    constX(source),
                    buildSubstitutions(macroContext.getSourceUnit(), closureExpression),
                    classX(ClassHelper.makeWithoutCaching(MacroBuilder.getMacroValue(closureBlock, asIs).getClass(), false))
            )
    );
}
 
Example #30
Source File: CpsTransformer.java    From groovy-cps with Apache License 2.0 5 votes vote down vote up
@Override
public void visitListExpression(final ListExpression exp) {
    if (exp.getExpressions().size() > 250) {
        sourceUnit.addError(new SyntaxException("List expressions can only contain up to 250 elements",
                exp.getLineNumber(), exp.getColumnNumber()));
    } else {
        makeNode("list", new Runnable() {
            @Override
            public void run() {
                visit(exp.getExpressions());
            }
        });
    }
}