Search in sources :

Example 31 with SyntaxException

use of org.codehaus.groovy.syntax.SyntaxException in project gcontracts by andresteingress.

the class ProcessingContextInformation method addError.

public void addError(String msg, ASTNode expr) {
    int line = expr.getLineNumber();
    int col = expr.getColumnNumber();
    SourceUnit source = sourceUnit();
    source.getErrorCollector().addErrorAndContinue(new SyntaxErrorMessage(new SyntaxException(msg + '\n', line, col), source));
}
Also used : SyntaxErrorMessage(org.codehaus.groovy.control.messages.SyntaxErrorMessage) SyntaxException(org.codehaus.groovy.syntax.SyntaxException) SourceUnit(org.codehaus.groovy.control.SourceUnit)

Example 32 with SyntaxException

use of org.codehaus.groovy.syntax.SyntaxException in project hale by halestudio.

the class GroovyScriptPage method addGroovyErrorAnnotation.

/**
 * Add an error annotation to the given annotation model based on an
 * exception that occurred while compiling or executing the Groovy Script.
 *
 * @param annotationModel the annotation model
 * @param document the current document
 * @param script the executed script, or <code>null</code>
 * @param exception the occurred exception
 */
public static void addGroovyErrorAnnotation(IAnnotationModel annotationModel, IDocument document, Script script, Exception exception) {
    // handle multiple groovy compilation errors
    if (exception instanceof MultipleCompilationErrorsException) {
        ErrorCollector errors = ((MultipleCompilationErrorsException) exception).getErrorCollector();
        for (int i = 0; i < errors.getErrorCount(); i++) {
            SyntaxException ex = errors.getSyntaxError(i);
            if (ex != null) {
                addGroovyErrorAnnotation(annotationModel, document, script, ex);
            }
        }
        return;
    }
    Annotation annotation = new Annotation(SimpleAnnotations.TYPE_ERROR, false, exception.getLocalizedMessage());
    Position position = null;
    // single syntax exception
    if (exception instanceof SyntaxException) {
        int line = ((SyntaxException) exception).getStartLine() - 1;
        if (line >= 0) {
            try {
                position = new Position(document.getLineOffset(line));
            } catch (BadLocationException e1) {
                log.warn("Wrong error position in document", e1);
            }
        }
    }
    // try to determine position from stack trace of script execution
    if (position == null && script != null) {
        for (StackTraceElement ste : exception.getStackTrace()) {
            if (ste.getClassName().startsWith(script.getClass().getName())) {
                int line = ste.getLineNumber() - 1;
                if (line >= 0) {
                    try {
                        position = new Position(document.getLineOffset(line));
                        break;
                    } catch (BadLocationException e1) {
                        log.warn("Wrong error position in document", e1);
                    }
                }
            }
        }
    }
    // fallback
    if (position == null) {
        position = new Position(0);
    }
    annotationModel.addAnnotation(annotation, position);
}
Also used : Position(org.eclipse.jface.text.Position) SyntaxException(org.codehaus.groovy.syntax.SyntaxException) ErrorCollector(org.codehaus.groovy.control.ErrorCollector) MultipleCompilationErrorsException(org.codehaus.groovy.control.MultipleCompilationErrorsException) Annotation(org.eclipse.jface.text.source.Annotation) BadLocationException(org.eclipse.jface.text.BadLocationException)

Example 33 with SyntaxException

use of org.codehaus.groovy.syntax.SyntaxException in project groovy by apache.

the class StaticTypesCallSiteWriter method addPropertyAccessError.

/*private boolean getField(final PropertyExpression expression, final Expression receiver, ClassNode receiverType, final String name) {
        boolean safe = expression.isSafe();
        boolean implicitThis = expression.isImplicitThis();

        if (makeGetField(receiver, receiverType, name, safe, implicitThis)) return true;
        if (receiver instanceof ClassExpression) {
            if (makeGetField(receiver, receiver.getType(), name, safe, implicitThis)) return true;
            if (makeGetPrivateFieldWithBridgeMethod(receiver, receiver.getType(), name, safe, implicitThis)) return true;
        }
        if (makeGetPrivateFieldWithBridgeMethod(receiver, receiverType, name, safe, implicitThis)) return true;

        boolean isClassReceiver = false;
        if (isClassClassNodeWrappingConcreteType(receiverType)) {
            isClassReceiver = true;
            receiverType = receiverType.getGenericsTypes()[0].getType();
        }
        if (isClassReceiver && makeGetField(receiver, CLASS_Type, name, safe, false)) return true;
        if (receiverType.isEnum()) {
            controller.getMethodVisitor().visitFieldInsn(GETSTATIC, BytecodeHelper.getClassInternalName(receiverType), name, BytecodeHelper.getTypeDescription(receiverType));
            controller.getOperandStack().push(receiverType);
            return true;
        }
        return false;
    }*/
private void addPropertyAccessError(final Expression receiver, final String propertyName, final ClassNode receiverType) {
    String receiverName = (receiver instanceof ClassExpression ? receiver.getType() : receiverType).toString(false);
    String message = "Access to " + receiverName + "#" + propertyName + " is forbidden";
    controller.getSourceUnit().addError(new SyntaxException(message, receiver));
}
Also used : SyntaxException(org.codehaus.groovy.syntax.SyntaxException) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression)

Example 34 with SyntaxException

use of org.codehaus.groovy.syntax.SyntaxException in project groovy by apache.

the class InvocationWriter method makeMOPBasedConstructorCall.

private void makeMOPBasedConstructorCall(final List<ConstructorNode> constructors, final ConstructorCallExpression call, final ClassNode callNode) {
    MethodVisitor mv = controller.getMethodVisitor();
    OperandStack operandStack = controller.getOperandStack();
    call.getArguments().visit(controller.getAcg());
    // keep Object[] on stack
    mv.visitInsn(DUP);
    // to select the constructor we need also the number of
    // available constructors and the class we want to make
    // the call on
    BytecodeHelper.pushConstant(mv, -1);
    controller.getAcg().visitClassExpression(new ClassExpression(callNode));
    operandStack.remove(1);
    // removes one Object[] leaves the int containing the
    // call flags and the constructor number
    selectConstructorAndTransformArguments.call(mv);
    // load "this"
    if (controller.isConstructor()) {
        mv.visitVarInsn(ALOAD, 0);
    } else {
        mv.visitTypeInsn(NEW, BytecodeHelper.getClassInternalName(callNode));
    }
    mv.visitInsn(SWAP);
    TreeMap<Integer, ConstructorNode> sortedConstructors = new TreeMap<>();
    for (ConstructorNode constructor : constructors) {
        String typeDescriptor = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, constructor.getParameters());
        int hash = BytecodeHelper.hashCode(typeDescriptor);
        ConstructorNode sameHashNode = sortedConstructors.put(hash, constructor);
        if (sameHashNode != null) {
            controller.getSourceUnit().addError(new SyntaxException("Unable to compile class " + controller.getClassNode().getName() + " due to hash collision in constructors", call.getLineNumber(), call.getColumnNumber()));
        }
    }
    Label[] targets = new Label[constructors.size()];
    int[] indices = new int[constructors.size()];
    Iterator<Integer> hashIt = sortedConstructors.keySet().iterator();
    Iterator<ConstructorNode> constructorIt = sortedConstructors.values().iterator();
    for (int i = 0, n = targets.length; i < n; i += 1) {
        targets[i] = new Label();
        indices[i] = hashIt.next();
    }
    // create switch targets
    Label defaultLabel = new Label();
    Label afterSwitch = new Label();
    mv.visitLookupSwitchInsn(defaultLabel, indices, targets);
    for (Label target : targets) {
        mv.visitLabel(target);
        // to extract the parameters.
        if (controller.isConstructor()) {
            // in this case we need one "this", so a SWAP will exchange
            // "this" and Object[], a DUP_X1 will then copy the Object[]
            // / to the last place in the stack:
            // Object[],this -SWAP-> this,Object[]
            // this,Object[] -DUP_X1-> Object[],this,Object[]
            mv.visitInsn(SWAP);
            mv.visitInsn(DUP_X1);
        } else {
            // in this case we need two "this" in between and the Object[]
            // at the bottom of the stack as well as on top for our invokeSpecial
            // So we do DUP_X1, DUP2_X1, POP
            // Object[],this -DUP_X1-> this,Object[],this
            // this,Object[],this -DUP2_X1-> Object[],this,this,Object[],this
            // Object[],this,this,Object[],this -POP->  Object[],this,this,Object[]
            mv.visitInsn(DUP_X1);
            mv.visitInsn(DUP2_X1);
            mv.visitInsn(POP);
        }
        ConstructorNode cn = constructorIt.next();
        String descriptor = BytecodeHelper.getMethodDescriptor(ClassHelper.VOID_TYPE, cn.getParameters());
        // unwrap the Object[] and make transformations if needed
        // that means, to duplicate the Object[], make a cast with possible
        // unboxing and then swap it with the Object[] for each parameter
        // vargs need special attention and transformation though
        Parameter[] parameters = cn.getParameters();
        int lengthWithoutVargs = parameters.length;
        if (parameters.length > 0 && parameters[parameters.length - 1].getType().isArray()) {
            lengthWithoutVargs -= 1;
        }
        for (int p = 0; p < lengthWithoutVargs; p += 1) {
            loadAndCastElement(operandStack, mv, parameters, p);
        }
        if (parameters.length > lengthWithoutVargs) {
            ClassNode type = parameters[lengthWithoutVargs].getType();
            BytecodeHelper.pushConstant(mv, lengthWithoutVargs);
            controller.getAcg().visitClassExpression(new ClassExpression(type));
            operandStack.remove(1);
            castToVargsArray.call(mv);
            BytecodeHelper.doCast(mv, type);
        } else {
            // at the end we remove the Object[]
            // the vargs case simply the last swap so no pop is needed
            mv.visitInsn(POP);
        }
        // make the constructor call
        mv.visitMethodInsn(INVOKESPECIAL, BytecodeHelper.getClassInternalName(callNode), "<init>", descriptor, false);
        mv.visitJumpInsn(GOTO, afterSwitch);
    }
    mv.visitLabel(defaultLabel);
    // this part should never be reached!
    mv.visitTypeInsn(NEW, "java/lang/IllegalArgumentException");
    mv.visitInsn(DUP);
    mv.visitLdcInsn("This class has been compiled with a super class which is binary incompatible with the current super class found on classpath. You should recompile this class with the new version.");
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/IllegalArgumentException", "<init>", "(Ljava/lang/String;)V", false);
    mv.visitInsn(ATHROW);
    mv.visitLabel(afterSwitch);
    // result on the stack, which we can remove now if inside a constructor.
    if (!controller.isConstructor()) {
        // in case we are not in a constructor we have an additional
        // object on the stack, the result of our constructor call
        // which we want to keep, so we swap with the dummy object and
        // do normal removal of it. In the end, the call result will be
        // on the stack then
        mv.visitInsn(SWAP);
        // for call result
        operandStack.push(callNode);
    }
    mv.visitInsn(POP);
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) Label(org.objectweb.asm.Label) ClassExpression(org.codehaus.groovy.ast.expr.ClassExpression) TreeMap(java.util.TreeMap) MethodVisitor(org.objectweb.asm.MethodVisitor) ConstructorNode(org.codehaus.groovy.ast.ConstructorNode) SyntaxException(org.codehaus.groovy.syntax.SyntaxException) Parameter(org.codehaus.groovy.ast.Parameter)

Example 35 with SyntaxException

use of org.codehaus.groovy.syntax.SyntaxException in project groovy by apache.

the class StaticCompileTransformation method visit.

@Override
public void visit(final ASTNode[] nodes, final SourceUnit source) {
    AnnotatedNode target = (AnnotatedNode) nodes[1];
    if (Boolean.TRUE.equals(target.getNodeMetaData(StaticTypeCheckingVisitor.class))) {
        return;
    }
    Map<String, Expression> members = ((AnnotationNode) nodes[0]).getMembers();
    Expression extensions = members.get("extensions");
    StaticTypeCheckingVisitor visitor = null;
    if (target instanceof ClassNode) {
        ClassNode classNode = (ClassNode) target;
        visitor = newVisitor(source, classNode);
        visitor.setCompilationUnit(compilationUnit);
        addTypeCheckingExtensions(visitor, extensions);
        classNode.putNodeMetaData(WriterControllerFactory.class, factory);
        target.putNodeMetaData(STATIC_COMPILE_NODE, !visitor.isSkipMode(target));
        visitor.initialize();
        visitor.visitClass(classNode);
    } else if (target instanceof MethodNode) {
        MethodNode methodNode = (MethodNode) target;
        ClassNode declaringClass = methodNode.getDeclaringClass();
        visitor = newVisitor(source, declaringClass);
        visitor.setCompilationUnit(compilationUnit);
        addTypeCheckingExtensions(visitor, extensions);
        methodNode.putNodeMetaData(STATIC_COMPILE_NODE, !visitor.isSkipMode(target));
        if (declaringClass.getNodeMetaData(WriterControllerFactory.class) == null) {
            declaringClass.putNodeMetaData(WriterControllerFactory.class, factory);
        }
        visitor.setMethodsToBeVisited(Collections.singleton(methodNode));
        visitor.initialize();
        visitor.visitMethod(methodNode);
    } else if (!(target instanceof PropertyNode)) {
        source.addError(new SyntaxException(STATIC_ERROR_PREFIX + "Unimplemented node type", target));
    }
    if (visitor != null) {
        visitor.performSecondPass();
    }
    StaticCompilationTransformer transformer = new StaticCompilationTransformer(source, visitor);
    if (target instanceof ClassNode) {
        transformer.visitClass((ClassNode) target);
    } else if (target instanceof MethodNode) {
        transformer.visitMethod((MethodNode) target);
    }
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) MethodNode(org.codehaus.groovy.ast.MethodNode) Expression(org.codehaus.groovy.ast.expr.Expression) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) StaticTypeCheckingVisitor(org.codehaus.groovy.transform.stc.StaticTypeCheckingVisitor) PropertyNode(org.codehaus.groovy.ast.PropertyNode) SyntaxException(org.codehaus.groovy.syntax.SyntaxException) AnnotatedNode(org.codehaus.groovy.ast.AnnotatedNode) WriterControllerFactory(org.codehaus.groovy.classgen.asm.WriterControllerFactory) StaticCompilationTransformer(org.codehaus.groovy.transform.sc.transformers.StaticCompilationTransformer)

Aggregations

SyntaxException (org.codehaus.groovy.syntax.SyntaxException)56 SyntaxErrorMessage (org.codehaus.groovy.control.messages.SyntaxErrorMessage)19 ClassNode (org.codehaus.groovy.ast.ClassNode)15 Expression (org.codehaus.groovy.ast.expr.Expression)12 MethodNode (org.codehaus.groovy.ast.MethodNode)11 SourceUnit (org.codehaus.groovy.control.SourceUnit)10 AnnotationNode (org.codehaus.groovy.ast.AnnotationNode)8 MethodCallExpression (org.codehaus.groovy.ast.expr.MethodCallExpression)8 FieldNode (org.codehaus.groovy.ast.FieldNode)7 InnerClassNode (org.codehaus.groovy.ast.InnerClassNode)7 ConstantExpression (org.codehaus.groovy.ast.expr.ConstantExpression)7 ArrayList (java.util.ArrayList)6 Parameter (org.codehaus.groovy.ast.Parameter)6 ClassExpression (org.codehaus.groovy.ast.expr.ClassExpression)6 PropertyExpression (org.codehaus.groovy.ast.expr.PropertyExpression)6 Token (org.codehaus.groovy.syntax.Token)6 LinkedList (java.util.LinkedList)5 PropertyNode (org.codehaus.groovy.ast.PropertyNode)5 TupleExpression (org.codehaus.groovy.ast.expr.TupleExpression)5 VariableExpression (org.codehaus.groovy.ast.expr.VariableExpression)5