public LGSPGraphProcessingEnvironment(LGSPGraph graph, LGSPActions actions)
     : base(graph, actions)
 {
     transactionManager = new LGSPTransactionManager(this);
     sequencesManager = new LGSPDeferredSequencesManager();
     SetClearVariables(true);
 }
        void DoIt()
        {
            graph = new LGSPGraph(new ProgramGraphsOriginalGraphModel());
            actions = new ProgramGraphsOriginalActions(graph);
            procEnv = new LGSPGraphProcessingEnvironment(graph, actions);

            // use new exact 2.5 interface
            IClass cls = null; 
            IMethodBody mb = null;
            bool success = actions.createProgramGraphPullUp.Apply(procEnv, ref cls, ref mb);
            IMatchesExact<Rule_pullUpMethod.IMatch_pullUpMethod> matchesExact =
                actions.pullUpMethod.Match(procEnv, 0, cls, mb);
            Console.WriteLine(matchesExact.Count + " matches found.");
            Console.WriteLine(matchesExact.FirstExact.node_m5.ToString());

            graph.Clear();
            
            // and again with old inexact interface
            IMatches matchesInexact;
            object[] returns;

            Action_createProgramGraphPullUp createProgramGraph = Action_createProgramGraphPullUp.Instance;
            matchesInexact = createProgramGraph.Match(procEnv, 0);
            returns = createProgramGraph.Modify(procEnv, matchesInexact.First);
            IGraphElement[] param = new LGSPNode[2];
            param[0] = (Class)returns[0];
            param[1] = (MethodBody)returns[1];
            matchesInexact = actions.GetAction("pullUpMethod").Match(procEnv, 0, param);
            Console.WriteLine(matchesInexact.Count + " matches found.");
            Console.WriteLine(matchesInexact.First.getNodeAt((int)Rule_pullUpMethod.pullUpMethod_NodeNums.m5).ToString());
        }
        public LGSPUniquenessEnsurer(LGSPGraph graph)
        {
            if(!graph.Model.GraphElementUniquenessIsEnsured)
                throw new Exception("Internal error, uniqueness ensurer constructed although uniqueness was not requested");

            if(graph.NumNodes > 0 || graph.NumEdges > 0)
                throw new Exception("Graph must be empty!");

            this.graph = graph;
            graph.uniquenessEnsurer = this;
            
            // global counter for fetching a new unique id
            nextNewId = 0;

            // we use an array organized as heap for storing the "free list" of already allocated but currently not used ids 
            heap.Add(-1); // we start at index 1, yields simpler arithmetic

            // subscribe to events we've to listen to ensure unique ids for the graph elements with a minimum amount of gaps
            graph.OnNodeAdded += NodeAdded;
            graph.OnEdgeAdded += EdgeAdded;
            graph.OnRemovingNode += RemovingNode;
            graph.OnRemovingEdge += RemovingEdge;
            graph.OnRetypingNode += RetypingNode;
            graph.OnRetypingEdge += RetypingEdge;
        }
        void DoIdpt()
        {
            graph = new LGSPGraph(new IndependentGraphModel());
            actions = new IndependentActions(graph);
            procEnv = new LGSPGraphProcessingEnvironment(graph, actions);

            procEnv.ApplyGraphRewriteSequence("create");

			Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found.");
			Console.WriteLine(procEnv.PerformanceInfo.RewritesPerformed + " rewrites performed.");
			procEnv.PerformanceInfo.Reset();

            IMatches matches = actions.GetAction("findIndependent").Match(procEnv, 0, null);
            Console.WriteLine(matches.Count + " matches found.");

            graph.Clear();

            procEnv.ApplyGraphRewriteSequence("createIterated");

            Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found.");
            Console.WriteLine(procEnv.PerformanceInfo.RewritesPerformed + " rewrites performed.");
            procEnv.PerformanceInfo.Reset();

            IAction_createIterated createIterated = actions.createIterated;
            IMatchesExact<Rule_createIterated.IMatch_createIterated> matchesCreateIterated = 
                createIterated.Match(procEnv, 0);
            IintNode beg;
            INode end;
            createIterated.Modify(procEnv, matchesCreateIterated.FirstExact, out beg, out end);

            IMatchesExact<Rule_findChainPlusChainToIntIndependent.IMatch_findChainPlusChainToIntIndependent> matchesFindChain =
                actions.findChainPlusChainToIntIndependent.Match(procEnv, 0, beg, end);
            Console.WriteLine(matchesFindChain.Count + " matches found.");
        }
Exemple #5
0
        public void Modify(GRGEN_LGSP.LGSPActionExecutionEnvironment actionEnv, GRGEN_LIBGR.IMatch _curMatch)
        {
            GRGEN_LGSP.LGSPGraph graph    = actionEnv.graph;
            Match_testRule       curMatch = (Match_testRule)_curMatch;

            GRGEN_LGSP.LGSPNode node_a = curMatch._node_a;
            GRGEN_LGSP.LGSPNode node_f = curMatch._node_f;
            GRGEN_LGSP.LGSPNode node_m = curMatch._node_m;
            graph.SettingAddedNodeNames(testRule_addedNodeNames);
            GRGEN_LGSP.LGSPNode        node_are  = graph.Retype(node_a, GRGEN_MODEL.NodeType_D2211_2222_31.typeVar);
            GRGEN_MODEL.ID2211_2222_31 inode_are = (GRGEN_MODEL.ID2211_2222_31)node_are;
            GRGEN_LGSP.LGSPNode        node_fre  = graph.Retype(node_f, GRGEN_MODEL.NodeType_D231_4121.typeVar);
            GRGEN_MODEL.ID231_4121     inode_fre = (GRGEN_MODEL.ID231_4121)node_fre;
            GRGEN_LGSP.LGSPNode        node_mre  = graph.Retype(node_m, GRGEN_MODEL.NodeType_D11_2221.typeVar);
            GRGEN_MODEL.ID11_2221      inode_mre = (GRGEN_MODEL.ID11_2221)node_mre;
            graph.SettingAddedEdgeNames(testRule_addedEdgeNames);
            {             // eval_0
                int tempvar_0 = (int )1234;
                graph.ChangingNodeAttribute(node_are, GRGEN_MODEL.NodeType_D2211_2222_31.AttributeType_d2211_2222_31, GRGEN_LIBGR.AttributeChangeType.Assign, tempvar_0, null);
                inode_are.@d2211_2222_31 = tempvar_0;
                graph.ChangedNodeAttribute(node_are, GRGEN_MODEL.NodeType_D2211_2222_31.AttributeType_d2211_2222_31);
                int tempvar_1 = (int )5678;
                graph.ChangingNodeAttribute(node_fre, GRGEN_MODEL.NodeType_D231_4121.AttributeType_d231_4121, GRGEN_LIBGR.AttributeChangeType.Assign, tempvar_1, null);
                inode_fre.@d231_4121 = tempvar_1;
                graph.ChangedNodeAttribute(node_fre, GRGEN_MODEL.NodeType_D231_4121.AttributeType_d231_4121);
                int tempvar_2 = (int )9012;
                graph.ChangingNodeAttribute(node_mre, GRGEN_MODEL.NodeType_D11_2221.AttributeType_d11_2221, GRGEN_LIBGR.AttributeChangeType.Assign, tempvar_2, null);
                inode_mre.@d11_2221 = tempvar_2;
                graph.ChangedNodeAttribute(node_mre, GRGEN_MODEL.NodeType_D11_2221.AttributeType_d11_2221);
            }
            return;
        }
        public virtual void FillAsClone(LGSPGraph originalGraph, IDictionary<IGraphElement, IGraphElement> oldToNewMap)
        {
            LGSPUniquenessEnsurer original = originalGraph.uniquenessEnsurer;

            nextNewId = original.nextNewId;

            heap.Clear(); // remove the -1
            heap.Capacity = original.heap.Capacity;
            heap.AddRange(original.heap);
        }
		public override IGraphElement[] ModifyNoReuse(LGSPGraph graph, LGSPMatch match)
		{
			LGSPNode node_p2 = match.nodes[ (int) NodeNums.@p2 - 1 ];
			LGSPNode node_p1 = match.nodes[ (int) NodeNums.@p1 - 1 ];
			LGSPEdge edge__edge0 = match.edges[ (int) EdgeNums.@_edge0 - 1 ];
			LGSPNode node__node0 = graph.AddNode(NodeType_Process.typeVar);
			LGSPEdge edge__edge1 = graph.AddEdge(EdgeType_connection.typeVar, node_p1, node__node0);
			LGSPEdge edge__edge2 = graph.AddEdge(EdgeType_connection.typeVar, node__node0, node_p2);
			graph.Remove(edge__edge0);
			return EmptyReturnElements;
		}
 static void PrintResults(int duration, LGSPGraph graph)
 {
     Console.WriteLine("Mutex benchmark: " + duration + " ms");
     Console.WriteLine("Number of nodes: " + graph.NumNodes);
     Console.WriteLine("Number of edges: " + graph.NumEdges);
     Console.WriteLine("Number of Process nodes: " + graph.GetNumExactNodes(Process.TypeInstance));
     Console.WriteLine("Number of Resource nodes: " + graph.GetNumExactNodes(Resource.TypeInstance));
     Console.WriteLine("Number of next edges: " + graph.GetNumExactEdges(next.TypeInstance));
     Console.WriteLine("Number of request edges: " + graph.GetNumExactEdges(request.TypeInstance));
     Console.WriteLine("Number of token edges: " + graph.GetNumExactEdges(token.TypeInstance));
 }
Exemple #9
0
 static void PrintResults(int duration, LGSPGraph graph)
 {
     Console.WriteLine("AntWorld benchmark: " + duration + " ms");
     Console.WriteLine("Number of nodes: " + graph.NumNodes);
     Console.WriteLine("Number of edges: " + graph.NumEdges);
     Console.WriteLine("Number of Process nodes: " + graph.GetNumExactNodes(Ant.TypeInstance));
     Console.WriteLine("Number of Resource nodes: " + graph.GetNumExactNodes(GridNode.TypeInstance));
     Console.WriteLine("Number of Process nodes: " + graph.GetNumExactNodes(GridCornerNode.TypeInstance));
     Console.WriteLine("Number of Resource nodes: " + graph.GetNumExactNodes(AntHill.TypeInstance));
     Console.WriteLine("Number of next edges: " + graph.GetNumExactEdges(NextAnt.TypeInstance));
     Console.WriteLine("Number of request edges: " + graph.GetNumExactEdges(GridEdge.TypeInstance));
     Console.WriteLine("Number of token edges: " + graph.GetNumExactEdges(PathToHill.TypeInstance));
     Console.WriteLine("Number of token edges: " + graph.GetNumExactEdges(AntPosition.TypeInstance));
 }
Exemple #10
0
        void DoIter()
        {
            graph = new LGSPGraph(new StdGraphModel());
            actions = new spanningTreeActions(graph);
            procEnv = new LGSPGraphProcessingEnvironment(graph, actions);

            IAction_initUndirected init = actions.initUndirected;
            IMatchesExact<Rule_initUndirected.IMatch_initUndirected> matchesInitUndirected = init.Match(procEnv, 0);
            INode root;
            init.Modify(procEnv, matchesInitUndirected.FirstExact, out root);

            IMatchesExact<Rule_spanningTree.IMatch_spanningTree> matchesSpanningTree = actions.spanningTree.Match(procEnv, 0, root);
            actions.spanningTree.Modify(procEnv, matchesSpanningTree.FirstExact);
            Console.WriteLine(matchesSpanningTree.Count + " matches found.");
        }
Exemple #11
0
 public static GRGEN_MODEL.@Node CreateNode(GRGEN_LGSP.LGSPGraph graph)
 {
     GRGEN_MODEL.@Node node;
     if (poolLevel == 0)
     {
         node = new GRGEN_MODEL.@Node();
     }
     else
     {
         node             = pool[--poolLevel];
         node.lgspInhead  = null;
         node.lgspOuthead = null;
         node.lgspFlags  &= ~(uint)GRGEN_LGSP.LGSPElemFlags.HAS_VARIABLES;
         // implicit initialization, container creation of Node
     }
     graph.AddNode(node);
     return(node);
 }
Exemple #12
0
 public static GRGEN_MODEL.@UEdge CreateEdge(GRGEN_LGSP.LGSPGraph graph, GRGEN_LGSP.LGSPNode source, GRGEN_LGSP.LGSPNode target)
 {
     GRGEN_MODEL.@UEdge edge;
     if (poolLevel == 0)
     {
         edge = new GRGEN_MODEL.@UEdge(source, target);
     }
     else
     {
         edge            = pool[--poolLevel];
         edge.lgspFlags &= ~(uint)GRGEN_LGSP.LGSPElemFlags.HAS_VARIABLES;
         edge.lgspSource = source;
         edge.lgspTarget = target;
         // implicit initialization, container creation of UEdge
     }
     graph.AddEdge(edge);
     return(edge);
 }
        public GraphMatchingState(LGSPGraph graph)
        {
            ++numGraphsComparedAtLeastOnce;

#if LOG_ISOMORPHY_CHECKING
            if(writer == null)
                writer = new StreamWriter("isocheck_log.txt");

            // print out the names of the type ids referenced in the interpretation plan when the first graph is initialized
            if(numGraphsComparedAtLeastOnce == 1)
            {
                foreach(NodeType nodeType in graph.Model.NodeModel.Types)
                    writer.WriteLine(nodeType.TypeID + " is node type " + nodeType.Name);
                foreach(EdgeType edgeType in graph.Model.EdgeModel.Types)
                    writer.WriteLine(edgeType.TypeID + " is edge type " + edgeType.Name);
                writer.Flush();
            }
#endif
        }
        public static bool ApplyXGRS_huh(GRGEN_LGSP.LGSPGraphProcessingEnvironment procEnv)
        {
            object x = procEnv.GetVariableValue("x");

            GRGEN_LGSP.LGSPGraph   graph   = procEnv.graph;
            GRGEN_LGSP.LGSPActions actions = procEnv.curActions;
            object a = procEnv.GetVariableValue("a");

            GRGEN_MODEL.N node_a = (GRGEN_MODEL.N)a;
            int           val_x  = (int)x;

            // announce change so that debugger can show new value or transaction manager can record it and roll it back
            graph.ChangingNodeAttribute(node_a, GRGEN_MODEL.NodeType_N.AttributeType_i, GRGEN_LIBGR.AttributeChangeType.Assign, val_x, null);
            node_a.i = val_x;
            // add reflexive edge
            GRGEN_MODEL.E someEdge = GRGEN_MODEL.E.CreateEdge(graph, node_a, node_a);
            // here you could do other nifty things like deleting nodes, retyping graph elements, or calling rules
            return(false);
        }
Exemple #15
0
        void DoTNT()
        {
            graph = new LGSPGraph(new TNTGraphModel());
            actions = new TNTActions(graph);
            procEnv = new LGSPGraphProcessingEnvironment(graph, actions);

            // use graph rewrite sequence
            procEnv.ApplyGraphRewriteSequence("createTNT");

            Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found.");
            Console.WriteLine(procEnv.PerformanceInfo.RewritesPerformed + " rewrites performed.");
            procEnv.PerformanceInfo.Reset();

            // use old inexact interface
            IMatches matchesInexact = actions.GetAction("TNT").Match(procEnv, 0, null);
            Console.WriteLine(matchesInexact.Count + " matches found.");

            // use new 2.5 exact interface
            IMatchesExact<Rule_ToluolCore.IMatch_ToluolCore> matchesExact = actions.ToluolCore.Match(procEnv, 0);
            Console.WriteLine(matchesExact.Count + " matches found.");
        }
        void DoAlt()
        {
            graph = new LGSPGraph(new AlternativesGraphModel());
            actions = new AlternativesActions(graph);
            procEnv = new LGSPGraphProcessingEnvironment(graph, actions);

            // use graph rewrite sequence
            procEnv.ApplyGraphRewriteSequence("createComplex");

            Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found.");
            Console.WriteLine(procEnv.PerformanceInfo.RewritesPerformed + " rewrites performed.");
            procEnv.PerformanceInfo.Reset();

            // use old inexact interface
            IMatches matches = actions.GetAction("Complex").Match(procEnv, 0, null);
            Console.WriteLine(matches.Count + " Complex matches found.");

            // use new 2.5 exact interface
            IMatchesExact<Rule_ComplexMax.IMatch_ComplexMax> matchesExact = actions.ComplexMax.Match(procEnv, 0);
            Console.WriteLine(matchesExact.Count + " ComplexMax matches found.");
        }
Exemple #17
0
 public static Node_Process CreateNode(LGSPGraph graph)
 {
     Node_Process node = new Node_Process();
     graph.AddNode(node);
     return node;
 }
Exemple #18
0
 public static Edge_connection CreateEdge(LGSPGraph graph, LGSPNode source, LGSPNode target)
 {
     Edge_connection edge = new Edge_connection(source, target);
     graph.AddEdge(edge);
     return edge;
 }
        /// <summary>
        /// Builds a pattern graph out of the graph.
        /// The pattern graph retains links to the original graph elements and uses them for attribute comparison.
        /// </summary>
        /// <param name="graph">The graph which is to be transfered into a pattern</param>
        /// <returns></returns>
        public PatternGraph BuildPatternGraph(LGSPGraph graph)
        {
            int numNodes = graph.NumNodes;
            int numEdges = graph.NumEdges;

            int count = 0;
            PatternNode[] nodes = new PatternNode[numNodes];
            INode[] correspondingNodes = new INode[numNodes];
            foreach(INode node in graph.Nodes)
            {
                LGSPNode n = (LGSPNode)node;
                nodes[count] = new PatternNode(
                    n.Type.TypeID, n.Type, n.Type.PackagePrefixedName,
                    graph.Name+"_node_"+count, "node_"+count,
                    null, null,
                    1.0f, -1, false,
                    null, null, null, null, null,
                    null, false, null
                );
                correspondingNodes[count] = node;
                ++count;
            }

            count = 0;
            PatternEdge[] edges = new PatternEdge[numEdges];
            IEdge[] correspondingEdges = new IEdge[numEdges];
            foreach(IEdge edge in graph.Edges)
            {
                LGSPEdge e = (LGSPEdge)edge;
                edges[count] = new PatternEdge(
                    true,
                    e.Type.TypeID, e.Type, e.Type.PackagePrefixedName,
                    graph.Name+"_edge_"+count, "edge_"+count,
                    null, null,
                    1.0f, -1, false,
                    null, null, null, null, null,
                    null, false, null
                );
                correspondingEdges[count] = edge;
                ++count;
            }

            bool[,] homNodes = new bool[numNodes, numNodes];
            for(int i = 0; i < numNodes; ++i)
                for(int j = 0; j < numNodes; ++j)
                    homNodes[i, j] = false;

            bool[,] homEdges = new bool[numEdges, numEdges];
            for(int i = 0; i < numEdges; ++i)
                for(int j = 0; j < numEdges; ++j)
                    homEdges[i, j] = false;
            
            bool[,] homNodesGlobal = new bool[numNodes, numNodes];
            for(int i = 0; i < numNodes; ++i)
                for(int j = 0; j < numNodes; ++j)
                    homNodesGlobal[i, j] = false;

            bool[,] homEdgesGlobal = new bool[numEdges, numEdges];
            for(int i = 0; i < numEdges; ++i)
                for(int j = 0; j < numEdges; ++j)
                    homEdgesGlobal[i, j] = false;

            bool[] totallyHomNodes = new bool[numNodes];
            for(int i = 0; i < numNodes; ++i)
                totallyHomNodes[i] = false;

            bool[] totallyHomEdges = new bool[numEdges];
            for(int i = 0; i < numEdges; ++i)
                totallyHomEdges[i] = false;

            List<PatternCondition> pcs = new List<PatternCondition>();
            for(int i = 0; i < numNodes; ++i)
            {
                if(nodes[i].Type.NumAttributes > 0)
                    pcs.Add(new PatternCondition(new expression.AreAttributesEqual(correspondingNodes[i], nodes[i]),
                        new string[] { nodes[i].name }, new string[] { }, new string[] { }, new VarType[] { }));
            }
            for(int i = 0; i < numEdges; ++i)
            {
                if(edges[i].Type.NumAttributes > 0)
                    pcs.Add(new PatternCondition(new expression.AreAttributesEqual(correspondingEdges[i], edges[i]),
                        new string[] { }, new string[] { edges[i].name }, new string[] { }, new VarType[] { }));
            }
            PatternCondition[] patternConditions = pcs.ToArray();

            PatternGraph patternGraph = new PatternGraph(
                graph.Name, "",
                null, graph.Name,
                false, false,
                nodes, edges, new PatternVariable[0],
                new PatternGraphEmbedding[0], new Alternative[0], new Iterated[0],
                new PatternGraph[0], new PatternGraph[0],
                patternConditions, new PatternYielding[0],
                homNodes, homEdges,
                homNodesGlobal, homEdgesGlobal,
                totallyHomNodes, totallyHomEdges
            );
            foreach(PatternNode node in nodes)
                node.pointOfDefinition = patternGraph;
            foreach(PatternEdge edge in edges)
                edge.pointOfDefinition = patternGraph;
            patternGraph.correspondingNodes = correspondingNodes;
            patternGraph.correspondingEdges = correspondingEdges;

            foreach(IEdge edge in graph.Edges)
            {
                int edgeIndex = Array.IndexOf<IEdge>(correspondingEdges, edge);
                int sourceIndex = Array.IndexOf<INode>(correspondingNodes, edge.Source);
                int targetIndex = Array.IndexOf<INode>(correspondingNodes, edge.Target);
                patternGraph.edgeToSourceNode.Add(edges[edgeIndex], nodes[sourceIndex]);
                patternGraph.edgeToTargetNode.Add(edges[edgeIndex], nodes[targetIndex]);
            }

            PatternGraphAnalyzer.PrepareInline(patternGraph);

            return patternGraph;
        }
 public testActions(LGSPGraph lgspgraph)
     : base(lgspgraph)
 {
     InitActions();
 }
Exemple #21
0
 /// <summary>
 /// Copy constructor.
 /// </summary>
 /// <param name="dataSource">The LGSPGraph object to get the data from</param>
 /// <param name="newName">Name of the copied graph.</param>
 public LGSPGraph(LGSPGraph dataSource, String newName)
 {
     graphID = graphIDSource;
     ++graphIDSource;
     
     IDictionary<IGraphElement, IGraphElement> oldToNewMap;
     Copy(dataSource, newName, out oldToNewMap);
 }
Exemple #22
0
        /// <summary>
        /// Loads a LGSPActions instance from the given file.
        /// If the file is a ".cs" file it will be compiled first.
        /// </summary>
        public static LGSPActions LoadActions(String actionFilename, LGSPGraph graph)
        {
            Assembly assembly;
            String assemblyName;

            String extension = Path.GetExtension(actionFilename);
            if(extension.Equals(".cs", StringComparison.OrdinalIgnoreCase))
            {
                CSharpCodeProvider compiler = new CSharpCodeProvider();
                CompilerParameters compParams = new CompilerParameters();
                compParams.ReferencedAssemblies.Add("System.dll");
                compParams.ReferencedAssemblies.Add(Assembly.GetAssembly(typeof(IBackend)).Location);
                compParams.ReferencedAssemblies.Add(Assembly.GetAssembly(typeof(LGSPActions)).Location);
                compParams.ReferencedAssemblies.Add(graph.modelAssemblyName);

                //                compParams.GenerateInMemory = true;
                compParams.CompilerOptions = "/optimize";
                compParams.OutputAssembly = String.Format("lgsp-action-assembly-{0:00000}.dll", actionID++);

                CompilerResults compResults = compiler.CompileAssemblyFromFile(compParams, actionFilename);
                if(compResults.Errors.HasErrors)
                {
                    String errorMsg = compResults.Errors.Count + " Errors:";
                    foreach(CompilerError error in compResults.Errors)
                        errorMsg += String.Format("\r\nLine: {0} - {1}", error.Line, error.ErrorText);
                    throw new ArgumentException("Illegal actions C# source code: " + errorMsg);
                }

                assembly = compResults.CompiledAssembly;
                assemblyName = compParams.OutputAssembly;
            }
            else if(extension.Equals(".dll", StringComparison.OrdinalIgnoreCase))
            {
                assembly = Assembly.LoadFrom(actionFilename);
                assemblyName = actionFilename;
                if(graph.backend != null) graph.backend.AddAssembly(assembly);          // TODO: still needed??
            }
            else
            {
                throw new ArgumentException("The action filename must be either a .cs or a .dll filename!");
            }

            Type actionsType = null;
            try
            {
                foreach(Type type in assembly.GetTypes())
                {
                    if(!type.IsClass || type.IsNotPublic) continue;
                    if(type.BaseType == typeof(LGSPActions))
                    {
                        if(actionsType != null)
                        {
                            throw new ArgumentException(
                                "The given action file contains more than one LGSPActions implementation!");
                        }
                        actionsType = type;
                    }
                }
            }
            catch(ReflectionTypeLoadException e)
            {
                String errorMsg = "";
                foreach(Exception ex in e.LoaderExceptions)
                    errorMsg += "- " + ex.Message + Environment.NewLine;
                if(errorMsg.Length == 0) errorMsg = e.Message;
                throw new ArgumentException(errorMsg);
            }
            if(actionsType == null)
                throw new ArgumentException("The given action file doesn't contain an LGSPActions implementation!");

            LGSPActions actions = (LGSPActions)Activator.CreateInstance(actionsType, graph, graph.modelAssemblyName, assemblyName);

            if(graph.Model.MD5Hash != actions.ModelMD5Hash)
                throw new ArgumentException("The given action file has been compiled with another model assembly!");

            return actions;
        }
		/// <summary>
		/// Canonize a graph
		/// </summary>
		/// <param name="graph">The graph to canonize.</param>
		public string Canonize (LGSPGraph graph)
		{
			elementTypeNameMap = new Dictionary<IGraphElement, string> ();
			//List of virtual nodes
			coNodes = new List<CoNode> ();
			nodeToCoNodeIndexMap = new Dictionary<INode, int> ();

			typeNames = new List<string> ();
			edgeTypeNames = new List<string> ();

			//Build virtual node(s) for each node and edge
			//Build the vNode -> typeID Map (2 entries for every directed edge class)

			foreach (var n in graph.Nodes) {
				string nodeTypeString = CanonizeElement (n);
				elementTypeNameMap [n] = nodeTypeString;
				if (!typeNames.Contains (nodeTypeString)) {
					typeNames.Add (nodeTypeString);
				}

				CoNode con = new CoNode (n);
				nodeToCoNodeIndexMap [n] = coNodes.Count;

				coNodes.Add (con);
			}

			foreach (var e in graph.Edges) {
				string edgeTypeString = CanonizeElement (e);
				elementTypeNameMap [e] = edgeTypeString;
				if (!edgeTypeNames.Contains (edgeTypeString)) {
					edgeTypeNames.Add (edgeTypeString);
				}
			}

			typeNames.Sort ();
			edgeTypeNames.Sort ();

			typeNameIDMap = new Dictionary<string, long> ();
			edgeTypeNameIDMap = new Dictionary<string, long> ();

			for (int i=0; i<typeNames.Count; i++) {
				string typeName = typeNames [i];
				typeNameIDMap [typeName] = (long)i;
			}
		
			{
				//increment by 3, types reserved for undirected, tail, head
				int index = 0;

				for (int i=0; i<edgeTypeNames.Count; i++) {
					string edgeTypeName = edgeTypeNames [i];
					edgeTypeNameIDMap [edgeTypeName] = index;
					index += 3;
				}
			}

			coNodeTypeIDs = coNodes.ConvertAll (x => 0L);

			foreach (var n in graph.Nodes) {
				int index = nodeToCoNodeIndexMap [n];
				string typeName = elementTypeNameMap [n];
				coNodeTypeIDs [index] = (typeNameIDMap [typeName]);
			}

			nodeNeighborMap = new Dictionary<INode, Dictionary<INode, IEdgeList>> ();

			//Fill in neighbormap
			foreach (var curNode in graph.Nodes) {
				Dictionary<INode, IEdgeList> neighborMap = new Dictionary<INode, IEdgeList> ();
				foreach (var e in curNode.Incident) {
					INode toNode = e.Opposite (curNode);
					if (!neighborMap.ContainsKey (toNode)) {
						neighborMap [toNode] = new IEdgeList ();
					}
					if (!neighborMap [toNode].Contains (e)) {
						neighborMap [toNode].Add (e);
					}
				}
				nodeNeighborMap [curNode] = neighborMap;
			}

			//Now every coNode corresponing to an INode has a correct typeID associated with it ...
			//There is a disjoint set of IDs (starting at 0) reserved in the edgeTypeNameIDMap
			edgeCoNodeTypeIDs = new List<long> ();
			Dictionary<INode, bool> visitedNodeSet = new Dictionary<INode, bool> ();
			connectedComponents = new List<List<int>> ();

			//Partition into connected components
			foreach (var n in graph.Nodes) {
				if (!visitedNodeSet.ContainsKey (n)) {
					visitedNodeSet [n] = true;
					List<int> connectedComponent = new List<int> ();
					BuildConnectedComponent (n, visitedNodeSet, connectedComponent);
					BuildCoNodes(connectedComponent);
					connectedComponents.Add (connectedComponent);
				}
			}


			if (edgeCoNodeTypeIDs.Count != 0) {
				PartialRankOrderList (edgeCoNodeTypeIDs);
				for (int i=0; i<edgeCoNodeTypeIDs.Count; i++) {
					edgeCoNodeTypeIDs [i] += (long)typeNames.Count;
				}
			}
			//Concat the edgeTypeIDs (built in RecurisveCoNodeBuild) to coNodeTypeIDs
			coNodeTypeIDs.AddRange(edgeCoNodeTypeIDs);
			List<String> connectedComponentStrings = new List<String> (connectedComponents.Count);

			foreach (var connectedComponent in connectedComponents) {
				connectedComponentStrings.Add (CanonizeConnectedComponent (connectedComponent));
			}

			connectedComponentStrings.Sort ();

			StringBuilder sb = new StringBuilder ();

			for (int i=0; i<(connectedComponentStrings.Count-1); i++) {
				sb.Append (connectedComponentStrings[i] + ".");
			}

			sb.Append(connectedComponentStrings[connectedComponentStrings.Count-1]);
			return sb.ToString();
		}
Exemple #24
0
 public void FillAsClone(GRGEN_LGSP.LGSPGraph originalGraph, IDictionary <GRGEN_LIBGR.IGraphElement, GRGEN_LIBGR.IGraphElement> oldToNewMap)
 {
 }
Exemple #25
0
 public StdIndexSet(GRGEN_LGSP.LGSPGraph graph)
 {
 }
 public override void Initialize(LGSPGraph graph, LGSPActions actions)
 {
     SetClearVariables(false);
     base.Initialize(graph, actions);
     SetClearVariables(true);
 }
        public LGSPMatches myMatch(LGSPGraph graph, int maxMatches, IGraphElement[] parameters)
        {
            matches.matches.Clear();
            // Lookup(edge__edge0:connection)
            foreach(EdgeType edge_type_edge__edge0 in EdgeType_connection.typeVar.SubOrSameTypes)
            {
                for(LGSPEdge edge_head_edge__edge0 = graph.edgesByTypeHeads[edge_type_edge__edge0.TypeID], edge_cur_edge__edge0 = edge_head_edge__edge0.typeNext; edge_cur_edge__edge0 != edge_head_edge__edge0; edge_cur_edge__edge0 = edge_cur_edge__edge0.typeNext)
                {
                    // ImplicitTarget(edge__edge0 -> node_p2:Process)
                    LGSPNode node_cur_node_p2 = edge_cur_edge__edge0.target;
                    if(!NodeType_Process.isMyType[node_cur_node_p2.type.TypeID]) goto contunmap_edge_cur_edge__edge0_2;
                    node_cur_node_p2.mappedTo = 1;
                    // ImplicitSource(edge__edge0 -> node_p1:Process)
                    LGSPNode node_cur_node_p1 = edge_cur_edge__edge0.source;
                    if(!NodeType_Process.isMyType[node_cur_node_p1.type.TypeID]) goto contunmap_node_cur_node_p2_4;
                    if(node_cur_node_p1.mappedTo != 0) goto cont_node_cur_node_p1_7;
                    LGSPMatch match = matchesList.GetNewMatch();
                    match.nodes[0] = node_cur_node_p2;
                    match.nodes[1] = node_cur_node_p1;
                    match.edges[0] = edge_cur_edge__edge0;
                    matchesList.CommitMatch();
                    if(maxMatches > 0 && matchesList.Count >= maxMatches)
                    {
                        node_cur_node_p2.mappedTo = 0;
                        graph.MoveHeadAfter(edge_cur_edge__edge0);
                        return matches;
                    }
cont_node_cur_node_p1_7:;
contunmap_node_cur_node_p2_4:;
                    node_cur_node_p2.mappedTo = 0;
contunmap_edge_cur_edge__edge0_2:;
                    // Tail of Lookup(edge_cur_edge__edge0)
                }
            }
            return matches;
        }
Exemple #28
0
        public GRGEN_LIBGR.IMatchesExact <Rule_testRule.IMatch_testRule> myMatch(GRGEN_LGSP.LGSPActionExecutionEnvironment actionEnv, int maxMatches)
        {
            GRGEN_LGSP.LGSPGraph graph = actionEnv.graph;
            matches.Clear();
            int isoSpace = 0;
            // Lookup testRule_edge__edge1
            int type_id_candidate_testRule_edge__edge1 = 1;

            for (GRGEN_LGSP.LGSPEdge head_candidate_testRule_edge__edge1 = graph.edgesByTypeHeads[type_id_candidate_testRule_edge__edge1], candidate_testRule_edge__edge1 = head_candidate_testRule_edge__edge1.lgspTypeNext; candidate_testRule_edge__edge1 != head_candidate_testRule_edge__edge1; candidate_testRule_edge__edge1 = candidate_testRule_edge__edge1.lgspTypeNext)
            {
                uint prev__candidate_testRule_edge__edge1;
                prev__candidate_testRule_edge__edge1      = candidate_testRule_edge__edge1.lgspFlags & (uint)GRGEN_LGSP.LGSPElemFlags.IS_MATCHED << isoSpace;
                candidate_testRule_edge__edge1.lgspFlags |= (uint)GRGEN_LGSP.LGSPElemFlags.IS_MATCHED << isoSpace;
                // Implicit Source testRule_node_f from testRule_edge__edge1
                GRGEN_LGSP.LGSPNode candidate_testRule_node_f = candidate_testRule_edge__edge1.lgspSource;
                if (candidate_testRule_node_f.lgspType.TypeID != 6)
                {
                    candidate_testRule_edge__edge1.lgspFlags = candidate_testRule_edge__edge1.lgspFlags & ~((uint)GRGEN_LGSP.LGSPElemFlags.IS_MATCHED << isoSpace) | prev__candidate_testRule_edge__edge1;
                    continue;
                }
                // Implicit Target testRule_node_m from testRule_edge__edge1
                GRGEN_LGSP.LGSPNode candidate_testRule_node_m = candidate_testRule_edge__edge1.lgspTarget;
                if (candidate_testRule_node_m.lgspType.TypeID != 17)
                {
                    candidate_testRule_edge__edge1.lgspFlags = candidate_testRule_edge__edge1.lgspFlags & ~((uint)GRGEN_LGSP.LGSPElemFlags.IS_MATCHED << isoSpace) | prev__candidate_testRule_edge__edge1;
                    continue;
                }
                // Extend Incoming testRule_edge__edge0 from testRule_node_f
                GRGEN_LGSP.LGSPEdge head_candidate_testRule_edge__edge0 = candidate_testRule_node_f.lgspInhead;
                if (head_candidate_testRule_edge__edge0 != null)
                {
                    GRGEN_LGSP.LGSPEdge candidate_testRule_edge__edge0 = head_candidate_testRule_edge__edge0;
                    do
                    {
                        if (candidate_testRule_edge__edge0.lgspType.TypeID != 1)
                        {
                            continue;
                        }
                        if ((candidate_testRule_edge__edge0.lgspFlags & (uint)GRGEN_LGSP.LGSPElemFlags.IS_MATCHED << isoSpace) != 0)
                        {
                            continue;
                        }
                        // Implicit Source testRule_node_a from testRule_edge__edge0
                        GRGEN_LGSP.LGSPNode candidate_testRule_node_a = candidate_testRule_edge__edge0.lgspSource;
                        if (candidate_testRule_node_a.lgspType.TypeID != 18)
                        {
                            continue;
                        }
                        Rule_testRule.Match_testRule match = matches.GetNextUnfilledPosition();
                        match._node_a      = candidate_testRule_node_a;
                        match._node_f      = candidate_testRule_node_f;
                        match._node_m      = candidate_testRule_node_m;
                        match._edge__edge0 = candidate_testRule_edge__edge0;
                        match._edge__edge1 = candidate_testRule_edge__edge1;
                        matches.PositionWasFilledFixIt();
                        // if enough matches were found, we leave
                        if (maxMatches > 0 && matches.Count >= maxMatches)
                        {
                            candidate_testRule_node_f.MoveInHeadAfter(candidate_testRule_edge__edge0);
                            graph.MoveHeadAfter(candidate_testRule_edge__edge1);
                            candidate_testRule_edge__edge1.lgspFlags = candidate_testRule_edge__edge1.lgspFlags & ~((uint)GRGEN_LGSP.LGSPElemFlags.IS_MATCHED << isoSpace) | prev__candidate_testRule_edge__edge1;
                            return(matches);
                        }
                    }while((candidate_testRule_edge__edge0 = candidate_testRule_edge__edge0.lgspInNext) != head_candidate_testRule_edge__edge0);
                }
                candidate_testRule_edge__edge1.lgspFlags = candidate_testRule_edge__edge1.lgspFlags & ~((uint)GRGEN_LGSP.LGSPElemFlags.IS_MATCHED << isoSpace) | prev__candidate_testRule_edge__edge1;
            }
            return(matches);
        }
Exemple #29
0
 public testActions(GRGEN_LGSP.LGSPGraph lgspgraph)
     : base(lgspgraph)
 {
     InitActions();
 }
        void DoIt()
        {
            // create the LibGr Search Plan backend we want to use
            LGSPBackend backend = new LGSPBackend();

            // the graph model we'll use
            JavaProgramGraphsGraphModel model = new JavaProgramGraphsGraphModel();

            // the actions object for the rules we'll to use
            IActions ba;

            // import the instance graph we created with gxl2grs, using the the .gm we created by hand
            // (can't use import gxl for the program graph, because the given .gxl is severly rotten)
            // we throw away the named graph cause we don't need names here and they require about the same amount of memory as the graph itself; 
            INamedGraph importedNamedGraph = (INamedGraph)Porter.Import("InstanceGraph.grs", backend, model, out ba);
            LGSPGraph graph = new LGSPGraph((LGSPNamedGraph)importedNamedGraph, "unnamed");
            importedNamedGraph = null;
            
            // get the actions object for the rules we want to use
            JavaProgramGraphsActions actions = ba!=null ? (JavaProgramGraphsActions)ba : new JavaProgramGraphsActions(graph);

            // the graph processing environment we'll use
            LGSPGraphProcessingEnvironment procEnv = new LGSPGraphProcessingEnvironment(graph, actions);

            // the instance graph script uses variables to build up the graph,
            // we query some of them here, to get the elements to refactor
            // (instead of variables one could use the element names)
            Class src = (Class)procEnv.GetNodeVarValue("I176"); // class Node
            Class tgt = (Class)procEnv.GetNodeVarValue("I194"); // class Packet - use if parameter is used in moving method
            //Class tgt = (Class)graph.GetNodeVarValue("I617"); // class String - use if instance variable is used in moving method
            MethodBody mb = (MethodBody)procEnv.GetNodeVarValue("I409"); // method body of send

            // get operation for method body by: 
            // get action, match action pattern with given parameters, apply rewrite filling given out parameters
            IMatchesExact<Rule_getOperation.IMatch_getOperation> matches = actions.getOperation.Match(procEnv, 1, mb);
            IOperation op;
            actions.getOperation.Modify(procEnv, matches.FirstExact, out op);

            // iterated application of action marking the body of the expression
            // (shows second way of getting action)
            int visitedFlagId = graph.AllocateVisitedFlag();
            Debug.Assert(visitedFlagId==0);
            IGraphElement[] param = new LGSPNode[1];
            param[0] = mb;
            IMatches matchesInexact;
            while((matchesInexact = actions.GetAction("markExpressionOfBody").Match(procEnv, 1, param)).Count == 1)
            {
                actions.GetAction("markExpressionOfBody").Modify(procEnv, matchesInexact.First);
            }

            // application of a graph rewrite sequence
            procEnv.SetVariableValue("src", src);
            procEnv.SetVariableValue("tgt", tgt);
            procEnv.SetVariableValue("mb", mb);
            procEnv.SetVariableValue("op", op);
            procEnv.ApplyGraphRewriteSequence(
                @"(p)=someParameterOfTargetType(mb,tgt) 
                    && !callToSuperExists && !isStatic(mb) && !methodNameExists(mb,tgt) 
                    && (!thisIsAccessed || thisIsAccessed && (srcparam)=addSourceParameter(op,src) && useSourceParameter(srcparam)*) 
                    && relinkOperationAndMethodBody(op,mb,src,tgt) 
                    && ( (call,pe)=getUnprocessedCallWithActualParameter(op,p) 
                         && ((def(srcparam) && addSourceToCall(call,srcparam)) || true) 
                         && (replaceAccess_Parameter_AccessWithoutLink(c,pe) || replaceAccess_Parameter_AccessWithLinkToExpression(c,pe)) 
                       )*");

            Console.WriteLine(procEnv.PerformanceInfo.MatchesFound + " matches found.");
            procEnv.PerformanceInfo.Reset();

            // unmark the body of the expression by searching all occurences and modifying them
            actions.unmarkExpression.ApplyAll(0, procEnv);
            graph.FreeVisitedFlag(visitedFlagId);

            // export changed graph (alternatively you may export it as InstanceGraphAfter.gxl)
            // if we'd use a NamedGraph we'd get the graph exported with its persistent names; so we get it exported with some hash names
            List<String> exportParameters = new List<string>();
            exportParameters.Add("InstanceGraphAfter.grs");
            Porter.Export(graph, exportParameters);
        }
Exemple #31
0
 /// <summary>
 /// Copy and extend constructor, creates a named graph from a normal graph.
 /// Initializes the name maps with the names provided in a given attribute each graph element must have
 /// </summary>
 /// <param name="graph">The graph to be used named</param>
 /// <param name="nameAttributeName">The name of the attribute to be used for naming</param>
 public LGSPNamedGraph(LGSPGraph graph, String nameAttributeName)
     : base(graph, graph.Name, out tmpOldToNewMap)
 {
     NameToElem = new Dictionary<String, IGraphElement>(graph.NumNodes + graph.NumEdges);
     ElemToName = new Dictionary<IGraphElement, String>(graph.NumNodes + graph.NumEdges);
     tmpOldToNewMap = null;
     DoName(nameAttributeName);
 }
Exemple #32
0
 public testActions(GRGEN_LGSP.LGSPGraph lgspgraph, string modelAsmName, string actionsAsmName)
     : base(lgspgraph, modelAsmName, actionsAsmName)
 {
     InitActions();
 }
        /// <summary>
        /// Generates scheduled search plans needed for matcher code generation for action compilation
        /// out of graph with analyze information, 
        /// The scheduled search plans are added to the main and the nested pattern graphs.
        /// </summary>
        public void GenerateScheduledSearchPlans(PatternGraph patternGraph, LGSPGraph graph,
            bool isSubpatternLike, bool isNegativeOrIndependent, 
            ScheduledSearchPlan nestingScheduledSearchPlan)
        {
            for(int i=0; i<patternGraph.schedules.Length; ++i)
            {
                patternGraph.AdaptToMaybeNull(i);
                if(Profile)
                    SetNeedForProfiling(patternGraph);
                PlanGraph planGraph = GeneratePlanGraph(graph.statistics, patternGraph,
                    isNegativeOrIndependent, isSubpatternLike,
                    ExtractOwnElements(nestingScheduledSearchPlan, patternGraph));
                MarkMinimumSpanningArborescence(planGraph, patternGraph.name);
                SearchPlanGraph searchPlanGraph = GenerateSearchPlanGraph(planGraph);
                ScheduledSearchPlan scheduledSearchPlan = ScheduleSearchPlan(
                    searchPlanGraph, patternGraph, isNegativeOrIndependent);
                AppendHomomorphyInformation(scheduledSearchPlan);
                patternGraph.schedules[i] = scheduledSearchPlan;
                patternGraph.RevertMaybeNullAdaption(i);

                foreach(PatternGraph neg in patternGraph.negativePatternGraphsPlusInlined)
                {
                    GenerateScheduledSearchPlans(neg, graph,
                        isSubpatternLike, true, null);
                }

                foreach(PatternGraph idpt in patternGraph.independentPatternGraphsPlusInlined)
                {
                    GenerateScheduledSearchPlans(idpt, graph,
                        isSubpatternLike, true, patternGraph.schedules[i]);
                }

                foreach(Alternative alt in patternGraph.alternativesPlusInlined)
                {
                    foreach (PatternGraph altCase in alt.alternativeCases)
                    {
                        GenerateScheduledSearchPlans(altCase, graph,
                            true, false, null);
                    }
                }

                foreach(Iterated iter in patternGraph.iteratedsPlusInlined)
                {
                    GenerateScheduledSearchPlans(iter.iteratedPattern, graph,
                        true, false, null);
                }
            }
        }
Exemple #34
0
        /// <summary>
        /// Constructs a new LGSPActions instance.
        /// This constructor is deprecated.
        /// </summary>
        /// <param name="lgspgraph">The associated graph.</param>
        /// <param name="modelAsmName">The name of the model assembly.</param>
        /// <param name="actionsAsmName">The name of the actions assembly.</param>
        public LGSPActions(LGSPGraph lgspgraph, String modelAsmName, String actionsAsmName)
        {
            graph = lgspgraph;
            modelAssemblyName = modelAsmName;
            actionsAssemblyName = actionsAsmName;
            matcherGenerator = new LGSPMatcherGenerator(graph.Model);
#if ASSERT_ALL_UNMAPPED_AFTER_MATCH
            OnMatched += new AfterMatchHandler(AssertAllUnmappedAfterMatch);
#endif
        }
        /// <summary>
        /// Generate new actions for the given actions, doing the same work, 
        /// but hopefully faster by taking graph analysis information into account
        /// </summary>
        public LGSPAction[] GenerateActions(LGSPGraph graph, String modelAssemblyName, String actionsAssemblyName, 
            params LGSPAction[] actions)
        {
            if(actions.Length == 0) throw new ArgumentException("No actions provided!");

            SourceBuilder sourceCode = new SourceBuilder(CommentSourceCode);
            GenerateFileHeaderForActionsFile(sourceCode, model.GetType().Namespace, actions[0].rulePattern.GetType().Namespace);

            // use domain of dictionary as set with rulepatterns of the subpatterns of the actions, get them from pattern graph
            Dictionary<LGSPMatchingPattern, LGSPMatchingPattern> subpatternMatchingPatterns 
                = new Dictionary<LGSPMatchingPattern, LGSPMatchingPattern>();
            foreach (LGSPAction action in actions)
            {
                foreach (KeyValuePair<LGSPMatchingPattern, LGSPMatchingPattern> usedSubpattern 
                    in action.rulePattern.patternGraph.usedSubpatterns)
                {
                    subpatternMatchingPatterns[usedSubpattern.Key] = usedSubpattern.Value;
                }
            }

            // generate code for subpatterns
            foreach (KeyValuePair<LGSPMatchingPattern, LGSPMatchingPattern> subpatternMatchingPattern in subpatternMatchingPatterns)
            {
                LGSPMatchingPattern smp = subpatternMatchingPattern.Key;

                GenerateScheduledSearchPlans(smp.patternGraph, graph, 
                    true, false, null);

                MergeNegativeAndIndependentSchedulesIntoEnclosingSchedules(smp.patternGraph);

                ParallelizeAsNeeded(smp);

                GenerateActionAndMatcher(sourceCode, smp, false);
            }

            // generate code for actions
            foreach(LGSPAction action in actions)
            {
                GenerateScheduledSearchPlans(action.rulePattern.patternGraph, graph,
                    false, false, null);

                MergeNegativeAndIndependentSchedulesIntoEnclosingSchedules(action.rulePattern.patternGraph);

                ParallelizeAsNeeded(action.rulePattern);

                GenerateActionAndMatcher(sourceCode, action.rulePattern, false);
            }

            // close namespace
            sourceCode.Append("}");

            if(DumpDynSourceCode)
            {
                using(StreamWriter writer = new StreamWriter("dynamic_" + actions[0].Name + ".cs"))
                    writer.Write(sourceCode.ToString());
            }

            // set up compiler
            CSharpCodeProvider compiler = new CSharpCodeProvider();
            CompilerParameters compParams = GetDynCompilerSetup(modelAssemblyName, actionsAssemblyName);
 
            // compile generated code
            CompilerResults compResults = compiler.CompileAssemblyFromSource(compParams, sourceCode.ToString());
            if(compResults.Errors.HasErrors)
            {
                String errorMsg = compResults.Errors.Count + " Errors:";
                foreach(CompilerError error in compResults.Errors)
                    errorMsg += Environment.NewLine + "Line: " + error.Line + " - " + error.ErrorText;
                throw new ArgumentException("Internal error: Illegal dynamic C# source code produced: " + errorMsg);
            }

            // create action instances
            LGSPAction[] newActions = new LGSPAction[actions.Length];
            for(int i = 0; i < actions.Length; i++)
            {
                newActions[i] = (LGSPAction) compResults.CompiledAssembly.CreateInstance(
                    "de.unika.ipd.grGen.lgspActions.DynAction_" + actions[i].Name);
                if(newActions[i] == null)
                    throw new ArgumentException("Internal error: Generated assembly does not contain action '"
                        + actions[i].Name + "'!");
            }
            return newActions;
        }
Exemple #36
0
        /// <summary>
        /// Constructs a new LGSPActions instance.
        /// </summary>
        /// <param name="lgspgraph">The associated graph.</param>
        public LGSPActions(LGSPGraph lgspgraph)
        {
            graph = lgspgraph;
            matcherGenerator = new LGSPMatcherGenerator(graph.Model);

            modelAssemblyName = Assembly.GetAssembly(graph.Model.GetType()).Location;
            actionsAssemblyName = Assembly.GetAssembly(this.GetType()).Location;

#if ASSERT_ALL_UNMAPPED_AFTER_MATCH
            OnMatched += new AfterMatchHandler(AssertAllUnmappedAfterMatch);
#endif
        }
 /// <summary>
 /// Generate a new action for the given action, doing the same work, 
 /// but hopefully faster by taking graph analysis information into account
 /// </summary>
 public LGSPAction GenerateAction(LGSPGraph graph, String modelAssemblyName, String actionsAssemblyName, LGSPAction action)
 {
     return GenerateActions(graph, modelAssemblyName, actionsAssemblyName, action)[0];
 }
Exemple #38
0
        /// <summary>
        /// Copy constructor helper.
        /// </summary>
        /// <param name="dataSource">The LGSPGraph object to get the data from</param>
        /// <param name="newName">Name of the copied graph.</param>
        /// <param name="oldToNewMap">A map of the old elements to the new elements after cloning,
        /// just forget about it if you don't need it.</param>
        private void Copy(LGSPGraph dataSource, String newName, out IDictionary<IGraphElement, IGraphElement> oldToNewMap)
        {
            model = dataSource.model;
            name = newName;

            InitializeGraph();

            model.CreateAndBindIndexSet(this);

            if(dataSource.backend != null)
            {
                backend = dataSource.backend;
                modelAssemblyName = dataSource.modelAssemblyName;
            }

            oldToNewMap = new Dictionary<IGraphElement, IGraphElement>();

            for(int i = 0; i < dataSource.nodesByTypeHeads.Length; i++)
            {
                for(LGSPNode head = dataSource.nodesByTypeHeads[i], node = head.lgspTypePrev; node != head; node = node.lgspTypePrev)
                {
                    LGSPNode newNode = (LGSPNode) node.Clone();
                    AddNodeWithoutEvents(newNode, node.lgspType.TypeID);
                    oldToNewMap[node] = newNode;
                }
            }

            for(int i = 0; i < dataSource.edgesByTypeHeads.Length; i++)
            {
                for(LGSPEdge head = dataSource.edgesByTypeHeads[i], edge = head.lgspTypePrev; edge != head; edge = edge.lgspTypePrev)
                {
                    LGSPEdge newEdge = (LGSPEdge) edge.Clone((INode) oldToNewMap[edge.lgspSource], (INode) oldToNewMap[edge.lgspTarget]);
                    AddEdgeWithoutEvents(newEdge, newEdge.lgspType.TypeID);
                    oldToNewMap[edge] = newEdge;
                }
            }

            /* TODO: remove when cloning of graph variables was implemented
             * foreach(KeyValuePair<IGraphElement, LinkedList<Variable>> kvp in dataSource.ElementMap)
            {
                IGraphElement newElem = oldToNewMap[kvp.Key];
                foreach(Variable var in kvp.Value)
                    SetVariableValue(var.Name, newElem);
            }*/

            model.FillIndexSetAsClone(this, dataSource, oldToNewMap);

            statistics = new LGSPGraphStatistics(this.Model);
            statistics.Copy(dataSource);
        }
 public testActions(LGSPGraph lgspgraph, IDumperFactory dumperfactory, String modelAsmName, String actionsAsmName)
     : base(lgspgraph, dumperfactory, modelAsmName, actionsAsmName)
 {
     InitActions();
 }