예제 #1
0
        /// Checks if the string in code block node is a literal or an identifier or has multiple lines of code.
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static SnapshotNodeType AnalyzeString(string code)
        {
            SnapshotNodeType type = SnapshotNodeType.None;

            if (!code.EndsWith(";"))
            {
                code += ";";
            }
            List <ProtoCore.AST.Node> n = new List <ProtoCore.AST.Node>();

            try
            {
                ProtoCore.Options options = new ProtoCore.Options();
                options.RootModulePathName = string.Empty;

                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));
                core.IsParsingPreloadedAssembly = false;
                core.IsParsingCodeBlockNode     = true;
                core.ParsingMode = ProtoCore.ParseMode.AllowNonAssignment;

                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 codeBlockNode = p.root as ProtoCore.AST.AssociativeAST.CodeBlockNode;
                n = p.GetParsedASTList(codeBlockNode);
            }
            catch (Exception)
            {
                //if syntax return SnapshotNodeType as None
                return(SnapshotNodeType.CodeBlock);
            }

            if (n.Count > 1 || n.Count == 0)
            {
                type = SnapshotNodeType.CodeBlock;
            }
            else if (n[0] is ProtoCore.AST.AssociativeAST.BinaryExpressionNode)
            {
                type = SnapshotNodeType.CodeBlock;
            }
            else if (n[0] is ProtoCore.AST.AssociativeAST.IdentifierNode)
            {
                type = SnapshotNodeType.Identifier;
            }
            else if (n[0] is ProtoCore.AST.AssociativeAST.IntNode || n[0] is ProtoCore.AST.AssociativeAST.DoubleNode || n[0] is ProtoCore.AST.AssociativeAST.StringNode || n[0] is ProtoCore.AST.AssociativeAST.FunctionCallNode || n[0] is ProtoCore.AST.AssociativeAST.RangeExprNode)
            {
                type = SnapshotNodeType.Literal;
            }
            else
            {
                type = SnapshotNodeType.CodeBlock;
            }
            return(type);
        }
예제 #2
0
        /// Checks if the string in code block node is a literal or an identifier or has multiple lines of code.
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static SnapshotNodeType AnalyzeString(string code)
        {
            SnapshotNodeType type = SnapshotNodeType.None;
            if (!code.EndsWith(";")) code += ";";
            List<ProtoCore.AST.Node> n = new List<ProtoCore.AST.Node>();

            try
            {
                ProtoCore.Options options = new ProtoCore.Options();
                options.RootModulePathName = string.Empty;

                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));
                core.IsParsingPreloadedAssembly = false;
                core.IsParsingCodeBlockNode = true;
                core.ParsingMode = ProtoCore.ParseMode.AllowNonAssignment;

                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 codeBlockNode = p.root as ProtoCore.AST.AssociativeAST.CodeBlockNode;
                n = p.GetParsedASTList(codeBlockNode);
            }
            catch (Exception)
            {
                //if syntax return SnapshotNodeType as None
                return SnapshotNodeType.CodeBlock;
            }

            if (n.Count > 1 || n.Count == 0)
                type = SnapshotNodeType.CodeBlock;
            else if (n[0] is ProtoCore.AST.AssociativeAST.BinaryExpressionNode)
                type = SnapshotNodeType.CodeBlock;
            else if (n[0] is ProtoCore.AST.AssociativeAST.IdentifierNode)
                type = SnapshotNodeType.Identifier;
            else if (n[0] is ProtoCore.AST.AssociativeAST.IntNode || n[0] is ProtoCore.AST.AssociativeAST.DoubleNode || n[0] is ProtoCore.AST.AssociativeAST.StringNode || n[0] is ProtoCore.AST.AssociativeAST.FunctionCallNode || n[0] is ProtoCore.AST.AssociativeAST.RangeExprNode)
                type = SnapshotNodeType.Literal;
            else type = SnapshotNodeType.CodeBlock;
            return type;
        }
예제 #3
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);
        }
예제 #4
0
        /// <summary>
        /// Checks if the string in code block node is a literal or an identifier or has multiple lines of code.
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static SnapshotNodeType AnalyzeString(string code)
        {
            SnapshotNodeType type = SnapshotNodeType.None;
            if (!code.EndsWith(";")) code += ";";
            List<ProtoCore.AST.Node> n = new List<ProtoCore.AST.Node>();
            try
            {
                BuildCore(true);
                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 codeBlockNode = p.root as ProtoCore.AST.AssociativeAST.CodeBlockNode;
                n = p.GetParsedASTList(codeBlockNode);
            }
            catch (Exception exception)
            {
                //if syntax return SnapshotNodeType as None
                return SnapshotNodeType.CodeBlock;
            }
            /*
             string LiteralPatternInt = @"^\s*-?\d+\s*$";
             string LiteralPatternDouble = @"^\d+([\.]\d+)?$";
             string LiteralPatternString = "^\"([^\"\\\\]|\\\\.)*\"$";
             string IdentifierPattern = @"^\s*[_a-zA-Z][_a-z0-9A-Z@]*\s*$";
             Match matchInt = Regex.Match(code, LiteralPatternInt);
             Match matchDouble = Regex.Match(code, LiteralPatternDouble);
             Match matchString = Regex.Match(code, LiteralPatternString);
             Match matchIdentifier = Regex.Match(code, IdentifierPattern);

            if (matchInt.Success || matchString.Success || matchDouble.Success)
                type = StringExpressionType.Literal;
            else if (matchIdentifier.Success)
                type = StringExpressionType.Identifier;
            else
                type = StringExpressionType.CodeBlock;*/
            if (n.Count > 1 || n.Count == 0)
                type = SnapshotNodeType.CodeBlock;
            else if (n[0] is ProtoCore.AST.AssociativeAST.BinaryExpressionNode)
                type = SnapshotNodeType.CodeBlock;
            else if (n[0] is ProtoCore.AST.AssociativeAST.IdentifierNode)
                type = SnapshotNodeType.Identifier;
            else if (n[0] is ProtoCore.AST.AssociativeAST.IntNode || n[0] is ProtoCore.AST.AssociativeAST.DoubleNode || n[0] is ProtoCore.AST.AssociativeAST.StringNode || n[0] is ProtoCore.AST.AssociativeAST.FunctionCallNode || n[0] is ProtoCore.AST.AssociativeAST.RangeExprNode)
                type = SnapshotNodeType.Literal;
            else type = SnapshotNodeType.CodeBlock;
            return type;
        }
예제 #5
0
        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);
        }
예제 #6
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(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);
        }
예제 #7
0
        /*
        proc RewriteCodeBlock(Node codeblock)
		
		    // Create new codeblocks for every line of code in the current codeblock CodeBlock[] newBlockList = new CodeBlock[node.lines.length]
            for n = 0 to node.lines.length
	            newBlockList[n].code = node.lines[n]
	            newBlockList[n].uid = generateUID(codeblock.uid)
            end
		
		    // At this point, determine which parents of the current codeblock node need to be connected to each splitted node

		    // Iterate through each parent of the current code block
		    foreach parentNode in codeblock.parents 

			    // Iterate through each child of the parent
			    for n = 0 to parentNode.children.length
			
				    // Check if the child is this codeblock
				    if parentNode.children[n] is equal to codeblock

                        // index ‘n’ is the current output slot of the codeblock		
                        newBlockList[n].parent.push(parentNode)

					    // Rewire the parent’s child to this new codeblock
					    parentNode.children[n] = newBlockList[n]

				    end
				    n++;
			    end
		    end			
        end

         */


        /*private List<Block> RewriteCodeBlock(Block codeblock)
        {
            Validity.Assert(codeblock != null);

            if (codeblock.Name == null || codeblock.Name.Length <= 0)
            {
                return null;
            }


            // Comment Jun: Im just trying to find the number of times ';' occurs
            // Make this more efficient by turning this into a function in a utils class
            string dummy = codeblock.Name.Replace(";", "");
            if ((codeblock.Name.Length - dummy.Length) <= 1)
            {
                // Single line codeblocks need not be split
                return null;
            }

            string[] token = new string[1];
            token[0] = ProtoCore.DSASM.Constants.termline;
            StringSplitOptions opt = new StringSplitOptions();
            string[] contents = codeblock.Name.Split(token, opt);
            int length = contents.Length;


            // The map of the new uid and its associated connecting slot
            Dictionary<int, uint> slotIndexToUIDMap = new Dictionary<int, uint>();

            // Create new codeblocks for every line of code in the current codeblock CodeBlock[] newBlockList = new CodeBlock[node.lines.length]
            List<Block> newBlockList = new List<Block>();
            for (int n = 0; n < length; n++)
            {
                // TODO Jun: Check with IDE why the semicolon is inconsitent
                string code = contents[n];
                if (code.Length > 0 && code[0] != ';')
                {
                    uint newGuid = GraphUtilities.GenerateUID();

                    List<AssignmentStatement> assignmentData = new List<AssignmentStatement>();
                    if (codeblock.assignmentData.Count > 0)
                    {
                        // This assignemnt data list must contain only 1 element
                        // This element is associated witht he current line in the codeblock
                        assignmentData.Add(codeblock.assignmentData[n]);
                    }
                    
                    Block newBlock = new Block(code, newGuid, assignmentData);
                    newBlock.splitFomUint = codeblock.Guid;
                    newBlockList.Add(newBlock);
                    slotIndexToUIDMap.Add(n, newGuid);
                }
            }

            // At this point, determine which parents of the current codeblock node need to be connected to each splitted node

            // Iterate through each parent of the current code block
            List<Node> parents = codeblock.GetParents();
            foreach (Node parentNode in parents)
            {
                // Iterate through each child of the parent
                for (int childIndex = 0; childIndex < parentNode.children.Count; childIndex++)
                {
                    Node child = null;
                    bool foundIndex = parentNode.children.TryGetValue(childIndex, out child);

                    if (foundIndex)
                    {
                        // Check if the child is this codeblock
                        if (child.Guid == codeblock.Guid)
                        {
                            int fromIndex = parentNode.childConnections[childIndex].from;

                            // Set the new codeblock's parent
                            newBlockList[fromIndex].AddParent(parentNode);

                            // Rewire the parent’s child to this new codeblock
                            parentNode.RemoveChild(childIndex);

                            parentNode.AddChild(newBlockList[fromIndex], childIndex, fromIndex);
                        }
                    }
                }
            }
            if (codeBlockUIDMap.ContainsKey(codeblock.Guid))
            {
                codeBlockUIDMap[codeblock.Guid] = slotIndexToUIDMap;
            }
            else
            {
                codeBlockUIDMap.Add(codeblock.Guid, slotIndexToUIDMap);
            }
            return newBlockList;
        }*/

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

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

            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);
        }