Package ptolemy.copernicus.kernel

Examples of ptolemy.copernicus.kernel.EntitySootClass


            ConstVariableModelAnalysis constAnalysis, Map options) {
        Expression entity = (Expression) actor;
        SootClass entityClass = PtolemyUtilities.actorClass;

        // Create a class for the entity instance.
        EntitySootClass entityInstanceClass = new EntitySootClass(entityClass,
                newClassName, Modifier.PUBLIC);
        Scene.v().addClass(entityInstanceClass);
        entityInstanceClass.setApplicationClass();

        // Create methods that will compute and set the values of the
        // parameters of this actor.
        ModelTransformer.createAttributeComputationFunctions(entity, entity,
                entityInstanceClass, constAnalysis);

        // Record everything that the class creates.
        HashMap tempCreatedMap = new HashMap();

        SootMethod initMethod = entityInstanceClass.getInitMethod();

        {
            // Populate the initialization method.
            JimpleBody body = Jimple.v().newBody(initMethod);
            initMethod.setActiveBody(body);
            body.insertIdentityStmts();

            Chain units = body.getUnits();
            Local thisLocal = body.getThisLocal();

            // Populate...
            // Initialize attributes that already exist in the class.
            ModelTransformer.createAttributes(body, entity, thisLocal, entity,
                    thisLocal, entityInstanceClass, tempCreatedMap);

            // Create and initialize ports
            ModelTransformer.createPorts(body, thisLocal, entity, thisLocal,
                    entity, entityInstanceClass, tempCreatedMap);

            // return void
            units.add(Jimple.v().newReturnVoidStmt());
        }

        // Add fields to contain the tokens for each port.
        Map nameToField = new HashMap();
        Map nameToType = new HashMap();

        {
            Iterator inputPorts = entity.inputPortList().iterator();

            while (inputPorts.hasNext()) {
                TypedIOPort port = (TypedIOPort) (inputPorts.next());
                String name = port.getName(entity);
                Type type = PtolemyUtilities.tokenType;
                nameToType.put(name, port.getType());

                SootField field = new SootField(StringUtilities
                        .sanitizeName(name)
                        + "Token", type);
                entityInstanceClass.addField(field);
                nameToField.put(name, field);
            }
        }
        // Populate the fire method.
        {
            SootMethod fireMethod = new SootMethod("fire",
                    Collections.EMPTY_LIST, VoidType.v(), Modifier.PUBLIC);
            entityInstanceClass.addMethod(fireMethod);

            JimpleBody body = Jimple.v().newBody(fireMethod);
            fireMethod.setActiveBody(body);
            body.insertIdentityStmts();

            Chain units = body.getUnits();
            Local thisLocal = body.getThisLocal();

            Local hasTokenLocal = Jimple.v().newLocal("hasTokenLocal",
                    BooleanType.v());
            body.getLocals().add(hasTokenLocal);

            Local tokenLocal = Jimple.v().newLocal("tokenLocal",
                    PtolemyUtilities.tokenType);
            body.getLocals().add(tokenLocal);

            Iterator inputPorts = entity.inputPortList().iterator();

            while (inputPorts.hasNext()) {
                TypedIOPort port = (TypedIOPort) (inputPorts.next());

                // FIXME: Handle multiports
                if (port.getWidth() > 0) {
                    String name = port.getName(entity);

                    // Create an if statement.
                    //
                    Local portLocal = Jimple.v().newLocal("port",
                            PtolemyUtilities.componentPortType);
                    body.getLocals().add(portLocal);

                    SootField portField = entityInstanceClass
                            .getFieldByName(StringUtilities.sanitizeName(name));
                    units.add(Jimple.v().newAssignStmt(
                            portLocal,
                            Jimple.v().newInstanceFieldRef(thisLocal,
                                    portField.makeRef())));
                    units.add(Jimple.v().newAssignStmt(
                            hasTokenLocal,
                            Jimple.v().newVirtualInvokeExpr(portLocal,
                                    PtolemyUtilities.hasTokenMethod.makeRef(),
                                    IntConstant.v(0))));

                    Stmt target = Jimple.v().newNopStmt();
                    units.add(Jimple.v().newIfStmt(
                            Jimple.v().newEqExpr(hasTokenLocal,
                                    IntConstant.v(0)), target));
                    units.add(Jimple.v().newAssignStmt(
                            tokenLocal,
                            Jimple.v().newVirtualInvokeExpr(portLocal,
                                    PtolemyUtilities.getMethod.makeRef(),
                                    IntConstant.v(0))));

                    SootField tokenField = entityInstanceClass
                            .getFieldByName(name + "Token");
                    units.add(Jimple.v().newAssignStmt(
                            Jimple.v().newInstanceFieldRef(thisLocal,
                                    tokenField.makeRef()), tokenLocal));
                    units.add(target);
                }
            }

            StringAttribute expressionAttribute = (StringAttribute) entity
                    .getAttribute("expression");
            String expression = expressionAttribute.getExpression();

            Local local = DataUtilities.generateExpressionCode(entity,
                    entityInstanceClass, expression, nameToField, nameToType,
                    body);

            // send the computed token
            String name = "output";
            Local portLocal = Jimple.v().newLocal("port",
                    PtolemyUtilities.componentPortType);
            body.getLocals().add(portLocal);

            SootField portField = entityInstanceClass.getFieldByName(name);

            units.add(Jimple.v().newAssignStmt(
                    portLocal,
                    Jimple.v().newInstanceFieldRef(thisLocal,
                            portField.makeRef())));
            units.add(Jimple.v().newInvokeStmt(
                    Jimple.v().newVirtualInvokeExpr(portLocal,
                            PtolemyUtilities.sendMethod.makeRef(),
                            IntConstant.v(0), local)));

            // return void
            units.add(Jimple.v().newReturnVoidStmt());

            LocalNameStandardizer.v().transform(body, "at.lns");
            LocalSplitter.v().transform(body, "at.ls");
        }

        {
            SootMethod preinitializeMethod = new SootMethod("preinitialize",
                    Collections.EMPTY_LIST, VoidType.v(), Modifier.PUBLIC);
            entityInstanceClass.addMethod(preinitializeMethod);

            JimpleBody body = Jimple.v().newBody(preinitializeMethod);
            preinitializeMethod.setActiveBody(body);
            body.insertIdentityStmts();

            Stmt insertPoint = Jimple.v().newReturnVoidStmt();
            body.getUnits().add(insertPoint);
            ModelTransformer.initializeAttributesBefore(body, insertPoint,
                    entity, body.getThisLocal(), entity, body.getThisLocal(),
                    entityInstanceClass);
            LocalNameStandardizer.v().transform(body, "at.lns");
            LocalSplitter.v().transform(body, "at.ls");
        }

        // Remove super calls to the executable interface.
        // FIXME: This would be nice to do by inlining instead of
        // special casing.
        ModelTransformer.implementExecutableInterface(entityInstanceClass);

        // Reinitialize the hierarchy, since we've added classes.
        Scene.v().setActiveHierarchy(new Hierarchy());
        Scene.v().setFastHierarchy(new FastHierarchy());

        // Inline all methods in the class that are called from
        // within the class.
        ModelTransformer.inlineLocalCalls(entityInstanceClass);

        // Remove the __CGInit method.  This should have been
        // inlined above.
        entityInstanceClass.removeMethod(entityInstanceClass.getInitMethod());

        return entityInstanceClass;
    }
View Full Code Here


    private static EntitySootClass _createCompositeActor(CompositeActor entity,
            String newClassName, Map options) {
        SootClass entityClass = PtolemyUtilities.compositeActorClass;

        // create a class for the entity instance.
        EntitySootClass entityInstanceClass = new EntitySootClass(entityClass,
                newClassName, Modifier.PUBLIC);
        Scene.v().addClass(entityInstanceClass);
        entityInstanceClass.setApplicationClass();

        // Record everything that the class creates.
        HashMap tempCreatedMap = new HashMap();

        // Create methods that will compute and set the values of the
        // parameters of this actor.
        createAttributeComputationFunctions(entity, entity,
                entityInstanceClass, _constAnalysis);

        {
            // create a new body for the initialization method.
            SootMethod initMethod = entityInstanceClass.getInitMethod();
            JimpleBody body = Jimple.v().newBody(initMethod);
            initMethod.setActiveBody(body);
            body.insertIdentityStmts();

            Chain units = body.getUnits();
            Local thisLocal = body.getThisLocal();

            // Create a new class for each actor in the model.
            _createActorsIn(entity, tempCreatedMap, "modelTransformer",
                    _constAnalysis, options);

            // Create code in the model class to instantiate the ports
            // and parameters of the model.
            createAttributes(body, entity, thisLocal, entity, thisLocal,
                    entityInstanceClass, tempCreatedMap);

            _ports(body, thisLocal, entity, thisLocal, entity,
                    entityInstanceClass, tempCreatedMap, true);

            // Excess initialization, but necessary for -actor???
            Stmt insertPoint = Jimple.v().newNopStmt();
            body.getUnits().add(insertPoint);

            // InitializeAttributes of the ports and parameters.
            initializeAttributesBefore(body, insertPoint, entity, thisLocal,
                    entity, thisLocal, entityInstanceClass);

            // Create code in the model class to instantiate all
            // actors and relations, and connect the relations
            // to the ports.
            _entities(body, thisLocal, entity, thisLocal, entity,
                    entityInstanceClass, tempCreatedMap, options);
            _relations(body, thisLocal, entity, entityInstanceClass);
            _links(body, entity);
            _linksOnPortsContainedByContainedEntities(body, entity);

            // return void
            units.add(Jimple.v().newReturnVoidStmt());
        }

        implementExecutableInterface(entityInstanceClass);

        // Reinitialize the hierarchy, since we've added classes.
        Scene.v().setActiveHierarchy(new Hierarchy());
        Scene.v().setFastHierarchy(new FastHierarchy());

        {
            Set locallyModifiedAttributeSet = _constAnalysis
                    .getVariablesWithChangeContext(entity);

            // Filter out any attribute that is independent (and might
            // be modified).
            for (Iterator i = locallyModifiedAttributeSet.iterator(); i
                    .hasNext();) {
                if (_constAnalysis.isIndependent((Variable) i.next())) {
                    i.remove();
                }
            }

            // Sort according to dependencies.
            List locallyModifiedAttributeList;

            try {
                DirectedGraph graph = _constAnalysis.getDependencyGraph();
                locallyModifiedAttributeList = Arrays.asList(Graph
                        .weightArray(graph.topologicalSort(graph
                                .nodes(locallyModifiedAttributeSet))));
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }

            System.out.println("locallyModifiedAttributeList of " + entity
                    + " = " + locallyModifiedAttributeList);

            // Add code to the beginning of the prefire method that
            // computes the attribute values of anything that is not a
            // constant.
            SootMethod method = entityInstanceClass.getMethodByName("prefire");
            System.out.println("method = " + method);

            JimpleBody body = (JimpleBody) method.getActiveBody();
            Stmt insertPoint = body.getFirstNonIdentityStmt();
            Local containerLocal = Jimple.v().newLocal("entity",
                    PtolemyUtilities.componentEntityType);
            body.getLocals().add(containerLocal);

            // Invoke the method to compute each attribute, in order.
            for (Iterator attributes = locallyModifiedAttributeList.iterator(); attributes
                    .hasNext();) {
                Attribute attribute = (Attribute) attributes.next();
                Entity attributeContainer = FieldsForEntitiesTransformer
                        .getEntityContainerOfObject(attribute);
                SootClass containerClass = (SootClass) _objectToClassMap
                        .get(attributeContainer);
                SootMethod computeMethod = containerClass
                        .getMethodByName(getAttributeComputationFunctionName(
                                attribute, attributeContainer));
                body.getUnits().insertBefore(
                        Jimple.v().newAssignStmt(
                                containerLocal,
                                Jimple.v().newVirtualInvokeExpr(
                                        body.getThisLocal(),
                                        PtolemyUtilities.getEntityMethod
                                                .makeRef(),
                                        StringConstant.v(attributeContainer
                                                .getName(entity)))),
                        insertPoint);

                // and then cast
                body.getUnits().insertBefore(
                        Jimple.v().newAssignStmt(
                                containerLocal,
                                Jimple.v().newCastExpr(containerLocal,
                                        RefType.v(containerClass))),
                        insertPoint);

                body.getUnits().insertBefore(
                        Jimple.v().newInvokeStmt(
                                Jimple.v().newVirtualInvokeExpr(containerLocal,
                                        computeMethod.makeRef())), insertPoint);
            }

            //    ModelTransformer.computeAttributesBefore(body, insertPoint,
            //                     entity, body.getThisLocal(),
            //                     entity, body.getThisLocal(),
            //                     entityInstanceClass,
            //                     locallyModifiedAttributeList);
            LocalNameStandardizer.v().transform(body, "at.lns");
            LocalSplitter.v().transform(body, "at.ls");
        }

        // Inline all methods in the class that are called from
        // within the class.
        inlineLocalCalls(entityInstanceClass);

        // Remove the __CGInit method.  This should have been
        // inlined above.
        entityInstanceClass.removeMethod(entityInstanceClass.getInitMethod());

        System.out.println("createdMap = " + tempCreatedMap);
        return entityInstanceClass;
    }
View Full Code Here

        SootClass entityClass = Scene.v().loadClassAndSupport(className);
        entityClass.setLibraryClass();

        // Create a class for the entity instance.
        EntitySootClass entityInstanceClass = new EntitySootClass(entityClass,
                newClassName, Modifier.PUBLIC);
        Scene.v().addClass(entityInstanceClass);
        entityInstanceClass.setApplicationClass();

        // Record everything that the class creates.
        HashMap tempCreatedMap = new HashMap();

        // Populate the method to initialize this instance.
        // We need to put something here before folding so that
        // the folder can deal with it.
        SootMethod initMethod = entityInstanceClass.getInitMethod();

        {
            JimpleBody body = Jimple.v().newBody(initMethod);
            initMethod.setActiveBody(body);

            // return void
            body.getUnits().add(Jimple.v().newReturnVoidStmt());
        }

        SootClass theClass = entityInstanceClass;
        SootClass superClass = theClass.getSuperclass();

        while ((superClass != PtolemyUtilities.objectClass)
                && (superClass != PtolemyUtilities.actorClass)
                && (superClass != PtolemyUtilities.compositeActorClass)) {
            superClass.setLibraryClass();
            try {
                SootUtilities.foldClass(theClass);
            } catch (RuntimeException exception) {
                throw new RuntimeException("Failed to fold \"" + theClass
                        + "\"", exception);
            }
            superClass = theClass.getSuperclass();
        }

        // Go through all the initialization code and remove any old
        // parameter initialization code.  This has to happen after
        // class folding so that all of the parameter initialization
        // is available, but before we add the correct initialization.
        // FIXME: This needs to look at all code that is reachable
        // from a constructor.
        _removeAttributeInitialization(theClass);

        Entity classEntity = null;

        try {
            classEntity = (Entity) ModelTransformer._findDeferredInstance(
                    entity).clone(null);

            // The cloning process results an object that defers change
            // requests.  By default, we do not want to defer change
            // requests, but more importantly, we need to execute
            // any change requests that may have been queued
            // during cloning. The following call does that.
            classEntity.setDeferringChangeRequests(false);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        ModelTransformer.updateCreatedSet(entity.getFullName(), classEntity,
                classEntity, tempCreatedMap);

        // Create methods that will compute and set the values of the
        // parameters of this actor.
        ModelTransformer.createAttributeComputationFunctions(entity, entity,
                entityInstanceClass, constAnalysis);

        {
            // replace the previous dummy body
            // for the initialization method with a new one.
            JimpleBody body = Jimple.v().newBody(initMethod);
            initMethod.setActiveBody(body);
            body.insertIdentityStmts();

            Chain units = body.getUnits();
            Local thisLocal = body.getThisLocal();

            // create attributes for those in the class
            ModelTransformer.createAttributes(body, entity, thisLocal, entity,
                    thisLocal, entityInstanceClass, tempCreatedMap);

            // Create and initialize ports
            ModelTransformer.createPorts(body, thisLocal, entity, thisLocal,
                    entity, entityInstanceClass, tempCreatedMap);

            // Extra initialization necessary?
            Stmt insertPoint = Jimple.v().newNopStmt();
            body.getUnits().add(insertPoint);

            ModelTransformer.initializeAttributesBefore(body, insertPoint,
                    entity, thisLocal, entity, thisLocal, entityInstanceClass);

            // return void
            units.add(Jimple.v().newReturnVoidStmt());
        }

        // Remove super calls to the executable interface.
        // FIXME: This would be nice to do by inlining instead of
        // special casing.
        ModelTransformer.implementExecutableInterface(entityInstanceClass);

        {
            // Add code to the beginning of the preinitialize method that
            // initializes the attributes.
            SootMethod method = theClass.getMethodByName("preinitialize");
            JimpleBody body = (JimpleBody) method.getActiveBody();

            /* Stmt insertPoint = */body.getFirstNonIdentityStmt();

            // Do we initialize parameters in preinitialize or in the
            // constructor?
            // ModelTransformer.initializeAttributesBefore(body,
            // insertPoint,
            //                     entity, body.getThisLocal(),
            //                     entity, body.getThisLocal(),
            //                     entityInstanceClass);
            LocalNameStandardizer.v().transform(body, "at.lns");
            LocalSplitter.v().transform(body, "at.ls");
        }

        // FIXME: This should do what
        // ModelTransformed._createCompositeActor does.
        //    {
        //             LinkedList notConstantAttributeList = new LinkedList(
        //                     entity.attributeList(Variable.class));
        //             notConstantAttributeList.removeAll(
        //                     constAnalysis.getConstVariables(entity));
        //             // Sort according to dependencies.
        //             System.out.println("notConstantAttributeList of " + entity
        //                     + " = " + notConstantAttributeList);
        //             // Add code to the beginning of the prefire method that
        //             // computes the attribute values of anything that is not a
        //             // constant.
        //             SootMethod method = theClass.getMethodByName("prefire");
        //             JimpleBody body = (JimpleBody)method.getActiveBody();
        //             Stmt insertPoint = body.getFirstNonIdentityStmt();
        //             ModelTransformer.computeAttributesBefore(body, insertPoint,
        //                     entity, body.getThisLocal(),
        //                     entity, body.getThisLocal(),
        //                     entityInstanceClass,
        //                     notConstantAttributeList);
        //             LocalNameStandardizer.v().transform(body, "at.lns");
        //             LocalSplitter.v().transform(body, "at.ls");
        //         }
        // Reinitialize the hierarchy, since we've added classes.
        try {
            Scene.v().setActiveHierarchy(new Hierarchy());
        } catch (Error ex) {
            ex.printStackTrace(System.out);
        }

        try {
            Scene.v().setFastHierarchy(new FastHierarchy());
        } catch (Error ex) {
            ex.printStackTrace(System.out);
        }

        // Inline all methods in the class that are called from
        // within the class.
        ModelTransformer.inlineLocalCalls(entityInstanceClass);

        // Remove the __CGInit method.  This should have been
        // inlined above.
        entityInstanceClass.removeMethod(entityInstanceClass.getInitMethod());

        return entityInstanceClass;
    }
View Full Code Here

        FSMActor entity = (FSMActor) actor;

        SootClass entityClass = PtolemyUtilities.actorClass;

        // create a class for the entity instance.
        EntitySootClass entityInstanceClass = new EntitySootClass(entityClass,
                newClassName, Modifier.PUBLIC);
        Scene.v().addClass(entityInstanceClass);
        entityInstanceClass.setApplicationClass();

        // Create methods that will compute and set the values of the
        // parameters of this actor.
        ModelTransformer.createAttributeComputationFunctions(entity, entity,
                entityInstanceClass, constAnalysis);

        // Record everything that the class creates.
        HashMap tempCreatedMap = new HashMap();

        SootMethod initMethod = entityInstanceClass.getInitMethod();

        {
            System.out.println("creating <init>");

            // Populate the initialization method.
            JimpleBody body = Jimple.v().newBody(initMethod);
            initMethod.setActiveBody(body);
            body.insertIdentityStmts();

            Chain units = body.getUnits();
            Local thisLocal = body.getThisLocal();

            // Populate...
            // Initialize attributes that already exist in the class.
            //  System.out.println("initializing attributes");
            ModelTransformer.createAttributes(body, entity, thisLocal, entity,
                    thisLocal, entityInstanceClass, tempCreatedMap);

            // Create and initialize ports
            // System.out.println("initializing ports");
            ModelTransformer.createPorts(body, thisLocal, entity, thisLocal,
                    entity, entityInstanceClass, tempCreatedMap);

            // return void
            units.add(Jimple.v().newReturnVoidStmt());
        }

        // Add fields to contain the tokens for each port.
        Map nameToField = new HashMap();
        Map nameToType = new HashMap();

        {
            Iterator inputPorts = entity.inputPortList().iterator();

            while (inputPorts.hasNext()) {
                TypedIOPort port = (TypedIOPort) (inputPorts.next());
                String name = port.getName(entity);
                Type type = PtolemyUtilities.tokenType;
                nameToType.put(name, port.getType());

                // PtolemyUtilities.getSootTypeForTokenType(
                //  port.getType());
                SootField field = new SootField(StringUtilities
                        .sanitizeName(name)
                        + "Token", type);
                entityInstanceClass.addField(field);
                nameToField.put(name, field);

                field = new SootField(StringUtilities.sanitizeName(name)
                        + "IsPresent", type);
                entityInstanceClass.addField(field);
                nameToField.put(name + "_isPresent", field);
            }
        }

        {
            SootMethod preinitializeMethod = new SootMethod("preinitialize",
                    Collections.EMPTY_LIST, VoidType.v(), Modifier.PUBLIC);
            entityInstanceClass.addMethod(preinitializeMethod);

            JimpleBody body = Jimple.v().newBody(preinitializeMethod);
            preinitializeMethod.setActiveBody(body);
            body.insertIdentityStmts();

            Stmt insertPoint = Jimple.v().newReturnVoidStmt();
            body.getUnits().add(insertPoint);
            ModelTransformer.initializeAttributesBefore(body, insertPoint,
                    entity, body.getThisLocal(), entity, body.getThisLocal(),
                    entityInstanceClass);
        }

        // Add a field to keep track of the current state.
        SootField currentStateField = new SootField("_currentState", IntType
                .v());
        entityInstanceClass.addField(currentStateField);

        SootField nextTransitionField = new SootField("_nextTransition",
                IntType.v());
        entityInstanceClass.addField(nextTransitionField);
        // populate the initialize method.
        {
            System.out.println("create initialize()");

            SootMethod initializeMethod = new SootMethod("initialize",
                    Collections.EMPTY_LIST, VoidType.v(), Modifier.PUBLIC);
            entityInstanceClass.addMethod(initializeMethod);

            JimpleBody body = Jimple.v().newBody(initializeMethod);
            initializeMethod.setActiveBody(body);
            body.insertIdentityStmts();

            Chain units = body.getUnits();
            Local thisLocal = body.getThisLocal();

            // Set the initial state.
            String initialStateName = ((StringAttribute) entity
                    .getAttribute("initialStateName")).getExpression();
            int initialStateIndex = entity.entityList().indexOf(
                    entity.getEntity(initialStateName));
            units.add(Jimple.v().newAssignStmt(
                    Jimple.v().newInstanceFieldRef(thisLocal,
                            currentStateField.makeRef()),
                    IntConstant.v(initialStateIndex)));

            // return void
            units.add(Jimple.v().newReturnVoidStmt());

            LocalNameStandardizer.v().transform(body, "at.lns");
            LocalSplitter.v().transform(body, "at.ls");
        }
        // populate the fire method.
        {
            System.out.println("create fire()");

            SootMethod fireMethod = new SootMethod("fire",
                    Collections.EMPTY_LIST, VoidType.v(), Modifier.PUBLIC);
            entityInstanceClass.addMethod(fireMethod);

            JimpleBody body = Jimple.v().newBody(fireMethod);
            fireMethod.setActiveBody(body);
            body.insertIdentityStmts();

            Chain units = body.getUnits();
            Local thisLocal = body.getThisLocal();

            Local hasTokenLocal = Jimple.v().newLocal("hasTokenLocal",
                    BooleanType.v());
            body.getLocals().add(hasTokenLocal);

            Local tokenLocal = Jimple.v().newLocal("tokenLocal",
                    PtolemyUtilities.tokenType);
            body.getLocals().add(tokenLocal);

            Iterator inputPorts = entity.inputPortList().iterator();

            while (inputPorts.hasNext()) {
                TypedIOPort port = (TypedIOPort) (inputPorts.next());

                // FIXME: Handle multiports
                if (port.getWidth() > 0) {
                    String name = port.getName(entity);

                    // Create an if statement.
                    //
                    Local portLocal = Jimple.v().newLocal("port",
                            PtolemyUtilities.componentPortType);
                    body.getLocals().add(portLocal);

                    SootField portField = entityInstanceClass
                            .getFieldByName(StringUtilities.sanitizeName(name));
                    units.add(Jimple.v().newAssignStmt(
                            portLocal,
                            Jimple.v().newInstanceFieldRef(thisLocal,
                                    portField.makeRef())));
                    units.add(Jimple.v().newAssignStmt(
                            hasTokenLocal,
                            Jimple.v().newVirtualInvokeExpr(portLocal,
                                    PtolemyUtilities.hasTokenMethod.makeRef(),
                                    IntConstant.v(0))));

                    Local hasTokenToken = PtolemyUtilities.addTokenLocal(body,
                            "token", PtolemyUtilities.booleanTokenClass,
                            PtolemyUtilities.booleanTokenConstructor,
                            hasTokenLocal);

                    // store the isPresent
                    SootField tokenIsPresentField = (SootField) nameToField
                            .get(name + "_isPresent");
                    units.add(Jimple.v().newAssignStmt(
                            Jimple.v().newInstanceFieldRef(thisLocal,
                                    tokenIsPresentField.makeRef()),
                            hasTokenToken));

                    Stmt target = Jimple.v().newNopStmt();
                    units.add(Jimple.v().newIfStmt(
                            Jimple.v().newEqExpr(hasTokenLocal,
                                    IntConstant.v(0)), target));
                    units.add(Jimple.v().newAssignStmt(
                            tokenLocal,
                            Jimple.v().newVirtualInvokeExpr(portLocal,
                                    PtolemyUtilities.getMethod.makeRef(),
                                    IntConstant.v(0))));

                    SootField tokenField = (SootField) nameToField.get(name);
                    units.add(Jimple.v().newAssignStmt(
                            Jimple.v().newInstanceFieldRef(thisLocal,
                                    tokenField.makeRef()), tokenLocal));
                    units.add(target);
                }
            }

            Map stateToStartStmt = new HashMap();
            List stateStmtList = new LinkedList();
            int numberOfStates = entity.entityList().size();

            // Figure out what state we are in.
            for (Iterator states = entity.entityList().iterator(); states
                    .hasNext();) {
                State state = (State) states.next();
                Stmt startStmt = Jimple.v().newNopStmt();

                stateToStartStmt.put(state, startStmt);
                stateStmtList.add(startStmt);
            }

            Local currentStateLocal = Jimple.v().newLocal("currentStateLocal",
                    IntType.v());
            body.getLocals().add(currentStateLocal);

            Local nextStateLocal = Jimple.v().newLocal("nextStateLocal",
                    IntType.v());
            body.getLocals().add(nextStateLocal);

            Local flagLocal = Jimple.v().newLocal("flagLocal", BooleanType.v());
            body.getLocals().add(flagLocal);

            Local transitionTakenLocal = Jimple.v().newLocal(
                    "transitionTakenLocal", BooleanType.v());
            body.getLocals().add(transitionTakenLocal);

            Local nextTransitionLocal = Jimple.v().newLocal(
                    "nextTransitionLocal", IntType.v());
            body.getLocals().add(nextTransitionLocal);

            units.add(Jimple.v().newAssignStmt(
                    currentStateLocal,
                    Jimple.v().newInstanceFieldRef(thisLocal,
                            currentStateField.makeRef())));

            // Start by doing nothing.
            units.add(Jimple.v().newAssignStmt(transitionTakenLocal,
                    IntConstant.v(0)));
            units.add(Jimple.v().newAssignStmt(nextTransitionLocal,
                    IntConstant.v(-1)));

            // If no transition is taken, then stay in this state.
            units.add(Jimple.v().newAssignStmt(nextStateLocal,
                    currentStateLocal));

            Stmt finishedStmt = Jimple.v().newNopStmt();
            Stmt errorStmt = Jimple.v().newNopStmt();

            // Get the current state.
            units.add(Jimple.v().newTableSwitchStmt(currentStateLocal, 0,
                    numberOfStates - 1, stateStmtList, errorStmt));

            // Generate code for each state.
            for (Iterator states = entity.entityList().iterator(); states
                    .hasNext();) {
                State state = (State) states.next();
                System.out.println("state " + state.getName());

                Stmt startStmt = (Stmt) stateToStartStmt.get(state);
                units.add(startStmt);

                // Fire the refinement actor.
                TypedActor[] refinements = null;

                try {
                    refinements = state.getRefinement();
                } catch (Exception ex) {
                    throw new RuntimeException(ex.getMessage());
                }

                if (refinements != null) {
                    for (int i = 0; i < refinements.length; i++) {
                        TypedActor refinement = refinements[i];

                        Local containerLocal = Jimple.v().newLocal("container",
                                RefType.v(PtolemyUtilities.namedObjClass));
                        body.getLocals().add(containerLocal);

                        Local entityLocal = Jimple.v().newLocal("entity",
                                RefType.v(PtolemyUtilities.entityClass));
                        body.getLocals().add(entityLocal);

                        NamedObj containerModel = entity.getContainer();
                        String deepName = ((NamedObj) refinement)
                                .getName(containerModel);

                        units.add(Jimple.v().newAssignStmt(
                                containerLocal,
                                Jimple.v().newInterfaceInvokeExpr(
                                        thisLocal,
                                        PtolemyUtilities.getContainerMethod
                                                .makeRef())));
                        units
                                .add(Jimple
                                        .v()
                                        .newAssignStmt(
                                                containerLocal,
                                                Jimple
                                                        .v()
                                                        .newCastExpr(
                                                                containerLocal,
                                                                RefType
                                                                        .v(PtolemyUtilities.compositeActorClass))));
                        units.add(Jimple.v().newAssignStmt(
                                entityLocal,
                                Jimple.v().newVirtualInvokeExpr(
                                        containerLocal,
                                        PtolemyUtilities.getEntityMethod
                                                .makeRef(),
                                        StringConstant.v(deepName))));

                        units
                                .add(Jimple
                                        .v()
                                        .newAssignStmt(
                                                entityLocal,
                                                Jimple
                                                        .v()
                                                        .newCastExpr(
                                                                entityLocal,
                                                                RefType
                                                                        .v(PtolemyUtilities.compositeActorClass))));

                        SootMethod rprefireMethod;
                        SootMethod rfireMethod;
                        SootMethod rpostfireMethod;

                        if (refinement instanceof CompositeActor) {
                            rprefireMethod = SootUtilities
                                    .searchForMethodByName(
                                            PtolemyUtilities.compositeActorClass,
                                            "prefire");
                            rfireMethod = SootUtilities.searchForMethodByName(
                                    PtolemyUtilities.compositeActorClass,
                                    "fire");
                            rpostfireMethod = SootUtilities
                                    .searchForMethodByName(
                                            PtolemyUtilities.compositeActorClass,
                                            "postfire");
                        } else {
                            throw new RuntimeException();
                        }

                        units.add(Jimple.v().newInvokeStmt(
                                Jimple.v().newVirtualInvokeExpr(entityLocal,
                                        rprefireMethod.makeRef())));
                        units.add(Jimple.v().newInvokeStmt(
                                Jimple.v().newVirtualInvokeExpr(entityLocal,
                                        rfireMethod.makeRef())));
                        units.add(Jimple.v().newInvokeStmt(
                                Jimple.v().newVirtualInvokeExpr(entityLocal,
                                        rpostfireMethod.makeRef())));
                    }
                }

                // Determine the next state in this state.
                for (Iterator transitions = state.outgoingPort
                        .linkedRelationList().iterator(); transitions.hasNext();) {
                    Transition transition = (Transition) transitions.next();
                    System.out.println("transition = " + transition);

                    String guardExpression = transition.getGuardExpression();

                    Local guardLocal = DataUtilities.generateExpressionCode(
                            entity, entityInstanceClass, guardExpression,
                            nameToField, nameToType, body);

                    // Test the guard.
                    units
                            .add(Jimple
                                    .v()
                                    .newAssignStmt(
                                            tokenLocal,
                                            Jimple
                                                    .v()
                                                    .newCastExpr(
                                                            guardLocal,
                                                            RefType
                                                                    .v(PtolemyUtilities.booleanTokenClass))));
                    units.add(Jimple.v().newAssignStmt(
                            flagLocal,
                            Jimple.v().newVirtualInvokeExpr(
                                    tokenLocal,
                                    PtolemyUtilities.booleanValueMethod
                                            .makeRef())));

                    Stmt skipStmt = Jimple.v().newNopStmt();

                    units.add(Jimple.v().newIfStmt(
                            Jimple.v().newEqExpr(flagLocal, IntConstant.v(0)),
                            skipStmt));
                    units.add(Jimple.v().newIfStmt(
                            Jimple.v().newEqExpr(transitionTakenLocal,
                                    IntConstant.v(1)), errorStmt));

                    // If transition taken, then store the next state
                    units.add(Jimple.v().newAssignStmt(transitionTakenLocal,
                            IntConstant.v(1)));
                    units.add(Jimple.v().newAssignStmt(
                            nextTransitionLocal,
                            IntConstant.v(entity.relationList().indexOf(
                                    transition))));

                    int nextStateIndex = entity.entityList().indexOf(
                            transition.destinationState());
                    units.add(Jimple.v().newAssignStmt(nextStateLocal,
                            IntConstant.v(nextStateIndex)));

                    // Generate code for the outputExpression of the guard.
                    for (Iterator actions = transition.choiceActionList()
                            .iterator(); actions.hasNext();) {
                        AbstractActionsAttribute action = (AbstractActionsAttribute) actions
                                .next();
                        System.out.println("action = " + action);
                        _generateActionCode(entity, entityInstanceClass,
                                nameToField, nameToType, body, action);
                    }

                    units.add(skipStmt);
                }

                units.add(Jimple.v().newGotoStmt(finishedStmt));
            }

            units.add(errorStmt);

            // throw an exception.
            units.add(finishedStmt);

            Local exceptionLocal = SootUtilities.createRuntimeException(body,
                    errorStmt, "state error");
            units.insertBefore(Jimple.v().newThrowStmt(exceptionLocal),
                    errorStmt);

            // Store the next state.
            units.add(Jimple.v().newAssignStmt(
                    Jimple.v().newInstanceFieldRef(thisLocal,
                            currentStateField.makeRef()), nextStateLocal));

            // And the next Transition.
            units.add(Jimple.v()
                    .newAssignStmt(
                            Jimple.v().newInstanceFieldRef(thisLocal,
                                    nextTransitionField.makeRef()),
                            nextTransitionLocal));

            // return void
            units.add(Jimple.v().newReturnVoidStmt());

            LocalNameStandardizer.v().transform(body, "at.lns");
            LocalSplitter.v().transform(body, "at.ls");
        }
        // populate the postfire method.
        {
            System.out.println("create postfire()");

            SootMethod postfireMethod = new SootMethod("postfire",
                    Collections.EMPTY_LIST, BooleanType.v(), Modifier.PUBLIC);
            entityInstanceClass.addMethod(postfireMethod);

            JimpleBody body = Jimple.v().newBody(postfireMethod);
            postfireMethod.setActiveBody(body);
            body.insertIdentityStmts();

            Chain units = body.getUnits();
            Local thisLocal = body.getThisLocal();

            Map transitionToStartStmt = new HashMap();
            List transitionStmtList = new LinkedList();
            int numberOfTransitions = entity.relationList().size();

            // Figure out what transition we are in.
            for (Iterator transitions = entity.relationList().iterator(); transitions
                    .hasNext();) {
                Transition transition = (Transition) transitions.next();
                Stmt startStmt = Jimple.v().newNopStmt();

                transitionToStartStmt.put(transition, startStmt);
                transitionStmtList.add(startStmt);
            }

            Local nextTransitionLocal = Jimple.v().newLocal(
                    "nextTransitionLocal", IntType.v());
            body.getLocals().add(nextTransitionLocal);

            units.add(Jimple.v().newAssignStmt(
                    nextTransitionLocal,
                    Jimple.v().newInstanceFieldRef(thisLocal,
                            nextTransitionField.makeRef())));

            Stmt finishedStmt = Jimple.v().newNopStmt();
            Stmt errorStmt = Jimple.v().newNopStmt();

            // Get the current transition..
            units.add(Jimple.v().newTableSwitchStmt(nextTransitionLocal, 0,
                    numberOfTransitions - 1, transitionStmtList, errorStmt));

            // Generate code for each transition
            for (Iterator transitions = entity.relationList().iterator(); transitions
                    .hasNext();) {
                Transition transition = (Transition) transitions.next();
                Stmt startStmt = (Stmt) transitionToStartStmt.get(transition);
                units.add(startStmt);

                // Generate code for the commitExpression of the guard.
                for (Iterator actions = transition.commitActionList()
                        .iterator(); actions.hasNext();) {
                    AbstractActionsAttribute action = (AbstractActionsAttribute) actions
                            .next();
                    _generateActionCode(entity, entityInstanceClass,
                            nameToField, nameToType, body, action);
                }

                // Generate code to reinitialize the target state, if
                // reset is true.
                TypedActor[] refinements = null;

                try {
                    BooleanToken resetToken = (BooleanToken) transition.reset
                            .getToken();

                    if (resetToken.booleanValue()) {
                        refinements = (transition.destinationState())
                                .getRefinement();
                    }
                } catch (Exception ex) {
                    throw new RuntimeException(ex.getMessage());
                }

                if (refinements != null) {
                    for (int i = 0; i < refinements.length; i++) {
                        TypedActor refinement = refinements[i];

                        Local containerLocal = Jimple.v().newLocal("container",
                                RefType.v(PtolemyUtilities.namedObjClass));
                        body.getLocals().add(containerLocal);

                        Local entityLocal = Jimple.v().newLocal("entity",
                                RefType.v(PtolemyUtilities.entityClass));
                        body.getLocals().add(entityLocal);

                        NamedObj containerModel = entity.getContainer();
                        String deepName = ((NamedObj) refinement)
                                .getName(containerModel);

                        units.add(Jimple.v().newAssignStmt(
                                containerLocal,
                                Jimple.v().newInterfaceInvokeExpr(
                                        thisLocal,
                                        PtolemyUtilities.getContainerMethod
                                                .makeRef())));
                        units
                                .add(Jimple
                                        .v()
                                        .newAssignStmt(
                                                containerLocal,
                                                Jimple
                                                        .v()
                                                        .newCastExpr(
                                                                containerLocal,
                                                                RefType
                                                                        .v(PtolemyUtilities.compositeActorClass))));
                        units.add(Jimple.v().newAssignStmt(
                                entityLocal,
                                Jimple.v().newVirtualInvokeExpr(
                                        containerLocal,
                                        PtolemyUtilities.getEntityMethod
                                                .makeRef(),
                                        StringConstant.v(deepName))));

                        units
                                .add(Jimple
                                        .v()
                                        .newAssignStmt(
                                                entityLocal,
                                                Jimple
                                                        .v()
                                                        .newCastExpr(
                                                                entityLocal,
                                                                RefType
                                                                        .v(PtolemyUtilities.compositeActorClass))));

                        SootMethod rinitializeMethod = SootUtilities
                                .searchForMethodByName(
                                        PtolemyUtilities.compositeActorClass,
                                        "initialize");
                        units.add(Jimple.v().newInvokeStmt(
                                Jimple.v().newVirtualInvokeExpr(entityLocal,
                                        rinitializeMethod.makeRef())));
                    }
                }

                units.add(Jimple.v().newGotoStmt(finishedStmt));
            }

            units.add(errorStmt);
            units.add(finishedStmt);

            // return true
            units.add(Jimple.v().newReturnStmt(IntConstant.v(1)));

            LocalNameStandardizer.v().transform(body, "at.lns");
            LocalSplitter.v().transform(body, "at.ls");
        }

        // Remove super calls to the executable interface.
        // FIXME: This would be nice to do by inlining instead of
        // special casing.
        ModelTransformer.implementExecutableInterface(entityInstanceClass);

        // Reinitialize the hierarchy, since we've added classes.
        Scene.v().setActiveHierarchy(new Hierarchy());
        Scene.v().setFastHierarchy(new FastHierarchy());

        // Inline all methods in the class that are called from
        // within the class.
        ModelTransformer.inlineLocalCalls(entityInstanceClass);

        // Remove the __CGInit method.  This should have been
        // inlined above.
        entityInstanceClass.removeMethod(entityInstanceClass.getInitMethod());

        return entityInstanceClass;
    }
View Full Code Here

        // create a class for the model
        String modelClassName = PhaseOptions
                .getString(options, "targetPackage")
                + ".CG" + StringUtilities.sanitizeName(_model.getName());

        EntitySootClass modelClass = new EntitySootClass(
                PtolemyUtilities.compositeActorClass, modelClassName,
                Modifier.PUBLIC);
        Scene.v().addClass(modelClass);
        modelClass.setApplicationClass();

        // not really sure what this does..
        Scene.v().setMainClass(modelClass);

        // Initialize the model.
        SootMethod initMethod = modelClass.getInitMethod();
        JimpleBody body = Jimple.v().newBody(initMethod);
        initMethod.setActiveBody(body);
        body.insertIdentityStmts();

        Chain units = body.getUnits();
View Full Code Here

TOP

Related Classes of ptolemy.copernicus.kernel.EntitySootClass

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.