Search in sources :

Example 1 with Flow

use of org.apache.tapestry5.func.Flow in project tapestry-5 by apache.

the class JSRInlinerAdapter method emitInstantiation.

/**
 * Emits an instantiation of a subroutine, specified by <code>instantiation</code>. May add new
 * instantiations that are invoked by this one to the <code>worklist</code>, and new try/catch
 * blocks to <code>newTryCatchBlocks</code>.
 *
 * @param instantiation the instantiation that must be performed.
 * @param worklist list of the instantiations that remain to be done.
 * @param newInstructions the instruction list to which the instantiated code must be appended.
 * @param newTryCatchBlocks the exception handler list to which the instantiated handlers must be
 *     appended.
 * @param newLocalVariables the local variables list to which the instantiated local variables
 *     must be appended.
 */
private void emitInstantiation(final Instantiation instantiation, final List<Instantiation> worklist, final InsnList newInstructions, final List<TryCatchBlockNode> newTryCatchBlocks, final List<LocalVariableNode> newLocalVariables) {
    LabelNode previousLabelNode = null;
    for (int i = 0; i < instructions.size(); ++i) {
        AbstractInsnNode insnNode = instructions.get(i);
        if (insnNode.getType() == AbstractInsnNode.LABEL) {
            // Always clone all labels, while avoiding to add the same label more than once.
            LabelNode labelNode = (LabelNode) insnNode;
            LabelNode clonedLabelNode = instantiation.getClonedLabel(labelNode);
            if (clonedLabelNode != previousLabelNode) {
                newInstructions.add(clonedLabelNode);
                previousLabelNode = clonedLabelNode;
            }
        } else if (instantiation.findOwner(i) == instantiation) {
            if (insnNode.getOpcode() == RET) {
                // Translate RET instruction(s) to a jump to the return label for the appropriate
                // instantiation. The problem is that the subroutine may "fall through" to the ret of a
                // parent subroutine; therefore, to find the appropriate ret label we find the oldest
                // instantiation that claims to own this instruction.
                LabelNode retLabel = null;
                for (Instantiation retLabelOwner = instantiation; retLabelOwner != null; retLabelOwner = retLabelOwner.parent) {
                    if (retLabelOwner.subroutineInsns.get(i)) {
                        retLabel = retLabelOwner.returnLabel;
                    }
                }
                if (retLabel == null) {
                    // never happen for verifiable code.
                    throw new IllegalArgumentException("Instruction #" + i + " is a RET not owned by any subroutine");
                }
                newInstructions.add(new JumpInsnNode(GOTO, retLabel));
            } else if (insnNode.getOpcode() == JSR) {
                LabelNode jsrLabelNode = ((JumpInsnNode) insnNode).label;
                BitSet subroutineInsns = subroutinesInsns.get(jsrLabelNode);
                Instantiation newInstantiation = new Instantiation(instantiation, subroutineInsns);
                LabelNode clonedJsrLabelNode = newInstantiation.getClonedLabelForJumpInsn(jsrLabelNode);
                // Replace the JSR instruction with a GOTO to the instantiated subroutine, and push NULL
                // for what was once the return address value. This hack allows us to avoid doing any sort
                // of data flow analysis to figure out which instructions manipulate the old return
                // address value pointer which is now known to be unneeded.
                newInstructions.add(new InsnNode(ACONST_NULL));
                newInstructions.add(new JumpInsnNode(GOTO, clonedJsrLabelNode));
                newInstructions.add(newInstantiation.returnLabel);
                // Insert this new instantiation into the queue to be emitted later.
                worklist.add(newInstantiation);
            } else {
                newInstructions.add(insnNode.clone(instantiation));
            }
        }
    }
    // Emit the try/catch blocks that are relevant for this instantiation.
    for (TryCatchBlockNode tryCatchBlockNode : tryCatchBlocks) {
        final LabelNode start = instantiation.getClonedLabel(tryCatchBlockNode.start);
        final LabelNode end = instantiation.getClonedLabel(tryCatchBlockNode.end);
        if (start != end) {
            final LabelNode handler = instantiation.getClonedLabelForJumpInsn(tryCatchBlockNode.handler);
            if (start == null || end == null || handler == null) {
                throw new AssertionError("Internal error!");
            }
            newTryCatchBlocks.add(new TryCatchBlockNode(start, end, handler, tryCatchBlockNode.type));
        }
    }
    // Emit the local variable nodes that are relevant for this instantiation.
    for (LocalVariableNode localVariableNode : localVariables) {
        final LabelNode start = instantiation.getClonedLabel(localVariableNode.start);
        final LabelNode end = instantiation.getClonedLabel(localVariableNode.end);
        if (start != end) {
            newLocalVariables.add(new LocalVariableNode(localVariableNode.name, localVariableNode.desc, localVariableNode.signature, start, end, localVariableNode.index));
        }
    }
}
Also used : LabelNode(org.apache.tapestry5.internal.plastic.asm.tree.LabelNode) LookupSwitchInsnNode(org.apache.tapestry5.internal.plastic.asm.tree.LookupSwitchInsnNode) JumpInsnNode(org.apache.tapestry5.internal.plastic.asm.tree.JumpInsnNode) AbstractInsnNode(org.apache.tapestry5.internal.plastic.asm.tree.AbstractInsnNode) TableSwitchInsnNode(org.apache.tapestry5.internal.plastic.asm.tree.TableSwitchInsnNode) InsnNode(org.apache.tapestry5.internal.plastic.asm.tree.InsnNode) TryCatchBlockNode(org.apache.tapestry5.internal.plastic.asm.tree.TryCatchBlockNode) BitSet(java.util.BitSet) JumpInsnNode(org.apache.tapestry5.internal.plastic.asm.tree.JumpInsnNode) AbstractInsnNode(org.apache.tapestry5.internal.plastic.asm.tree.AbstractInsnNode) LocalVariableNode(org.apache.tapestry5.internal.plastic.asm.tree.LocalVariableNode)

Example 2 with Flow

use of org.apache.tapestry5.func.Flow in project tapestry-5 by apache.

the class JSRInlinerAdapter method findSubroutineInsns.

/**
 * Finds the instructions that belong to the subroutine starting at the given instruction index.
 * For this the control flow graph is visited with a depth first search (this includes the normal
 * control flow and the exception handlers).
 *
 * @param startInsnIndex the index of the first instruction of the subroutine.
 * @param subroutineInsns where the indices of the instructions of the subroutine must be stored.
 * @param visitedInsns the indices of the instructions that have been visited so far (including in
 *     previous calls to this method). This bitset is updated by this method each time a new
 *     instruction is visited. It is used to make sure each instruction is visited at most once.
 */
private void findSubroutineInsns(final int startInsnIndex, final BitSet subroutineInsns, final BitSet visitedInsns) {
    // First find the instructions reachable via normal execution.
    findReachableInsns(startInsnIndex, subroutineInsns, visitedInsns);
    // Then find the instructions reachable via the applicable exception handlers.
    while (true) {
        boolean applicableHandlerFound = false;
        for (TryCatchBlockNode tryCatchBlockNode : tryCatchBlocks) {
            // If the handler has already been processed, skip it.
            int handlerIndex = instructions.indexOf(tryCatchBlockNode.handler);
            if (subroutineInsns.get(handlerIndex)) {
                continue;
            }
            // If an instruction in the exception handler range belongs to the subroutine, the handler
            // can be reached from the routine, and its instructions must be added to the subroutine.
            int startIndex = instructions.indexOf(tryCatchBlockNode.start);
            int endIndex = instructions.indexOf(tryCatchBlockNode.end);
            int firstSubroutineInsnAfterTryCatchStart = subroutineInsns.nextSetBit(startIndex);
            if (firstSubroutineInsnAfterTryCatchStart >= startIndex && firstSubroutineInsnAfterTryCatchStart < endIndex) {
                findReachableInsns(handlerIndex, subroutineInsns, visitedInsns);
                applicableHandlerFound = true;
            }
        }
        // we must examine them again.
        if (!applicableHandlerFound) {
            return;
        }
    }
}
Also used : TryCatchBlockNode(org.apache.tapestry5.internal.plastic.asm.tree.TryCatchBlockNode)

Example 3 with Flow

use of org.apache.tapestry5.func.Flow in project tapestry-5 by apache.

the class Analyzer method findSubroutine.

/**
 * Follows the control flow graph of the currently analyzed method, starting at the given
 * instruction index, and stores a copy of the given subroutine in {@link #subroutines} for each
 * encountered instruction. Jumps to nested subroutines are <i>not</i> followed: instead, the
 * corresponding instructions are put in the given list.
 *
 * @param insnIndex an instruction index.
 * @param subroutine a subroutine.
 * @param jsrInsns where the jsr instructions for nested subroutines must be put.
 * @throws AnalyzerException if the control flow graph can fall off the end of the code.
 */
private void findSubroutine(final int insnIndex, final Subroutine subroutine, final List<AbstractInsnNode> jsrInsns) throws AnalyzerException {
    ArrayList<Integer> instructionIndicesToProcess = new ArrayList<>();
    instructionIndicesToProcess.add(insnIndex);
    while (!instructionIndicesToProcess.isEmpty()) {
        int currentInsnIndex = instructionIndicesToProcess.remove(instructionIndicesToProcess.size() - 1);
        if (currentInsnIndex < 0 || currentInsnIndex >= insnListSize) {
            throw new AnalyzerException(null, "Execution can fall off the end of the code");
        }
        if (subroutines[currentInsnIndex] != null) {
            continue;
        }
        subroutines[currentInsnIndex] = new Subroutine(subroutine);
        AbstractInsnNode currentInsn = insnList.get(currentInsnIndex);
        // Push the normal successors of currentInsn onto instructionIndicesToProcess.
        if (currentInsn instanceof JumpInsnNode) {
            if (currentInsn.getOpcode() == JSR) {
                // Do not follow a jsr, it leads to another subroutine!
                jsrInsns.add(currentInsn);
            } else {
                JumpInsnNode jumpInsn = (JumpInsnNode) currentInsn;
                instructionIndicesToProcess.add(insnList.indexOf(jumpInsn.label));
            }
        } else if (currentInsn instanceof TableSwitchInsnNode) {
            TableSwitchInsnNode tableSwitchInsn = (TableSwitchInsnNode) currentInsn;
            findSubroutine(insnList.indexOf(tableSwitchInsn.dflt), subroutine, jsrInsns);
            for (int i = tableSwitchInsn.labels.size() - 1; i >= 0; --i) {
                LabelNode labelNode = tableSwitchInsn.labels.get(i);
                instructionIndicesToProcess.add(insnList.indexOf(labelNode));
            }
        } else if (currentInsn instanceof LookupSwitchInsnNode) {
            LookupSwitchInsnNode lookupSwitchInsn = (LookupSwitchInsnNode) currentInsn;
            findSubroutine(insnList.indexOf(lookupSwitchInsn.dflt), subroutine, jsrInsns);
            for (int i = lookupSwitchInsn.labels.size() - 1; i >= 0; --i) {
                LabelNode labelNode = lookupSwitchInsn.labels.get(i);
                instructionIndicesToProcess.add(insnList.indexOf(labelNode));
            }
        }
        // Push the exception handler successors of currentInsn onto instructionIndicesToProcess.
        List<TryCatchBlockNode> insnHandlers = handlers[currentInsnIndex];
        if (insnHandlers != null) {
            for (TryCatchBlockNode tryCatchBlock : insnHandlers) {
                instructionIndicesToProcess.add(insnList.indexOf(tryCatchBlock.handler));
            }
        }
        // Push the next instruction, if the control flow can go from currentInsn to the next.
        switch(currentInsn.getOpcode()) {
            case GOTO:
            case RET:
            case TABLESWITCH:
            case LOOKUPSWITCH:
            case IRETURN:
            case LRETURN:
            case FRETURN:
            case DRETURN:
            case ARETURN:
            case RETURN:
            case ATHROW:
                break;
            default:
                instructionIndicesToProcess.add(currentInsnIndex + 1);
                break;
        }
    }
}
Also used : LabelNode(org.apache.tapestry5.internal.plastic.asm.tree.LabelNode) TryCatchBlockNode(org.apache.tapestry5.internal.plastic.asm.tree.TryCatchBlockNode) TableSwitchInsnNode(org.apache.tapestry5.internal.plastic.asm.tree.TableSwitchInsnNode) ArrayList(java.util.ArrayList) AbstractInsnNode(org.apache.tapestry5.internal.plastic.asm.tree.AbstractInsnNode) JumpInsnNode(org.apache.tapestry5.internal.plastic.asm.tree.JumpInsnNode) LookupSwitchInsnNode(org.apache.tapestry5.internal.plastic.asm.tree.LookupSwitchInsnNode)

Example 4 with Flow

use of org.apache.tapestry5.func.Flow in project tapestry-5 by apache.

the class OnEventWorker method addPublishEventInfo.

private void addPublishEventInfo(Flow<EventHandlerMethod> eventHandlerMethods, MutableComponentModel model) {
    JSONArray publishEvents = new JSONArray();
    for (EventHandlerMethod eventHandlerMethod : eventHandlerMethods) {
        if (eventHandlerMethod.publishEvent != null) {
            publishEvents.add(eventHandlerMethod.eventType.toLowerCase());
        }
    }
    // event information to it.
    if (publishEvents.size() > 0) {
        model.addMixinClassName(PublishServerSideEvents.class.getName(), "after:*");
        model.setMeta(InternalConstants.PUBLISH_COMPONENT_EVENTS_META, publishEvents.toString());
    }
}
Also used : JSONArray(org.apache.tapestry5.json.JSONArray) PublishServerSideEvents(org.apache.tapestry5.corelib.mixins.PublishServerSideEvents)

Example 5 with Flow

use of org.apache.tapestry5.func.Flow in project tapestry-5 by apache.

the class OnEventWorker method implementDispatchMethod.

private void implementDispatchMethod(final PlasticClass plasticClass, final boolean isRoot, final MutableComponentModel model, final Flow<EventHandlerMethod> eventHandlerMethods) {
    plasticClass.introduceMethod(TransformConstants.DISPATCH_COMPONENT_EVENT_DESCRIPTION).changeImplementation(new InstructionBuilderCallback() {

        public void doBuild(InstructionBuilder builder) {
            builder.startVariable("boolean", new LocalVariableCallback() {

                public void doBuild(LocalVariable resultVariable, InstructionBuilder builder) {
                    if (!isRoot) {
                        // As a subclass, there will be a base class implementation (possibly empty).
                        builder.loadThis().loadArguments().invokeSpecial(plasticClass.getSuperClassName(), TransformConstants.DISPATCH_COMPONENT_EVENT_DESCRIPTION);
                        // First store the result of the super() call into the variable.
                        builder.storeVariable(resultVariable);
                        builder.loadArgument(0).invoke(Event.class, boolean.class, "isAborted");
                        builder.when(Condition.NON_ZERO, RETURN_TRUE);
                    } else {
                        // No event handler method has yet been invoked.
                        builder.loadConstant(false).storeVariable(resultVariable);
                    }
                    boolean hasRestEndpointEventHandlerMethod = false;
                    JSONArray restEndpointEventHandlerMethods = null;
                    for (EventHandlerMethod method : eventHandlerMethods) {
                        method.buildMatchAndInvocation(builder, resultVariable);
                        model.addEventHandler(method.eventType);
                        if (method.handleActivationEventContext) {
                            model.doHandleActivationEventContext();
                        }
                        // We're collecting this info for all components, even considering REST
                        // events are only triggered in pages, because we can have REST event
                        // handler methods in base classes too, and we need this info
                        // for generating complete, correct OpenAPI documentation.
                        final OnEvent onEvent = method.method.getAnnotation(OnEvent.class);
                        final String methodName = method.method.getDescription().methodName;
                        if (isRestEndpointEventHandlerMethod(onEvent, methodName)) {
                            hasRestEndpointEventHandlerMethod = true;
                            if (restEndpointEventHandlerMethods == null) {
                                restEndpointEventHandlerMethods = new JSONArray();
                            }
                            JSONObject methodMeta = new JSONObject();
                            methodMeta.put("name", methodName);
                            JSONArray parameters = new JSONArray();
                            for (MethodParameter parameter : method.method.getParameters()) {
                                parameters.add(parameter.getType());
                            }
                            methodMeta.put("parameters", parameters);
                            restEndpointEventHandlerMethods.add(methodMeta);
                        }
                    }
                    // memory by not setting it to all component models.
                    if (model.isPage()) {
                        model.setMeta(InternalConstants.REST_ENDPOINT_EVENT_HANDLER_METHOD_PRESENT, hasRestEndpointEventHandlerMethod ? InternalConstants.TRUE : InternalConstants.FALSE);
                    }
                    // methods in components, something that would be ignored anyway.
                    if (restEndpointEventHandlerMethods != null) {
                        model.setMeta(InternalConstants.REST_ENDPOINT_EVENT_HANDLER_METHODS, restEndpointEventHandlerMethods.toCompactString());
                    }
                    builder.loadVariable(resultVariable).returnResult();
                }
            });
        }
    });
}
Also used : LocalVariableCallback(org.apache.tapestry5.plastic.LocalVariableCallback) InstructionBuilder(org.apache.tapestry5.plastic.InstructionBuilder) JSONObject(org.apache.tapestry5.json.JSONObject) LocalVariable(org.apache.tapestry5.plastic.LocalVariable) JSONArray(org.apache.tapestry5.json.JSONArray) MethodParameter(org.apache.tapestry5.plastic.MethodParameter) InstructionBuilderCallback(org.apache.tapestry5.plastic.InstructionBuilderCallback) OnEvent(org.apache.tapestry5.annotations.OnEvent)

Aggregations

AbstractInsnNode (org.apache.tapestry5.internal.plastic.asm.tree.AbstractInsnNode)4 JumpInsnNode (org.apache.tapestry5.internal.plastic.asm.tree.JumpInsnNode)4 LabelNode (org.apache.tapestry5.internal.plastic.asm.tree.LabelNode)4 LookupSwitchInsnNode (org.apache.tapestry5.internal.plastic.asm.tree.LookupSwitchInsnNode)4 TableSwitchInsnNode (org.apache.tapestry5.internal.plastic.asm.tree.TableSwitchInsnNode)4 TryCatchBlockNode (org.apache.tapestry5.internal.plastic.asm.tree.TryCatchBlockNode)4 ArrayList (java.util.ArrayList)2 List (java.util.List)2 JSONArray (org.apache.tapestry5.json.JSONArray)2 File (java.io.File)1 BigDecimal (java.math.BigDecimal)1 BigInteger (java.math.BigInteger)1 BitSet (java.util.BitSet)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 OnEvent (org.apache.tapestry5.annotations.OnEvent)1 Coercion (org.apache.tapestry5.commons.services.Coercion)1 StringToEnumCoercion (org.apache.tapestry5.commons.util.StringToEnumCoercion)1 TimeInterval (org.apache.tapestry5.commons.util.TimeInterval)1 PublishServerSideEvents (org.apache.tapestry5.corelib.mixins.PublishServerSideEvents)1