Example #1
0
 /// <summary>
 /// Given a graph, rewrite is given the heuristics of this pattern class
 /// </summary>
 /// <param name="graph"></param>
 /// <returns></returns>
 public List<SnapshotNode> RewriteFromPattern(List<SnapshotNode> graph)
 {
     List<SnapshotNode> n=new List<SnapshotNode>();
     foreach (SnapshotNode c in graph)
                         n.Add(c);
     foreach (SnapshotNode node in n)
     {
         if (node.Type == SnapshotNodeType.Function)
         {
             string[] functionQualifers = node.Content.Split(';');
             switch (functionQualifers[1])
             {
                 case "Math.Sin":
                 case "Math.Cos":
                 case "Math.Tan":
                     SnapshotNode ssn = new SnapshotNode((uint)(node.Id * 100), node.Type, "Math.dll;Math.RadiansToDegrees; ");
                     List<Connection> inp = new List<Connection>();
                     foreach (Connection c in node.InputList)
                         inp.Add(c);
                     ssn.InputList = inp;
                     ssn.OutputList = new List<Connection>();
                     graph.Add(ssn);
                     Connection connection = new Connection();
                     connection.OtherNode = ssn.Id;
                     connection.LocalIndex = 0;
                     connection.OtherIndex = 0;
                     int num = graph.IndexOf(node);
                     graph[num].InputList.Clear();
                     graph[num].InputList.Add(connection);
                     break;
                 default: break;
             }
         }
     }
     return graph;
 }
Example #2
0
        public static List<SnapshotNode> NodeToCodeBlocks(List<SnapshotNode> inputs, GraphToDSCompiler.GraphCompiler originalGC)
        {
            List<SnapshotNode> codeBlocks = new List<SnapshotNode>();
            GraphToDSCompiler.GraphCompiler newGC = GraphCompiler.CreateInstance();

            newGC.SetCore(core);
            GraphToDSCompiler.SynchronizeData newSyncData = new SynchronizeData();
            newSyncData.AddedNodes = inputs;
            newSyncData.ModifiedNodes = new List<SnapshotNode>();
            newSyncData.RemovedNodes = new List<uint>();
            GraphToDSCompiler.GraphBuilder GB = new GraphBuilder(newSyncData, newGC);

            #region fix connection for multi-line CBN
            /*for multi-line code blocks*/
            List<Node> completeList = originalGC.Graph.nodeList;
            List<uint> originalNodeUIDList = new List<uint>();
            foreach (Node oriGcNode in completeList)
            {
                originalNodeUIDList.Add(oriGcNode.Guid);
            }

            GB.AddNodesToAST();

            //List<SnapshotNode> inputsCopy = new List<SnapshotNode>(inputs);
            for (int i = 0; i < inputs.Count; i++)
            {
                SnapshotNode inputSnapshotNode = inputs[i];
                for (int j = 0; j < inputSnapshotNode.InputList.Count; j++)
                {
                    Connection inputConnection = inputSnapshotNode.InputList[j];
                    if (!originalNodeUIDList.Contains(inputConnection.OtherNode))
                    {
                        Connection correctedInputConnection = new Connection();
                        correctedInputConnection.LocalName = inputConnection.LocalName;
                        correctedInputConnection.LocalIndex = inputConnection.LocalIndex;
                        correctedInputConnection.IsImplicit = inputConnection.IsImplicit;
                        correctedInputConnection.OtherIndex = inputConnection.OtherIndex;
                        if (newGC.codeBlockUIDMap.ContainsKey(inputConnection.OtherNode))
                        {
                            correctedInputConnection.OtherNode = newGC.codeBlockUIDMap[inputConnection.OtherNode][inputConnection.OtherIndex];
                        }
                        else
                        {
                            correctedInputConnection.OtherNode = originalGC.codeBlockUIDMap[inputConnection.OtherNode][inputConnection.OtherIndex];
                        }
                        inputSnapshotNode.InputList.Remove(inputConnection);
                        inputSnapshotNode.InputList.Insert(j, correctedInputConnection);
                    }
                }
                for (int j = 0; j < inputSnapshotNode.OutputList.Count; j++)
                {
                    Connection outputConnection = inputSnapshotNode.OutputList[j];
                    if (!originalNodeUIDList.Contains(outputConnection.OtherNode))                       // if the other node is split
                    {
                        Connection correctedInputConnection = new Connection();
                        correctedInputConnection.LocalName = outputConnection.LocalName;
                        correctedInputConnection.LocalIndex = outputConnection.LocalIndex;
                        correctedInputConnection.IsImplicit = outputConnection.IsImplicit;
                        correctedInputConnection.OtherIndex = outputConnection.OtherIndex;
                        if (newGC.codeBlockUIDMap.ContainsKey(outputConnection.OtherNode))
                        {
                            correctedInputConnection.OtherNode = newGC.GetUidOfRHSIdentifierInCodeBlock(
                                outputConnection.OtherNode, outputConnection.OtherIndex, outputConnection.LocalName);
                            //correctedInputConnection.OtherNode = newGC.codeBlockUIDMap[outputConnection.OtherNode][outputConnection.OtherIndex];
                        }
                        else
                        {
                            correctedInputConnection.OtherNode = originalGC.codeBlockUIDMap[outputConnection.OtherNode][outputConnection.OtherIndex];
                        }
                        inputSnapshotNode.OutputList.Remove(outputConnection);
                        inputSnapshotNode.OutputList.Insert(j, correctedInputConnection);
                    }
                }
            }
            GB.nodesToAdd = inputs;
            GB.MakeConnectionsForAddedNodes_NodeToCode(GB.nodesToAdd);
            newGC.PrintGraph();
            #endregion

            //GB.BuildGraphForCodeBlock();

            List<uint> nodesToBeAdded = new List<uint>();
            List<Node> nodesToBeReplaced = new List<Node>();

            //adding children node from the originalGC to the newGC needed for the newGC to generate code
            foreach (Node n in completeList)
            {
                foreach (Node child in n.GetChildren())
                {
                    if (newGC.Graph.GetNode(child.Guid) != null)
                    {
                        if (child.Name != newGC.Graph.GetNode(child.Guid).Name)
                        {
                            nodesToBeReplaced.Add(child);
                        }
                    }
                }
            }

            foreach (uint n in nodesToBeAdded)
            {
                Node n1 = completeList.FirstOrDefault(q => q.Guid == n);
                //n1.children.Clear();
                nodesToBeReplaced.Add(n1);
                //newSyncData.RemovedNodes.Add(n);
            }

            List<uint> nodeToCodeUIDs = new List<uint>();
            foreach (SnapshotNode ssn in inputs)
                nodeToCodeUIDs.Add(ssn.Id);
            newGC.nodeToCodeUIDs = nodeToCodeUIDs;

            /*create output snapshot nodes*/
            List<Connection> inputNodeInputConnections = new List<Connection>();
            List<Connection> inputNodeOutputConnections = new List<Connection>();
            foreach (SnapshotNode ssn in inputs)
            {
                foreach (Connection inputConnection in ssn.InputList)
                {
                    if (!nodeToCodeUIDs.Contains(inputConnection.OtherNode))
                        inputNodeInputConnections.Add(inputConnection);
                }
                foreach (Connection outputConnection in ssn.OutputList)
                {
                    if (!nodeToCodeUIDs.Contains(outputConnection.OtherNode))
                        inputNodeOutputConnections.Add(outputConnection);
                }
            }

            newGC.ReplaceNodesFromAList(nodesToBeReplaced);
            newSyncData.AddedNodes = new List<SnapshotNode>();
            newSyncData.ModifiedNodes = new List<SnapshotNode>();
            newSyncData.RemovedNodes = new List<uint>();
            GB = new GraphBuilder(newSyncData, newGC);
            //string result = GB.BuildGraphDAG();
            List<SnapshotNode> nodeToCodeBlocks = GB.PrintCodeForSelectedNodes(originalGC, inputs);

            /*for now, only connected nodes are supported: return all connections that are not internal connections (connections between the selected nodes)*/
            //uint id = 0;
            //foreach (string content in toCode)
            //{
            //    SnapshotNode ssn = new SnapshotNode();
            //    ssn.Type = SnapshotNodeType.CodeBlock;
            //    ssn.Content = content;
            //    ssn.Id = id++;
            //    ssn.InputList = new List<Connection>();
            //    //stupid stub
            //    foreach (Connection inputConnection in inputNodeInputConnections)
            //    {
            //        Connection newInputConnection = new Connection();
            //        newInputConnection.OtherNode = inputConnection.OtherNode;
            //        newInputConnection.OtherIndex = inputConnection.OtherIndex;
            //        newInputConnection.IsImplicit = inputConnection.IsImplicit;
            //        string[] tokens = newGC.Graph.GetNode(inputConnection.OtherNode).Name.Split('=');
            //        newInputConnection.LocalName = tokens[0];
            //        ssn.InputList.Add(newInputConnection);
            //    }
            //    //ssn.InputList = inputNodeInputConnections;
            //    ssn.OutputList = new List<Connection>();
            //    foreach (Connection outputConnection in inputNodeOutputConnections)
            //    {
            //        Connection newOutputConnection = new Connection();
            //        newOutputConnection.OtherNode = outputConnection.OtherNode;
            //        newOutputConnection.OtherIndex = outputConnection.OtherIndex;
            //        newOutputConnection.IsImplicit = outputConnection.IsImplicit;
            //        //string[] tokens = originalGC.Graph.GetNode(outputConnection.OtherNode).Name.Split('=');
            //        newOutputConnection.LocalName = outputConnection.LocalName;
            //        ssn.OutputList.Add(newOutputConnection);
            //    }
            //    //ssn.OutputList = inputNodeOutputConnections;
            //    codeBlocks.Add(ssn);
            //}

            /*update the original GC*/
            foreach (SnapshotNode inputNode in inputs)
            {
                if (originalNodeUIDList.Contains(inputNode.Id))
                    originalGC.RemoveNodes(inputNode.Id, false);
                else
                {
                    foreach (KeyValuePair<uint, Dictionary<int, uint>> kvp in originalGC.codeBlockUIDMap)
                    {
                        if (kvp.Value.ContainsValue(inputNode.Id))
                        {
                            originalGC.RemoveNodes(kvp.Key, false);
                        }
                    }
                }
            }
            foreach (Node node in newGC.Graph.nodeList)
            {
                node.Name = node.Name.TrimEnd(';') + ";";
            }
            originalGC.Graph.nodeList.Union<Node>(newGC.Graph.nodeList);
            //originalGC = newGC;
            /**/

            return nodeToCodeBlocks;
            //return codeBlocks;
        }

        /// <summary>
        /// This is called to Parse individual assignment statements in Codeblock nodes in GraphUI
        /// and return the resulting ProtoAST node
        /// </summary>
        /// <param name="statement"></param>
        public static ProtoCore.AST.Node Parse(string statement, out ProtoCore.AST.AssociativeAST.CodeBlockNode commentNode)
        {
            commentNode = null;
            BuildCore(true);

            Validity.Assert(core != null);
            Validity.Assert(statement != null);

            if (string.IsNullOrEmpty(statement))
                return null;

            System.IO.MemoryStream memstream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(statement));
            ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(memstream);
            ProtoCore.DesignScriptParser.Parser p = new ProtoCore.DesignScriptParser.Parser(s, core);

            p.Parse();
            commentNode = p.commentNode;

            return p.root;
        }

        public static bool Parse(Guid nodeGUID, ref string code, 
                                 out List<ProtoCore.AST.Node> parsedNodes, 
                                 out IEnumerable<ProtoCore.BuildData.ErrorEntry> errors,
                                 out IEnumerable<ProtoCore.BuildData.WarningEntry> warnings, 
                                 List<String> unboundIdentifiers, 
                                 out List<String> tempIdentifiers)
        {
            tempIdentifiers = new List<string>();

            List<String> compiledCode = new List<String>();
            parsedNodes = null;
            //-----------------------------------------------------------------------------------
            //--------------------------------Correct the code-----------------------------------
            //-----------------------------------------------------------------------------------
            // Use the compile expression to format the code by adding the required %t temp vars
            // needed for non assignment statements
            CompileExpression(code, out compiledCode);

            string codeToParse = "";
            for (int i = 0; i < compiledCode.Count; i++)
            {
                string tempVariableName = string.Format("temp_{0}_", i) + nodeGUID.ToString().Replace("-", "_");
                tempIdentifiers.Add(tempVariableName);

                string singleExpression = compiledCode[i];
                singleExpression = singleExpression.Replace("%t", tempVariableName);
                codeToParse += singleExpression;
            }

            code = codeToParse;

            //Catch the errors thrown by compile expression, namely function modiferstack and class decl found
            if (core.BuildStatus.ErrorCount > 0)
            {
                errors = core.BuildStatus.Errors;
                warnings = core.BuildStatus.Warnings;
                parsedNodes = null;
                return false;
            }

            // Parse and compile the code to get the result AST nodes as well as
            // any errors or warnings that were caught by the comiler
            ProtoCore.BuildStatus buildStatus;
            var tempUnboundIdentifiers = new Dictionary<int, List<VariableLine>>();
            List<ProtoCore.AST.Node> nodeList = new List<ProtoCore.AST.Node>();

            ParseCodeBlockNodeStatements(codeToParse, out tempUnboundIdentifiers, out nodeList, out buildStatus);
            errors = buildStatus.Errors;
            warnings = buildStatus.Warnings;

            //Get the unboundIdentifiers from the warnings
            foreach (KeyValuePair<int, List<VariableLine>> kvp in tempUnboundIdentifiers)
            {
                foreach (VariableLine vl in kvp.Value)
                {
                    if (!unboundIdentifiers.Contains(vl.variable))
                    {
                        unboundIdentifiers.Add(vl.variable);
                    }
                }
            }

            // Assign the 'out' variables
            // Use the parse function to get the parsed nodes to return to the
            // user
            if (nodeList != null)
            {
                parsedNodes = new List<ProtoCore.AST.Node>();
                ProtoCore.AST.AssociativeAST.CodeBlockNode cNode;
                parsedNodes = ParserUtils.GetAstNodes(Parse(codeToParse, out cNode));
            }
            else
            {
                parsedNodes = null;
            }

            return true;
        }

        public static List<ProtoCore.AST.Node> ParseCodeBlock(string code)
        {
            Validity.Assert(code != null);

            if (string.IsNullOrEmpty(code))
                return null;

            // TODO: Change the logic to ignore Import statements in this case using parser - pratapa
            // Check if this will work with modifier blocks as well
            /*string[] stmts = code.Split(';');
            string source = "";
            for (int i=0; i < stmts.Length; ++i)
            {
                if (!stmts[i].Contains("import"))
                    source += stmts[i] + ";";
            }*/

            ProtoCore.Options options = new ProtoCore.Options();
            ProtoCore.Core core = new ProtoCore.Core(options);
            core.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(core));
            core.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(core));

            System.IO.MemoryStream memstream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(code));
            ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(memstream);
            ProtoCore.DesignScriptParser.Parser p = new ProtoCore.DesignScriptParser.Parser(s, core);

            p.Parse();
            ProtoCore.AST.AssociativeAST.CodeBlockNode cbn = p.root as ProtoCore.AST.AssociativeAST.CodeBlockNode;

            Validity.Assert(cbn != null);
            return p.GetParsedASTList(cbn);
        }
Example #3
0
 private static List<Connection> ProcessConnectionLists(string[] f)
 {
     List<Connection> lc = new List<Connection>();
     for (int i = 0; i < f.Length - 1; i++)
     {
         Connection con = new Connection();
         string[] c = f[i].Split(ConnectionDataMemberMarker);
         con.OtherNode = uint.Parse(c[0]);
         con.LocalIndex = Int32.Parse(c[1]);
         con.OtherIndex = Int32.Parse(c[2]);
         con.LocalName = c[3];
         lc.Add(con);
     }
     return lc;
 }
Example #4
0
        public void ConnectTo(uint connectToUid, int localIndex, int otherIndex, bool isConnectingFromInputSlot, bool isImplicit, string name = "")
        {
            Connection connection = new Connection();
            connection.LocalIndex = localIndex;
            connection.LocalName = name;
            connection.OtherIndex = otherIndex;
            connection.OtherNode = connectToUid;
            connection.IsImplicit = isImplicit;

            if (isConnectingFromInputSlot)
            {
                InputList.Add(connection);
            }
            else
            {
                OutputList.Add(connection);
            }
        }
Example #5
0
 public void TestDeltaExecution03()
 {
     //===========================================================================
     // Creates:
     //      driver  node a = 10
     //      driver node b= 20
     //      and using '+' operator node and assign it to idetifier
     //===========================================================================
     ILiveRunner liveRunner = new ProtoScript.Runners.Obsolete.LiveRunner();
     //===========================================================================
     // Build the driver node a=10
     //===========================================================================
     GraphToDSCompiler.SynchronizeData data = new GraphToDSCompiler.SynchronizeData();
     uint uidDriver1 = 1;
     uint uidDriver2 = 2;
     uint uidOp1 = 3;
     uint uidIdent1 = 4;
     Connection k1 = new Connection();
     k1.LocalIndex = 0;// output slot
     k1.OtherIndex = 0;// input slot
     k1.OtherNode = uidOp1;
     k1.LocalName = "a";
     Connection k2 = new Connection();
     k2.LocalIndex = 0;
     k2.OtherIndex = 1;
     k2.OtherNode = uidOp1;
     k2.LocalName = "b";
     Connection k4 = new Connection();
     k4.LocalIndex = 0;
     k4.OtherIndex = 0;
     k4.OtherNode = uidDriver1;
     Connection k5 = new Connection();
     k5.LocalIndex = 1;
     k5.OtherIndex = 0;
     k5.OtherNode = uidDriver2;
     Connection k6 = new Connection();
     k6.LocalIndex = 0;
     k6.OtherIndex = 0;
     k6.OtherNode = uidIdent1;
     Connection k7 = new Connection();
     k7.LocalIndex = 0;
     k7.OtherIndex = 0;
     k7.OtherNode = uidOp1;
     SnapshotNode n1 = new SnapshotNode(uidDriver1, SnapshotNodeType.CodeBlock, "a=10;");
     n1.OutputList.Add(k1);
     SnapshotNode n2 = new SnapshotNode(uidDriver2, SnapshotNodeType.CodeBlock, "b=20;");
     n2.OutputList.Add(k2);
     SnapshotNode n3 = new SnapshotNode(uidOp1, SnapshotNodeType.Function, ";+;double,double;temp");
     n3.InputList.Add(k4);
     n3.InputList.Add(k5);
     n3.OutputList.Add(k6);
     SnapshotNode n4 = new SnapshotNode(uidIdent1, SnapshotNodeType.Identifier, "A");
     n4.InputList.Add(k7);
     data.AddedNodes.Add(n1);
     data.AddedNodes.Add(n2);
     data.AddedNodes.Add(n3);
     data.AddedNodes.Add(n4);
     //===========================================================================
     // Compile the current graph
     //===========================================================================
     liveRunner.UpdateGraph(data);
     //===========================================================================
     // Verify the value of Identifier
     //===========================================================================
     ProtoCore.Mirror.RuntimeMirror mirror = liveRunner.QueryNodeValue(uidIdent1);
     Assert.IsTrue(mirror.GetData().GetStackValue().opdata == 30);
 }
Example #6
0
 public void TestDeltaExecution01()
 {
     //===========================================================================
     // Creates:
     //      a = 10
     //
     // Adds:
     //      b = 20
     //===========================================================================
     ILiveRunner liveRunner = new ProtoScript.Runners.Obsolete.LiveRunner();
     //===========================================================================
     // Build the first snapshot nodes a = 10
     //===========================================================================
     GraphToDSCompiler.SynchronizeData data = new GraphToDSCompiler.SynchronizeData();
     uint uidIdent = 1;
     uint uidLiteral = 2;
     Connection k1 = new Connection();
     k1.LocalIndex = 0;
     k1.OtherIndex = 0;
     k1.OtherNode = uidLiteral;
     Connection k2 = new Connection();
     k2.LocalIndex = 0;
     k2.OtherIndex = 0;
     k2.OtherNode = uidIdent;
     SnapshotNode n1 = new SnapshotNode(uidIdent, SnapshotNodeType.Identifier, "a");
     n1.InputList.Add(k1);
     SnapshotNode n2 = new SnapshotNode(uidLiteral, SnapshotNodeType.Literal, "10");
     n2.OutputList.Add(k2);
     data.AddedNodes.Add(n1);
     data.AddedNodes.Add(n2);
     //===========================================================================
     // Compile the current graph
     //===========================================================================
     liveRunner.UpdateGraph(data);
     //===========================================================================
     // Build the first snapshot nodes b = 10
     //===========================================================================
     uint uidIdent2 = 10;
     uint uidLiteral2 = 20;
     data = new GraphToDSCompiler.SynchronizeData();
     k1 = new Connection();
     k1.LocalIndex = 0;
     k1.OtherIndex = 0;
     k1.OtherNode = uidLiteral2;
     k2 = new Connection();
     k2.LocalIndex = 0;
     k2.OtherIndex = 0;
     k2.OtherNode = uidIdent2;
     n1 = new SnapshotNode(uidIdent2, SnapshotNodeType.Identifier, "b");
     n1.InputList.Add(k1);
     n2 = new SnapshotNode(uidLiteral2, SnapshotNodeType.Literal, "20");
     n2.OutputList.Add(k2);
     data.AddedNodes.Add(n1);
     data.AddedNodes.Add(n2);
     //===========================================================================
     // Compile the current graph and added graph
     //===========================================================================
     liveRunner.UpdateGraph(data);
     //===========================================================================
     // Verify the value of 'a'
     //===========================================================================
     ProtoCore.Mirror.RuntimeMirror mirror = liveRunner.QueryNodeValue(uidIdent);
     Assert.IsTrue(mirror.GetData().GetStackValue().opdata == 10);
     //===========================================================================
     // Verify the value of 'b'
     //===========================================================================
     mirror = liveRunner.QueryNodeValue(uidIdent2);
     Assert.IsTrue(mirror.GetData().GetStackValue().opdata == 20);
 }
Example #7
0
        public static List<SnapshotNode> NodeToCodeBlocks(List<SnapshotNode> inputs, GraphToDSCompiler.GraphCompiler originalGC)
        {
            List<SnapshotNode> codeBlocks = new List<SnapshotNode>();
            GraphToDSCompiler.GraphCompiler newGC = GraphCompiler.CreateInstance();

            newGC.SetCore(core);
            GraphToDSCompiler.SynchronizeData newSyncData = new SynchronizeData();
            newSyncData.AddedNodes = inputs;
            newSyncData.ModifiedNodes = new List<SnapshotNode>();
            newSyncData.RemovedNodes = new List<uint>();
            GraphToDSCompiler.GraphBuilder GB = new GraphBuilder(newSyncData, newGC);

            #region fix connection for multi-line CBN
            /*for multi-line code blocks*/
            List<Node> completeList = originalGC.Graph.nodeList;
            List<uint> originalNodeUIDList = new List<uint>();
            foreach (Node oriGcNode in completeList)
            {
                originalNodeUIDList.Add(oriGcNode.Guid);
            }

            GB.AddNodesToAST();
            
            //List<SnapshotNode> inputsCopy = new List<SnapshotNode>(inputs);
            for (int i = 0; i < inputs.Count; i++)
            {
                SnapshotNode inputSnapshotNode = inputs[i];
                for (int j = 0; j < inputSnapshotNode.InputList.Count; j++)
                {
                    Connection inputConnection = inputSnapshotNode.InputList[j];
                    if (!originalNodeUIDList.Contains(inputConnection.OtherNode))
                    {
                        Connection correctedInputConnection = new Connection();
                        correctedInputConnection.LocalName = inputConnection.LocalName;
                        correctedInputConnection.LocalIndex = inputConnection.LocalIndex;
                        correctedInputConnection.IsImplicit = inputConnection.IsImplicit;
                        correctedInputConnection.OtherIndex = inputConnection.OtherIndex;
                        if (newGC.codeBlockUIDMap.ContainsKey(inputConnection.OtherNode))
                        {
                            correctedInputConnection.OtherNode = newGC.codeBlockUIDMap[inputConnection.OtherNode][inputConnection.OtherIndex];
                        }
                        else 
                        {
                            correctedInputConnection.OtherNode = originalGC.codeBlockUIDMap[inputConnection.OtherNode][inputConnection.OtherIndex];
                        }
                        inputSnapshotNode.InputList.Remove(inputConnection);
                        inputSnapshotNode.InputList.Insert(j, correctedInputConnection);
                    }
                }
                for (int j = 0; j < inputSnapshotNode.OutputList.Count; j++)
                {
                    Connection outputConnection = inputSnapshotNode.OutputList[j];
                    if (!originalNodeUIDList.Contains(outputConnection.OtherNode))                       // if the other node is split
                    {
                        Connection correctedInputConnection = new Connection();
                        correctedInputConnection.LocalName = outputConnection.LocalName;
                        correctedInputConnection.LocalIndex = outputConnection.LocalIndex;
                        correctedInputConnection.IsImplicit = outputConnection.IsImplicit;
                        correctedInputConnection.OtherIndex = outputConnection.OtherIndex;
                        if (newGC.codeBlockUIDMap.ContainsKey(outputConnection.OtherNode))
                        {
                            correctedInputConnection.OtherNode = newGC.GetUidOfRHSIdentifierInCodeBlock(
                                outputConnection.OtherNode, outputConnection.OtherIndex, outputConnection.LocalName);
                            //correctedInputConnection.OtherNode = newGC.codeBlockUIDMap[outputConnection.OtherNode][outputConnection.OtherIndex];
                        }
                        else
                        {
                            correctedInputConnection.OtherNode = originalGC.codeBlockUIDMap[outputConnection.OtherNode][outputConnection.OtherIndex];
                        }
                        inputSnapshotNode.OutputList.Remove(outputConnection);
                        inputSnapshotNode.OutputList.Insert(j, correctedInputConnection);
                    }
                }
            }
            GB.nodesToAdd = inputs;
            GB.MakeConnectionsForAddedNodes_NodeToCode(GB.nodesToAdd);
            newGC.PrintGraph();
            #endregion

            //GB.BuildGraphForCodeBlock();
            
            List<uint> nodesToBeAdded = new List<uint>();
            List<Node> nodesToBeReplaced = new List<Node>();

            //adding children node from the originalGC to the newGC needed for the newGC to generate code
            foreach (Node n in completeList)
            {
                foreach (Node child in n.GetChildren())
                {
                    if (newGC.Graph.GetNode(child.Guid) != null)
                    {
                        if (child.Name != newGC.Graph.GetNode(child.Guid).Name)
                        {
                            nodesToBeReplaced.Add(child);
                        }
                    }
                }
            }

            foreach (uint n in nodesToBeAdded)
            {
                Node n1 = completeList.FirstOrDefault(q => q.Guid == n);
                //n1.children.Clear();
                nodesToBeReplaced.Add(n1);
                //newSyncData.RemovedNodes.Add(n);
            }

            List<uint> nodeToCodeUIDs = new List<uint>();
            foreach (SnapshotNode ssn in inputs)
                nodeToCodeUIDs.Add(ssn.Id);
            newGC.nodeToCodeUIDs = nodeToCodeUIDs;

            /*create output snapshot nodes*/
            List<Connection> inputNodeInputConnections = new List<Connection>();
            List<Connection> inputNodeOutputConnections = new List<Connection>();
            foreach (SnapshotNode ssn in inputs)
            {
                foreach (Connection inputConnection in ssn.InputList)
                {
                    if (!nodeToCodeUIDs.Contains(inputConnection.OtherNode))
                        inputNodeInputConnections.Add(inputConnection);
                }
                foreach (Connection outputConnection in ssn.OutputList)
                {
                    if (!nodeToCodeUIDs.Contains(outputConnection.OtherNode))
                        inputNodeOutputConnections.Add(outputConnection);
                }
            }

            newGC.ReplaceNodesFromAList(nodesToBeReplaced);
            newSyncData.AddedNodes = new List<SnapshotNode>();
            newSyncData.ModifiedNodes = new List<SnapshotNode>();
            newSyncData.RemovedNodes = new List<uint>();
            GB = new GraphBuilder(newSyncData, newGC);
            //string result = GB.BuildGraphDAG();           
            List<SnapshotNode> nodeToCodeBlocks = GB.PrintCodeForSelectedNodes(originalGC, inputs);

            

            /*for now, only connected nodes are supported: return all connections that are not internal connections (connections between the selected nodes)*/
            //uint id = 0;
            //foreach (string content in toCode)
            //{
            //    SnapshotNode ssn = new SnapshotNode();
            //    ssn.Type = SnapshotNodeType.CodeBlock;
            //    ssn.Content = content;
            //    ssn.Id = id++;
            //    ssn.InputList = new List<Connection>();
            //    //stupid stub
            //    foreach (Connection inputConnection in inputNodeInputConnections)
            //    {
            //        Connection newInputConnection = new Connection();
            //        newInputConnection.OtherNode = inputConnection.OtherNode;
            //        newInputConnection.OtherIndex = inputConnection.OtherIndex;
            //        newInputConnection.IsImplicit = inputConnection.IsImplicit;
            //        string[] tokens = newGC.Graph.GetNode(inputConnection.OtherNode).Name.Split('=');
            //        newInputConnection.LocalName = tokens[0];
            //        ssn.InputList.Add(newInputConnection);
            //    }
            //    //ssn.InputList = inputNodeInputConnections; 
            //    ssn.OutputList = new List<Connection>();
            //    foreach (Connection outputConnection in inputNodeOutputConnections)
            //    {
            //        Connection newOutputConnection = new Connection();
            //        newOutputConnection.OtherNode = outputConnection.OtherNode;
            //        newOutputConnection.OtherIndex = outputConnection.OtherIndex;
            //        newOutputConnection.IsImplicit = outputConnection.IsImplicit;
            //        //string[] tokens = originalGC.Graph.GetNode(outputConnection.OtherNode).Name.Split('=');
            //        newOutputConnection.LocalName = outputConnection.LocalName;
            //        ssn.OutputList.Add(newOutputConnection);
            //    }
            //    //ssn.OutputList = inputNodeOutputConnections;
            //    codeBlocks.Add(ssn);
            //}
            
            /*update the original GC*/
            foreach (SnapshotNode inputNode in inputs)
            {
                if (originalNodeUIDList.Contains(inputNode.Id))
                    originalGC.RemoveNodes(inputNode.Id, false);
                else 
                {
                    foreach (KeyValuePair<uint, Dictionary<int, uint>> kvp in originalGC.codeBlockUIDMap)
                    {
                        if (kvp.Value.ContainsValue(inputNode.Id))
                        {
                            originalGC.RemoveNodes(kvp.Key, false);
                        }
                    }
                }
            }
            foreach (Node node in newGC.Graph.nodeList)
            {
                node.Name = node.Name.TrimEnd(';') + ";";
            }
            originalGC.Graph.nodeList.Union<Node>(newGC.Graph.nodeList);
            //originalGC = newGC;
            /**/

            return nodeToCodeBlocks;
            //return codeBlocks;
        }
        public static List<SnapshotNode> NodeToCodeBlocks(List<SnapshotNode> inputs, GraphToDSCompiler.GraphCompiler originalGC)
        {
            List<SnapshotNode> codeBlocks = new List<SnapshotNode>();
            GraphToDSCompiler.GraphCompiler newGC = GraphCompiler.CreateInstance();

            newGC.SetCore(compileState);
            GraphToDSCompiler.SynchronizeData newSyncData = new SynchronizeData();
            newSyncData.AddedNodes = inputs;
            newSyncData.ModifiedNodes = new List<SnapshotNode>();
            newSyncData.RemovedNodes = new List<uint>();
            GraphToDSCompiler.GraphBuilder GB = new GraphBuilder(newSyncData, newGC);

            #region fix connection for multi-line CBN
            /*for multi-line code blocks*/
            List<Node> completeList = originalGC.Graph.nodeList;
            List<uint> originalNodeUIDList = new List<uint>();
            foreach (Node oriGcNode in completeList)
            {
                originalNodeUIDList.Add(oriGcNode.Guid);
            }

            GB.AddNodesToAST();

            //List<SnapshotNode> inputsCopy = new List<SnapshotNode>(inputs);
            for (int i = 0; i < inputs.Count; i++)
            {
                SnapshotNode inputSnapshotNode = inputs[i];
                for (int j = 0; j < inputSnapshotNode.InputList.Count; j++)
                {
                    Connection inputConnection = inputSnapshotNode.InputList[j];
                    if (!originalNodeUIDList.Contains(inputConnection.OtherNode))
                    {
                        Connection correctedInputConnection = new Connection();
                        correctedInputConnection.LocalName = inputConnection.LocalName;
                        correctedInputConnection.LocalIndex = inputConnection.LocalIndex;
                        correctedInputConnection.IsImplicit = inputConnection.IsImplicit;
                        correctedInputConnection.OtherIndex = inputConnection.OtherIndex;
                        if (newGC.codeBlockUIDMap.ContainsKey(inputConnection.OtherNode))
                        {
                            correctedInputConnection.OtherNode = newGC.codeBlockUIDMap[inputConnection.OtherNode][inputConnection.OtherIndex];
                        }
                        else
                        {
                            correctedInputConnection.OtherNode = originalGC.codeBlockUIDMap[inputConnection.OtherNode][inputConnection.OtherIndex];
                        }
                        inputSnapshotNode.InputList.Remove(inputConnection);
                        inputSnapshotNode.InputList.Insert(j, correctedInputConnection);
                    }
                }
                for (int j = 0; j < inputSnapshotNode.OutputList.Count; j++)
                {
                    Connection outputConnection = inputSnapshotNode.OutputList[j];
                    if (!originalNodeUIDList.Contains(outputConnection.OtherNode))                       // if the other node is split
                    {
                        Connection correctedInputConnection = new Connection();
                        correctedInputConnection.LocalName = outputConnection.LocalName;
                        correctedInputConnection.LocalIndex = outputConnection.LocalIndex;
                        correctedInputConnection.IsImplicit = outputConnection.IsImplicit;
                        correctedInputConnection.OtherIndex = outputConnection.OtherIndex;
                        if (newGC.codeBlockUIDMap.ContainsKey(outputConnection.OtherNode))
                        {
                            correctedInputConnection.OtherNode = newGC.GetUidOfRHSIdentifierInCodeBlock(
                                outputConnection.OtherNode, outputConnection.OtherIndex, outputConnection.LocalName);
                            //correctedInputConnection.OtherNode = newGC.codeBlockUIDMap[outputConnection.OtherNode][outputConnection.OtherIndex];
                        }
                        else
                        {
                            correctedInputConnection.OtherNode = originalGC.codeBlockUIDMap[outputConnection.OtherNode][outputConnection.OtherIndex];
                        }
                        inputSnapshotNode.OutputList.Remove(outputConnection);
                        inputSnapshotNode.OutputList.Insert(j, correctedInputConnection);
                    }
                }
            }
            GB.nodesToAdd = inputs;
            GB.MakeConnectionsForAddedNodes_NodeToCode(GB.nodesToAdd);
            newGC.PrintGraph();
            #endregion

            //GB.BuildGraphForCodeBlock();

            List<uint> nodesToBeAdded = new List<uint>();
            List<Node> nodesToBeReplaced = new List<Node>();

            //adding children node from the originalGC to the newGC needed for the newGC to generate code
            foreach (Node n in completeList)
            {
                foreach (Node child in n.GetChildren())
                {
                    if (newGC.Graph.GetNode(child.Guid) != null)
                    {
                        if (child.Name != newGC.Graph.GetNode(child.Guid).Name)
                        {
                            nodesToBeReplaced.Add(child);
                        }
                    }
                }
            }

            foreach (uint n in nodesToBeAdded)
            {
                Node n1 = completeList.FirstOrDefault(q => q.Guid == n);
                //n1.children.Clear();
                nodesToBeReplaced.Add(n1);
                //newSyncData.RemovedNodes.Add(n);
            }

            List<uint> nodeToCodeUIDs = new List<uint>();
            foreach (SnapshotNode ssn in inputs)
                nodeToCodeUIDs.Add(ssn.Id);
            newGC.nodeToCodeUIDs = nodeToCodeUIDs;

            /*create output snapshot nodes*/
            List<Connection> inputNodeInputConnections = new List<Connection>();
            List<Connection> inputNodeOutputConnections = new List<Connection>();
            foreach (SnapshotNode ssn in inputs)
            {
                foreach (Connection inputConnection in ssn.InputList)
                {
                    if (!nodeToCodeUIDs.Contains(inputConnection.OtherNode))
                        inputNodeInputConnections.Add(inputConnection);
                }
                foreach (Connection outputConnection in ssn.OutputList)
                {
                    if (!nodeToCodeUIDs.Contains(outputConnection.OtherNode))
                        inputNodeOutputConnections.Add(outputConnection);
                }
            }

            newGC.ReplaceNodesFromAList(nodesToBeReplaced);
            newSyncData.AddedNodes = new List<SnapshotNode>();
            newSyncData.ModifiedNodes = new List<SnapshotNode>();
            newSyncData.RemovedNodes = new List<uint>();
            GB = new GraphBuilder(newSyncData, newGC);
            //string result = GB.BuildGraphDAG();
            List<SnapshotNode> nodeToCodeBlocks = GB.PrintCodeForSelectedNodes(originalGC, inputs);

            /*for now, only connected nodes are supported: return all connections that are not internal connections (connections between the selected nodes)*/
            //uint id = 0;
            //foreach (string content in toCode)
            //{
            //    SnapshotNode ssn = new SnapshotNode();
            //    ssn.Type = SnapshotNodeType.CodeBlock;
            //    ssn.Content = content;
            //    ssn.Id = id++;
            //    ssn.InputList = new List<Connection>();
            //    //stupid stub
            //    foreach (Connection inputConnection in inputNodeInputConnections)
            //    {
            //        Connection newInputConnection = new Connection();
            //        newInputConnection.OtherNode = inputConnection.OtherNode;
            //        newInputConnection.OtherIndex = inputConnection.OtherIndex;
            //        newInputConnection.IsImplicit = inputConnection.IsImplicit;
            //        string[] tokens = newGC.Graph.GetNode(inputConnection.OtherNode).Name.Split('=');
            //        newInputConnection.LocalName = tokens[0];
            //        ssn.InputList.Add(newInputConnection);
            //    }
            //    //ssn.InputList = inputNodeInputConnections;
            //    ssn.OutputList = new List<Connection>();
            //    foreach (Connection outputConnection in inputNodeOutputConnections)
            //    {
            //        Connection newOutputConnection = new Connection();
            //        newOutputConnection.OtherNode = outputConnection.OtherNode;
            //        newOutputConnection.OtherIndex = outputConnection.OtherIndex;
            //        newOutputConnection.IsImplicit = outputConnection.IsImplicit;
            //        //string[] tokens = originalGC.Graph.GetNode(outputConnection.OtherNode).Name.Split('=');
            //        newOutputConnection.LocalName = outputConnection.LocalName;
            //        ssn.OutputList.Add(newOutputConnection);
            //    }
            //    //ssn.OutputList = inputNodeOutputConnections;
            //    codeBlocks.Add(ssn);
            //}

            /*update the original GC*/
            foreach (SnapshotNode inputNode in inputs)
            {
                if (originalNodeUIDList.Contains(inputNode.Id))
                    originalGC.RemoveNodes(inputNode.Id, false);
                else
                {
                    foreach (KeyValuePair<uint, Dictionary<int, uint>> kvp in originalGC.codeBlockUIDMap)
                    {
                        if (kvp.Value.ContainsValue(inputNode.Id))
                        {
                            originalGC.RemoveNodes(kvp.Key, false);
                        }
                    }
                }
            }
            foreach (Node node in newGC.Graph.nodeList)
            {
                node.Name = node.Name.TrimEnd(';') + ";";
            }
            originalGC.Graph.nodeList.Union<Node>(newGC.Graph.nodeList);
            //originalGC = newGC;
            /**/

            return nodeToCodeBlocks;
            //return codeBlocks;
        }

        /// <summary>
        /// This is called to Parse individual assignment statements in Codeblock nodes in GraphUI
        /// and return the resulting ProtoAST node
        /// </summary>
        /// <param name="statement"></param>
        public static ProtoCore.AST.Node Parse(string statement, out ProtoCore.AST.AssociativeAST.CodeBlockNode commentNode)
        {
            commentNode = null;
            BuildCompileState(true);

            Validity.Assert(compileState != null);
            Validity.Assert(statement != null);

            if (string.IsNullOrEmpty(statement))
                return null;

            System.IO.MemoryStream memstream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(statement));
            ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(memstream);
            ProtoCore.DesignScriptParser.Parser p = new ProtoCore.DesignScriptParser.Parser(s, compileState);

            p.Parse();
            commentNode = p.commentNode;

            return p.root;
        }

        public static List<ProtoCore.AST.Node> ParseCodeBlock(string code)
        {
            Validity.Assert(code != null);

            if (string.IsNullOrEmpty(code))
                return null;

            // TODO: Change the logic to ignore Import statements in this case using parser - pratapa
            // Check if this will work with modifier blocks as well
            /*string[] stmts = code.Split(';');
            string source = "";
            for (int i=0; i < stmts.Length; ++i)
            {
                if (!stmts[i].Contains("import"))
                    source += stmts[i] + ";";
            }*/

            ProtoLanguage.CompileOptions options = new ProtoLanguage.CompileOptions();
            ProtoLanguage.CompileStateTracker compileState = new ProtoLanguage.CompileStateTracker(options);

            //compileState.Executives.Add(ProtoCore.Language.kAssociative, new ProtoAssociative.Executive(compileState));
            //compileState.Executives.Add(ProtoCore.Language.kImperative, new ProtoImperative.Executive(compileState));

            System.IO.MemoryStream memstream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(code));
            ProtoCore.DesignScriptParser.Scanner s = new ProtoCore.DesignScriptParser.Scanner(memstream);
            ProtoCore.DesignScriptParser.Parser p = new ProtoCore.DesignScriptParser.Parser(s, compileState);

            p.Parse();
            ProtoCore.AST.AssociativeAST.CodeBlockNode cbn = p.root as ProtoCore.AST.AssociativeAST.CodeBlockNode;

            Validity.Assert(cbn != null);
            return p.GetParsedASTList(cbn);
        }
Example #9
0
        /**/
        public List<uint> ConnectionToUID(List<Connection> input)
        {
            List<uint> result = new List<uint>();
            foreach (Connection inputConnection in input)
            {
                result.Add(inputConnection.OtherNode);
            }
            return result;
        }

        /*Tron: Use for node to code function
         *For each connected component of the graph, generate a respective string of code
         */
        public List<SnapshotNode> ToCode(AST graph, GraphCompiler originalGC, List<SnapshotNode> inputs)
        {
            List<SnapshotNode> result = new List<SnapshotNode>();

            List<Node> li = TopSort.sort(graph);
            tguid = 20000;
            List<string> listIslands = new List<string>();
            List<Node> islandNodes = new List<Node>();
            int countIslands = 0;
            statementList = new AST();
            ModifiedStmtGuidList.Clear();
            List<string> importIslands = new List<string>();
            IEnumerable iter = li;
            List<Node> islandNodeList = new List<Node>();
            //List<List<Node>> listing = new List<List<Node>>();
            List<Node> listing = new List<Node>();
            foreach (Node node in iter)
            {
                if (node != null)
                {
                    if (node is ImportNode)
                    {
                        importIslands.Add(node.ToScript() + ProtoCore.DSASM.Constants.termline);
                    }
                    else if (node.IsIsland)
                    {
                        countIslands++;
                        if (node is ArrayNode)
                        {
                            BuildArrayNodeStatement(node, statementList);
                            if (!islandNodes.Contains(node))
                                islandNodes.Add(node);
                            string island = statementList.GetNode(node.Guid).ToScript() + ProtoCore.DSASM.Constants.termline;
                            if (!listIslands.Contains(island))
                                listIslands.Add(island);
                        }
                        else if (node is LiteralNode)
                        {
                            BuildLiteralNodeStatement(node, statementList);
                            string island = statementList.GetNode(node.Guid).ToScript() + ProtoCore.DSASM.Constants.termline;
                            if (!listIslands.Contains(island))
                                listIslands.Add(island);
                        }
                        else if (node is Func)
                        {
                            BuildFunctionCallStatement(node, statementList);
                            string island = statementList.GetNode(node.Guid).ToScript() + ProtoCore.DSASM.Constants.termline;
                            if (!listIslands.Contains(island))
                                listIslands.Add(island);
                        }
                        else if (node is Operator)
                        {
                            BuildOperatorStatement(node, statementList);
                            string island = statementList.GetNode(node.Guid).ToScript() + ProtoCore.DSASM.Constants.termline;
                            if (!listIslands.Contains(island))
                                listIslands.Add(island);
                        }
                        else if (node is Block)
                        {
                            BuildBlockStatement(node, statementList);
                            islandNodes.Add(node);
                            //string island = statementList.GetNode(node.Guid).ToScript() + ProtoCore.DSASM.Constants.termline;
                            //if (!listIslands.Contains(island))
                              //  listIslands.Add(island);
                        }
                        else if (node is IdentNode)
                        {
                            // comment Jun:
                            // An island identifier node is handled by emitting a null as its rhs
                            statementList.AddNode(node);
                            string contents = statementList.GetNode(node.Guid).ToScript() + "=" + ProtoCore.DSASM.Literal.Null + ProtoCore.DSASM.Constants.termline;
                            listIslands.Add(contents);
                        }
                        else
                        {
                            statementList.AddNode(node);
                            string island = node.ToScript() + ProtoCore.DSASM.Constants.termline;
                            if (!listIslands.Contains(island))
                                listIslands.Add(island);
                        }
                        islandNodeList.Add(node);
                        listing = listing.ToList().Union<Node>(BuildStatement(node, statementList)).ToList();
                        HandleNewNode(node);
                    }
                    else if (node.IsLeaf)
                    {
                        if (node is ArrayNode)
                        {
                            BuildArrayNodeStatement(node, statementList);
                        }
                        else if (node is LiteralNode)
                        {
                            BuildLiteralNodeStatement(node, statementList);
                        }
                        else if (node is Func)
                        {
                            BuildFunctionCallStatement(node, statementList);
                        }
                        else if (node is Operator)
                        {
                            BuildOperatorStatement(node, statementList);
                        }
                        else if (node is Block)
                        {
                            BuildBlockStatement(node, statementList);
                        }
                        else if (node is IdentNode)
                        {
                            statementList.AddNode(node);
                            string contents = statementList.GetNode(node.Guid).ToScript() + "=" + ProtoCore.DSASM.Literal.Null + ProtoCore.DSASM.Constants.termline;
                            listIslands.Add(contents);
                        }
                        HandleNewNode(node);
                    }
                    else if (node.IsRoot && !node.IsIsland)
                    {
                        if (node is Operator)
                        {
                            BuildOperatorStatement(node, statementList);
                        }
                        else if (node is Func)
                        {
                            BuildFunctionCallStatement(node, statementList);
                        }
                        else if (node is Block)
                        {
                            BuildBlockStatement(node, statementList);
                        }
                        //liststat = BuildStatement(node, statementList);
                        //finalScript=finalScript.Union(BuildStatement(node, statementList)).ToList();
                        
                        //comment out for NodeToCode function
                        //listing.Add(BuildStatement(node, statementList));
                        listing = BuildStatement(node, statementList);
                        HandleNewNode(node);
                    }
                    else if (node is Operator)
                    {
                        BuildOperatorStatement(node, statementList);
                        HandleNewNode(node);
                    }
                    else if (node is Func)
                    {
                        BuildFunctionCallStatement(node, statementList);
                        HandleNewNode(node);
                    }
                    else if (node is ArrayNode)
                    {
                        BuildArrayNodeStatement(node, statementList);
                        HandleNewNode(node);
                    }
                    else if (node is LiteralNode)
                    {
                        BuildLiteralNodeStatement(node, statementList);
                        HandleNewNode(node);
                    }
                    else if (node is Block)
                    {
                        BuildBlockStatement(node, statementList);
                        listing = BuildStatement(node, statementList);
                        HandleNewNode(node);
                    }
                }
            }
            StringBuilder builder = new StringBuilder();
            foreach (string island in importIslands)// Loop through all strings
            {
                builder.Append(island);             // Append string to StringBuilder
            }
            foreach (string island in listIslands)  // Loop through all strings
            {
                builder.Append(island);             // Append string to StringBuilder
            }

            /*N2C*/
            #region get connected components of the graph
            List<Node> nodeToCodeInputList = new List<Node>();
            List<List<Node>> listingAlternate = new List<List<Node>>();
            List<List<Node>> listingAlt2 = new List<List<Node>>();
            if (nodeToCodeUIDs.Count != 0)
            {
                foreach (uint nodeID in nodeToCodeUIDs)
                {
                    if (graph.GetNode(nodeID) != null)
                    {
                        nodeToCodeInputList.Add(graph.GetNode(nodeID));
                    }
                    else
                    {
                        if (this.codeBlockUIDMap[nodeID] != null)
                        {
                            foreach (KeyValuePair<int, uint> pair in this.codeBlockUIDMap[nodeID])
                            {
                                nodeToCodeInputList.Add(graph.GetNode(pair.Value));
                            }
                        }
                    }
                }
                //listingAlternate = GetConnectedComponents(nodeToCodeInputList, graph);
                listingAlt2 = GetConnectedComponents_02(nodeToCodeInputList, graph);
            }
            #endregion

            //foreach (List<Node> n1 in listing)
            //{
            //    foreach (Node n2 in n1)
            //        if (!finalScript.Contains(n2))
            //            finalScript.Add(n2);
            //        else
            //        {
            //            finalScript.Remove(n2);
            //            finalScript.Add(n2);
            //        }
            //}
            listing = SortCodeBlocks(listing);
            List<List<Node>> finalList = new List<List<Node>>();
            foreach (List<Node> l1 in listingAlt2)
            {
                List<Node> temp = new List<Node>();
                foreach (Node n1 in l1)
                    foreach (Node listingNode in listing)
                        if (listingNode.Guid == n1.Guid)
                            temp.Add(listingNode);
                if (temp.Count != 0)
                    finalList.Add(temp);
            }            
            islandNodeList = islandNodeList.Union(islandNodes).ToList();
            //islandNodeList = SortCodeBlocks(islandNodeList);
            //if (islandNodeList.Count != 0)
            //    finalList.Add(islandNodeList);

            #region generate code and snapshot node
            uint id = 0;
            foreach (List<Node> nodeList in finalList)
            {
                string output = "";
                List<Node> tempList = SortCodeBlocks(nodeList);
                //tempList.Reverse();
                foreach (Node node in tempList)
                {
                    if (nodeToCodeUIDs.Contains(node.Guid))
                    {
                        if (node.ToCode() != null)
                            output += node.ToCode().Replace(";", "") + ProtoCore.DSASM.Constants.termline;
                    }
                    else
                    {
                        foreach (KeyValuePair<uint, Dictionary<int, uint>> pair in this.codeBlockUIDMap)
                        {
                            if (pair.Value.ContainsValue(node.Guid))
                            {
                                output += node.ToCode().Replace(";", "") + ProtoCore.DSASM.Constants.termline; //ensure only one semicolon at the end of a statement, by request from UI
                            }
                        }
                    }    
                }
                output = output.TrimEnd('\n');
                SnapshotNode ssn = new SnapshotNode();
                ssn.Id = id++;
                ssn.Content = output;
                ssn.Type = SnapshotNodeType.CodeBlock;
                ssn.InputList = new List<Connection>();

                foreach (SnapshotNode inputNode in inputs)
                {
                    foreach (Node subTreeNode in nodeList)
                    {
                        if (inputNode.Id == subTreeNode.Guid)
                        {
                            foreach (Connection c1 in inputNode.InputList)
                            {
                                if (!IsInternalConnection(c1, this))                //the connection is not internal, return it back to UI
                                {
                                    Connection newInputConnection = new Connection();
                                    newInputConnection.OtherNode = c1.OtherNode;
                                    newInputConnection.OtherIndex = c1.OtherIndex;
                                    newInputConnection.IsImplicit = c1.IsImplicit;
                                    string[] tokens = graph.GetNode(c1.OtherNode).Name.Split('=');
                                    newInputConnection.LocalName = tokens[0];
                                    ssn.InputList.Add(newInputConnection);
                                }
                            }
                        }
                        else if (codeBlockUIDMap.ContainsKey(inputNode.Id))         //inputNode was split
                        {
                            if (codeBlockUIDMap[inputNode.Id].ContainsValue(subTreeNode.Guid))
                            {
                                foreach (Connection c1 in inputNode.InputList)
                                {
                                    if (!IsInternalConnection(c1, this))
                                    {
                                        int indexSlot = 0;
                                        foreach (KeyValuePair<int, uint> pair in codeBlockUIDMap[inputNode.Id])
                                        {
                                            if (pair.Value == subTreeNode.Guid)
                                                indexSlot = pair.Key;
                                        }
                                        if (c1.OtherIndex == indexSlot)
                                        {
                                            Connection newInputConnection = new Connection();
                                            newInputConnection.OtherNode = c1.OtherNode;
                                            newInputConnection.OtherIndex = c1.OtherIndex;
                                            foreach (KeyValuePair<uint, Dictionary<int, uint>> pair in originalGC.codeBlockUIDMap)
                                            {
                                                if (pair.Value.ContainsValue(c1.OtherNode))                     //this means if the other node was split, return the original Id that was sent to us by the UI
                                                {
                                                    newInputConnection.OtherNode = pair.Key;
                                                    newInputConnection.OtherIndex = pair.Value.First(x => x.Value == c1.OtherNode).Key;
                                                }
                                            }
                                            newInputConnection.IsImplicit = c1.IsImplicit;
                                            string[] tokens = graph.GetNode(c1.OtherNode).Name.Split('=');
                                            newInputConnection.LocalName = tokens[0];
                                            ssn.InputList.Add(newInputConnection);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                ssn.OutputList = new List<Connection>();
                foreach (SnapshotNode inputNode in inputs)
                {
                    foreach (Node subTreeNode in nodeList)
                    {
                        //if (subTreeNode.Name.Split('=')[0] == outputCnt.LocalName)
                        if (inputNode.Id == subTreeNode.Guid)
                        {
                            foreach (Connection c1 in inputNode.OutputList)
                            {
                                if (!IsInternalConnection(c1, this))
                                {
                                    Connection newOutputConnection = new Connection();
                                    newOutputConnection.OtherNode = c1.OtherNode;
                                    newOutputConnection.OtherIndex = c1.OtherIndex;
                                    newOutputConnection.IsImplicit = c1.IsImplicit;
                                    newOutputConnection.LocalName = c1.LocalName;
                                    ssn.OutputList.Add(newOutputConnection);
                                }
                            }
                        }

                        else if (codeBlockUIDMap.ContainsKey(inputNode.Id))         //inputNode was split
                        {
                            if (codeBlockUIDMap[inputNode.Id].ContainsValue(subTreeNode.Guid))
                            {
                                foreach (Connection c1 in inputNode.OutputList)
                                {
                                    if (!IsInternalConnection(c1, this))
                                    {
                                        int indexSlot = 0;
                                        foreach (KeyValuePair<int, uint> pair in codeBlockUIDMap[inputNode.Id])
                                        {
                                            if (pair.Value == subTreeNode.Guid)
                                            {
                                                indexSlot = pair.Key;
                                                break;
                                            }
                                        }
                                        if (c1.LocalIndex == indexSlot)
                                        {
                                            Connection newOutputConnection = new Connection();
                                            newOutputConnection.OtherNode = c1.OtherNode;
                                            newOutputConnection.OtherIndex = c1.OtherIndex;
                                            foreach (KeyValuePair<uint, Dictionary<int, uint>> pair in originalGC.codeBlockUIDMap)
                                            {
                                                if (pair.Value.ContainsValue(c1.OtherNode))                     //this means if the other node was split, return the original Id that was sent to us by the UI
                                                {
                                                    newOutputConnection.OtherNode = pair.Key;
                                                    newOutputConnection.OtherIndex = pair.Value.First(x => x.Value == c1.OtherNode).Key;
                                                }
                                            }
                                            newOutputConnection.IsImplicit = c1.IsImplicit;
                                            newOutputConnection.LocalName = c1.LocalName;
                                            ssn.OutputList.Add(newOutputConnection);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                result.Add(ssn);
            }
            #endregion

            #region remove _temp_xxx name
            //Dictionary<string, string> tempReplaceValue = new Dictionary<string, string>();
            //for (int i = 0; i < result.Count; i++)
            //{
            //    SnapshotNode ssn = result[i];
            //    string[] statements = ssn.Content.Split(';');
            //    for (int j = 0; j < statements.Length; j++)
            //    {
            //        string statement = statements[j];
            //        string lhsTempName = statement.Split('=')[0].Replace("\n", "").Trim();
            //        foreach (Node astNode in graph.nodeList)
            //        {
            //            if (astNode.Name.Split('=')[0].Trim() == lhsTempName && lhsTempName.StartsWith("_temp_"))
            //            {
            //                //this means in the ast there is some statement _temp_abc = something
            //                //which means the _temp_xxx is generated, not typed in by users
            //                tempReplaceValue.Add(lhsTempName, statement.Split('=')[1].Replace("\n", "").Trim());
            //            }
            //        }
            //    }
            //}
            //for (int i = 0; i < result.Count; i++)
            //{
            //    SnapshotNode ssn = result[i];
            //    foreach (KeyValuePair<string, string> pair in tempReplaceValue)
            //    {
            //        ssn.Content.Replace(pair.Key, pair.Value);
            //    }
            //}
            #endregion

            #region replace _temp_ name with more elegant name
            //int tempId = 0;
            //for (int i = 0; i < result.Count; i++)
            //{
            //    SnapshotNode ssn = result[i];
            //    string[] statements = ssn.Content.Split(';');
            //    for (int j = 0; j < statements.Length; j++)
            //    {
            //        string statement = statements[j];
            //        string lhsTempName = statement.Split('=')[0].Replace("\n", "").Trim();
            //        foreach (Node astNode in graph.nodeList)
            //        {
            //            if (astNode.Name.Split('=')[0].Trim() == lhsTempName && lhsTempName.StartsWith("_temp_"))
            //            {
            //                string newTempName = "temp_" + tempId++;
            //                for (int k = 0; k < result.Count; k++)
            //                {
            //                    result[k].Content = result[k].Content.Replace(lhsTempName, newTempName);
            //                }
            //            }
            //        }
            //        if (statement.Split('=').Length > 1)
            //        {
            //            string rhsTempName = statement.Split('=')[1].Replace("\n", "").Trim();
            //            foreach (Node astNode in graph.nodeList)
            //            {
            //                if (astNode.Name.Split('=')[0].Trim() == rhsTempName && rhsTempName.StartsWith("_temp_"))
            //                {
            //                    string newTempName = "temp_" + tempId++;
            //                    for (int k = 0; k < result.Count; k++)
            //                    {
            //                        result[k].Content = result[k].Content.Replace(rhsTempName, newTempName);
            //                    }
            //                }
            //            }
            //        }
            //    }
            //}
            #endregion

            #region return to original input connections
            for (int i = 0; i < result.Count; i++)
            {
                SnapshotNode ssn = result[i];
                for (int j = 0; j < ssn.InputList.Count; j++)
                {
                    Connection inputConnection = ssn.InputList[j];
                    foreach (KeyValuePair<uint, Dictionary<int, uint>> kvp in originalGC.codeBlockUIDMap)
                    {
                        foreach (KeyValuePair<int, uint> kvp2 in kvp.Value)
                        {
                            if (kvp2.Value == inputConnection.OtherNode)
                            {
                                Connection oldInputConnection = new Connection();
                                oldInputConnection.OtherNode = kvp.Key;
                                oldInputConnection.OtherIndex = inputConnection.OtherIndex;
                                oldInputConnection.IsImplicit = inputConnection.IsImplicit;
                                oldInputConnection.LocalName = inputConnection.LocalName;
                                oldInputConnection.LocalIndex = inputConnection.LocalIndex;
                                ssn.InputList.Remove(inputConnection);
                                ssn.InputList.Insert(j, oldInputConnection);
                            }
                        }
                    }
                }

                for (int j = 0; j < ssn.OutputList.Count; j++)
                {
                    Connection outputConnection = ssn.OutputList[j];
                    foreach (KeyValuePair<uint, Dictionary<int, uint>> kvp in originalGC.codeBlockUIDMap)
                    {
                        foreach (KeyValuePair<int, uint> kvp2 in kvp.Value)
                        {
                            if (kvp2.Value == outputConnection.OtherNode)
                            {
                                Connection oldInputConnection = new Connection();
                                oldInputConnection.OtherNode = kvp.Key;
                                oldInputConnection.OtherIndex = outputConnection.OtherIndex;
                                oldInputConnection.IsImplicit = outputConnection.IsImplicit;
                                oldInputConnection.LocalName = outputConnection.LocalName;
                                oldInputConnection.LocalIndex = outputConnection.LocalIndex;
                                ssn.OutputList.Remove(outputConnection);
                                ssn.OutputList.Insert(j, oldInputConnection);
                            }
                        }
                    }
                }
            }
            #endregion
            /*Chirag's
            foreach (var value in finalScript)
            {
                if (nodeToCodeUIDs.Contains((value as Node).Guid))
                    if (value.ToCode() != null)
                        liststat += value.ToCode() + ProtoCore.DSASM.Constants.termline;
            }
            liststat = builder.ToString() + liststat;
            //liststat += builder.ToString();
            //GraphUtilities.runningUID = GraphToDSCompiler.Constants.UIDStart;
            //result.AddRange(liststat.Split(';'));
            */
            UpdateAddedNodesInModifiedNameList();

            return result;
        }
Example #10
0
 private bool IsInternalConnection(Connection c1, GraphCompiler oriGC)
 {
     bool result = false;
     if (nodeToCodeUIDs.Contains(c1.OtherNode))
     {
         result = true;
     }  
     else
     {
         foreach (KeyValuePair<uint, Dictionary<int, uint>> kvp in oriGC.codeBlockUIDMap)
         {
             if (nodeToCodeUIDs.Contains(kvp.Key) && kvp.Value.ContainsValue(c1.OtherNode))
                 result = true;
         }
     }
     return result;
 }
        private void EstablishExplicitOutputConnection(VisualNode startNode, Connection connection, List<IVisualNode> modifiedNodes)
        {
            VisualNode endNode = nodeCollection[connection.OtherNode] as VisualNode;
            List<uint> startSlotIds = (startNode as VisualNode).GetSlotIdsByName(SlotType.Output, connection.LocalName);
            uint startSlotId = startSlotIds.Last();
            uint endSlotId = endNode.GetInputSlot(connection.OtherIndex);
            Slot outputSlot = GetSlot(startSlotId) as Slot;
            Slot inputSlot = GetSlot(endSlotId) as Slot;
            edgeController.CreateLinkingEdge(outputSlot, inputSlot);
            (startNode as VisualNode).HandleNewConnection(startSlotId);
            endNode.HandleNewConnection(endSlotId);

            modifiedNodes.Add(startNode);
            modifiedNodes.Add(endNode);
        }
        private void EstablishExplicitInputConnection(VisualNode endNode, Connection connection, List<IVisualNode> modifiedNodes)
        {
            VisualNode startNode = (VisualNode)nodeCollection[connection.OtherNode];
            uint startSlotId = startNode.GetOutputSlot(connection.OtherIndex);
            uint endSlotId = endNode.GetInputSlot(connection.LocalIndex);
            Slot outputSlot = GetSlot(startSlotId) as Slot;
            Slot inputSlot = GetSlot(endSlotId) as Slot;
            edgeController.CreateLinkingEdge(outputSlot, inputSlot);
            startNode.HandleNewConnection(startSlotId);
            endNode.HandleNewConnection(endSlotId);

            modifiedNodes.Add(startNode);
            modifiedNodes.Add(endNode);
        }
 private Connection CreateConnectionStructure(uint otherNodeId, int otherIndex, int localIndex, string localName, bool isImplicit)
 {
     Connection connection = new Connection();
     connection.IsImplicit = isImplicit;
     connection.LocalIndex = localIndex;
     connection.LocalName = localName;
     connection.OtherIndex = otherIndex;
     connection.OtherNode = otherNodeId;
     return connection;
 }