001/* An analysis that finds the free variables in a ptolemy model
002
003 Copyright (c) 2003-2013 The Regents of the University of California.
004 All rights reserved.
005 Permission is hereby granted, without written agreement and without
006 license or royalty fees, to use, copy, modify, and distribute this
007 software and its documentation for any purpose, provided that the above
008 copyright notice and the following two paragraphs appear in all copies
009 of this software.
010
011 IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
012 FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
013 ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
014 THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
015 SUCH DAMAGE.
016
017 THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
018 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
019 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
020 PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
021 CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
022 ENHANCEMENTS, OR MODIFICATIONS.
023
024 PT_COPYRIGHT_VERSION_2
025 COPYRIGHTENDKEY
026 */
027package ptolemy.actor.util;
028
029import java.util.Collections;
030import java.util.HashMap;
031import java.util.HashSet;
032import java.util.Iterator;
033import java.util.Set;
034
035import ptolemy.data.expr.ASTPtRootNode;
036import ptolemy.data.expr.ParseTreeFreeVariableCollector;
037import ptolemy.data.expr.PtParser;
038import ptolemy.data.expr.Variable;
039import ptolemy.kernel.CompositeEntity;
040import ptolemy.kernel.Entity;
041import ptolemy.kernel.util.IllegalActionException;
042
043///////////////////////////////////////////////////////////////////
044//// FreeVariableModelAnalysis
045
046/**
047 An analysis that traverses a model to determine all the free variables
048 in a hierarchical model.  The free variables in a model are defined to
049 be the set of identifiers that are referenced by the model, but are
050 not defined in the model.  The free variables must be assigned values
051 for the model to be executable.
052
053 This class traverses the model, but it not read synchronized on the
054 model, therefore its caller should be.
055
056 @author Stephen Neuendorffer
057 @version $Id$
058 @since Ptolemy II 4.0
059 @Pt.ProposedRating Yellow (neuendor)
060 @Pt.AcceptedRating Yellow (neuendor)
061 */
062public class FreeVariableModelAnalysis {
063    /** Analyze the given model to return a set of names which must
064     *  be defined externally for the model to be completely specified.
065     *  In addition, store the intermediate results for contained actors
066     *  so they can be retrieved by the getFreeVariables() method.
067     *  @param model The model that will be analyzed.
068     *  @exception IllegalActionException If an exception occurs
069     *  during analysis.
070     */
071    public FreeVariableModelAnalysis(Entity model)
072            throws IllegalActionException {
073        _entityToFreeVariableNameSet = new HashMap();
074        _freeVariables(model);
075    }
076
077    /** Return the computed free variables for the given entity.
078     *  @param entity An entity, which must be deeply contained by the
079     *  model for which this analysis was created.
080     *  @return The computed free variables for the given entity.
081     *  @exception RuntimeException If the free variables for the
082     *  entity have not already been computed.
083     */
084    public Set getFreeVariables(Entity entity) {
085        Set freeVariables = (Set) _entityToFreeVariableNameSet.get(entity);
086
087        if (freeVariables == null) {
088            throw new RuntimeException("Entity " + entity.getFullName()
089                    + " has not been analyzed.");
090        }
091
092        return Collections.unmodifiableSet(freeVariables);
093    }
094
095    ///////////////////////////////////////////////////////////////////
096    ////                         private methods                   ////
097    // Recursively compute the set of free variables for all actors
098    // deeply contained in the given model.
099    private Set _freeVariables(Entity model) throws IllegalActionException {
100        // First get the free variables of contained actors.
101        Set set = new HashSet();
102
103        if (model instanceof CompositeEntity) {
104            for (Iterator entities = ((CompositeEntity) model).entityList()
105                    .iterator(); entities.hasNext();) {
106                Entity entity = (Entity) entities.next();
107                set.addAll(_freeVariables(entity));
108            }
109        }
110
111        // Next, compute the set of variable names defined in this container.
112        Set variableNames = new HashSet();
113
114        for (Object element : model.attributeList(Variable.class)) {
115            Variable variable = (Variable) element;
116            variableNames.add(variable.getName());
117        }
118
119        variableNames = Collections.unmodifiableSet(variableNames);
120
121        // Free variables of contained actors that are defined in this
122        // container are not free variables of this container.
123        set.removeAll(variableNames);
124
125        // Iterate over all the variables of this container, and add in
126        // any free variables they reference.
127        PtParser parser = new PtParser();
128        ParseTreeFreeVariableCollector collector = new ParseTreeFreeVariableCollector();
129
130        for (Object element : model.attributeList(Variable.class)) {
131            Variable variable = (Variable) element;
132            String expression = variable.getExpression();
133            ASTPtRootNode root = null;
134
135            if (variable.isStringMode()
136                    && !variable.isSuppressVariableSubstitution()) {
137                root = parser.generateStringParseTree(expression);
138            } else {
139                root = parser.generateParseTree(expression);
140            }
141            if (root != null) {
142                Set freeIdentifiers = new HashSet(
143                        collector.collectFreeVariables(root));
144
145                // Identifiers that reference other variables in the same container
146                // are bound, not free.
147                Set tempSet = new HashSet(variableNames);
148                tempSet.remove(variable.getName());
149                freeIdentifiers.removeAll(tempSet);
150
151                set.addAll(freeIdentifiers);
152            }
153        }
154
155        _entityToFreeVariableNameSet.put(model, set);
156        return set;
157    }
158
159    ///////////////////////////////////////////////////////////////////
160    ////                         private variables                 ////
161    private HashMap _entityToFreeVariableNameSet;
162}