public void TestDeserialize1()
        {
            string code = "a=1;";
            Dictionary <int, List <VariableLine> > unboundIdentifiers = null;
            List <ProtoCore.AST.Node> astNodes = null;

            GraphUtilities.ParseCodeBlockNodeStatements(code, unboundIdentifiers, out astNodes);

            Ui.Statement statement = new Ui.Statement(astNodes[0]);

            IStorage storage = new BinaryStorage();

            statement.Serialize(storage);
            Ui.Statement newStatement = new Ui.Statement(storage);
            storage.Seek(0, SeekOrigin.Begin);
            newStatement.Deserialize(storage);

            VariableSlotInfo outputExpression = new VariableSlotInfo("a", 1, uint.MaxValue);

            Assert.AreEqual("a", statement.DefinedVariable);
            Assert.AreEqual(outputExpression, statement.OutputExpression);
            Assert.AreEqual(0, statement.References.Count);
            Assert.AreEqual(0, statement.Children.Count);
            Assert.AreEqual(false, statement.IsSwappable);
            Assert.AreEqual(false, statement.IsComplex);
        }
Beispiel #2
0
            public override void Execute()
            {
                NodesToCodeCompletedEventArgs args = null;
                List <ProtoCore.AST.AssociativeAST.AssociativeNode> astList = new List <ProtoCore.AST.AssociativeAST.AssociativeNode>();

                if (subtrees != null)
                {
                    foreach (var tree in subtrees)
                    {
                        Validity.Assert(tree.AstNodes != null && tree.AstNodes.Count > 0);
                        astList.AddRange(tree.AstNodes);
                    }
                }

                lock (runner.operationsMutex)
                {
                    try
                    {
                        string code = GraphUtilities.ASTListToCode(astList);
                        args = new NodesToCodeCompletedEventArgs(code, EventStatus.OK, "Node to code task complete.");
                    }
                    catch (Exception exception)
                    {
                        args = new NodesToCodeCompletedEventArgs(string.Empty, EventStatus.Error, exception.Message);
                    }
                }

                // Notify the listener
                if (null != runner.NodesToCodeCompleted)
                {
                    runner.NodesToCodeCompleted(this, args);
                }
            }
Beispiel #3
0
        internal override ErrorType ValidateInputString(out string error)
        {
            error = string.Empty;
            List <string>    errors = new List <string>();
            SnapshotNodeType type   = SnapshotNodeType.None;

            type = GraphUtilities.AnalyzeString(this.Text);
            if (type != SnapshotNodeType.Literal)
            {
                errors.Add("Invalid value.");
            }

            type = GraphUtilities.AnalyzeString(this.Caption);
            if (type != SnapshotNodeType.Identifier)
            {
                errors.Add("Invalid variable name.");
            }

            for (int i = 0; i < errors.Count; i++)
            {
                error += errors[i];
                if (i != errors.Count - 1)
                {
                    error += "\n";
                }
            }

            if (error == string.Empty)
            {
                return(ErrorType.None);
            }
            return(ErrorType.Syntax);
        }
Beispiel #4
0
        public IList <int> EventualSafeNodes(int[][] adjacencyMatrix)
        {
            // all nodes in a strongly connected component is unsafe
            // because they can get in a loop
            _graph = GraphUtilities.GetDiGraphFromAdjacencyMatrix(adjacencyMatrix);
            // for each node, we try to see if it can reach a cycle
            // a cycle is reached when during a DFS, a back edge is discovered
            foreach (var node in _graph.Nodes)
            {
                if (node.Color == Color.Uncolored)
                {
                    Visit(node);
                }
            }
            var safeList = new List <int>();

            foreach (var node in _graph.Nodes)
            {
                if (node.Color != Color.Black)
                {
                    safeList.Add(node.Label);
                }
            }
            safeList.Sort();
            return(safeList);
        }
Beispiel #5
0
        //https://leetcode.com/problems/network-delay-time/
        public int NetworkDelayTime(int[][] times, int N, int K)
        {
            var diGraph           = GraphUtilities.GetDiGraphFromWeightedEdges(times, N);
            var shortestDistances = Dijkstras <int> .GetShortestDistancesFrom(diGraph, K - 1);

            var maxTime = shortestDistances.Values.Max();

            return(maxTime == int.MaxValue? -1: maxTime);
        }
Beispiel #6
0
        public static void GraphHasCorrectNumberOfTreeEdges <K, T>(int expectedEdges, List <GraphVertex <K, T> > graph)
            where K : IUnfoldableEdge
            where T : IUnfoldablePlanarFace <K>
        {
            var alledges = GraphUtilities.GetAllTreeEdges(graph);

            Assert.AreEqual(expectedEdges, alledges.Count);
            Console.WriteLine("correct number of edges");
        }
        /// <summary>
        /// actually construct list of graph verts with stored faces and edges
        /// iterates dictionary of edges to faces and building graph
        /// </summary>
        /// <param name="faces"></param>
        /// <param name="edgeDict"></param>
        /// <returns></returns>
        public static List <GraphVertex <K, T> > GenGraph <T, K>(List <T> facelikes, Dictionary <K, List <T> > edgeDict)
            where K : IUnfoldableEdge
            where T : IUnfoldablePlanarFace <K>
        {
            List <GraphVertex <K, T> > graph = new List <GraphVertex <K, T> >();

            // first build the graph nodes, just referencing faces
            foreach (T face in facelikes)
            {
                var CurrentVertex = new GraphVertex <K, T>(face);
                graph.Add(CurrentVertex);
            }

            // then build edges, need to use edge dict to do this
            foreach (GraphVertex <K, T> vertex in graph)
            {
                T facelike = vertex.Face;
                foreach (K edgelike in facelike.EdgeLikeEntities)
                {
                    //var edgekey = new EdgeLikeEntity(edge);
                    // again we dont need to generate a new key with this wrapper - already stored on the face in this form

                    var edgekey = edgelike;

                    // find adjacent faces in the dict
                    var subfaces = edgeDict[edgekey];
                    // find the graph verts that represent these faces
                    var verts = GraphUtilities.FindNodesByMatchingFaces(graph, subfaces);
                    //remove dupe faces, not sure if these should really be removed
                    verts = verts.Distinct().ToList();
                    //need to remove self loops
                    //build list of toremove, then remove them
                    var toremove = new List <GraphVertex <K, T> >();
                    foreach (GraphVertex <K, T> testvert in verts)
                    {
                        if (testvert == vertex)
                        {
                            toremove.Add(testvert);
                        }
                    }
                    verts = verts.Except(toremove).ToList();


                    // these are the verts this edge connects
                    foreach (var VertToConnectTo in verts)
                    {
                        K   wrappedEdgeOnThisGraphEdge = GraphUtilities.FindRealEdgeByTwoFaces <T, K>(graph, subfaces, edgeDict);
                        var CurrentGraphEdge           = new GraphEdge <K, T>(wrappedEdgeOnThisGraphEdge, vertex, VertToConnectTo);
                        vertex.GraphEdges.Add(CurrentGraphEdge);
                    }
                }
            }
            return(graph);
        }
 private static async Task <HttpResponseMessage> Run(HttpRequest req, ILogger log, ExecutionContext ec, string version)
 {
     return(await SafeExecutor.Execute(async() =>
     {
         var cnfg = ConfigUtilities.LoadConfiguration();
         var graphRequestUrl = UrlUtilities.Combine(cnfg.GraphBaseUrl, req.Path, req.QueryString.ToString());
         var authProvider = FunctionUtilities.GetAuthenticationProvider(req, cnfg);
         var graphClient = GraphUtilities.GetAuthenticatedClient(cnfg.GraphBaseUrl, version, authProvider);
         var graphResponse = await GraphUtilities.ExecuteGetRequest(graphClient, graphRequestUrl);
         return await FunctionUtilities.TransformResponse(req.GetHostUrl(), cnfg.GraphBaseUrl, graphResponse);
     }, req, log));
 }
Beispiel #9
0
        // Token: 0x060028F0 RID: 10480 RVA: 0x001BE988 File Offset: 0x001BCB88
        private void AddGraphObstacles(Simulator sim, GridGraph grid)
        {
            bool reverse = Vector3.Dot(grid.transform.TransformVector(Vector3.up), (sim.movementPlane == MovementPlane.XY) ? Vector3.back : Vector3.up) > 0f;

            GraphUtilities.GetContours(grid, delegate(Vector3[] vertices)
            {
                if (reverse)
                {
                    Array.Reverse(vertices);
                }
                this.obstacles.Add(sim.AddObstacle(vertices, this.wallHeight, true));
            }, this.wallHeight * 0.4f, null);
        }
Beispiel #10
0
 // Token: 0x060028F1 RID: 10481 RVA: 0x001BEA04 File Offset: 0x001BCC04
 private void AddGraphObstacles(Simulator simulator, INavmesh navmesh)
 {
     GraphUtilities.GetContours(navmesh, delegate(List <Int3> vertices, bool cycle)
     {
         Vector3[] array = new Vector3[vertices.Count];
         for (int i = 0; i < array.Length; i++)
         {
             array[i] = (Vector3)vertices[i];
         }
         ListPool <Int3> .Release(vertices);
         this.obstacles.Add(simulator.AddObstacle(array, this.wallHeight, cycle));
     });
 }
Beispiel #11
0
 /// <summary>Adds obstacles for a navmesh/recast graph</summary>
 void AddGraphObstacles(Pathfinding.RVO.Simulator simulator, INavmesh navmesh)
 {
     GraphUtilities.GetContours(navmesh, (vertices, cycle) => {
         var verticesV3 = new Vector3[vertices.Count];
         for (int i = 0; i < verticesV3.Length; i++)
         {
             verticesV3[i] = (Vector3)vertices[i];
         }
         // Pool the 'vertices' list to reduce allocations
         ListPool <Int3> .Release(vertices);
         obstacles.Add(simulator.AddObstacle(verticesV3, wallHeight, cycle));
     });
 }
Beispiel #12
0
        internal override string ToCode(out SnapshotNodeType type)
        {
            string replicationGuideString = string.Empty;
            int    i = 0;

            foreach (uint slot in inputSlots)
            {
                List <int> tmp = new List <int>();
                int        j   = 0;

                foreach (int value in replicationGuides[i])
                {
                    tmp.Add(value);
                    j++;
                }
                replicationGuideString += SnapshotNode.CreateReplicationGuideText(tmp);

                // The delimiter for a group of replication guides is'%'
                // Put all these characters in a definition structure or file
                replicationGuideString += GraphToDSCompiler.Constants.ReplicationGuideDelimiter;
                i++;
            }
            string assemblyPath = graphController.MapAssemblyPath(this.Assembly);

            // only external library need to convert the assembly path
            if (this.Assembly != assemblyPath)
            {
                assemblyPath = GraphUtilities.ConvertAbsoluteToRelative(assemblyPath);
            }

            if (this.MemberType == LibraryItem.MemberType.InstanceMethod || this.MemberType == LibraryItem.MemberType.InstanceProperty)
            {
                type = SnapshotNodeType.Method;
                string tempArgumentTypes = this.ArgumentTypes;
                // there is additional slot[0] with name "this" and type "this"
                // the "this" type need to be converted to proper class name(first part of the qualifiedName)
                //
                if (this.QualifiedName.Contains('.'))
                {
                    string className = this.QualifiedName.Substring(0, this.QualifiedName.IndexOf('.'));
                    tempArgumentTypes = tempArgumentTypes.Replace("this", className);
                }

                return(string.Format("{0};{1};{2};{3};{4}", assemblyPath, this.Caption, tempArgumentTypes, this.Text, replicationGuideString));
            }
            else
            {
                type = SnapshotNodeType.Function;
                return(string.Format("{0};{1};{2};{3};{4}", assemblyPath, this.QualifiedName, this.ArgumentTypes, this.Text, replicationGuideString));
            }
        }
Beispiel #13
0
        internal override ErrorType ValidateInputString(out string error)
        {
            error = string.Empty;
            SnapshotNodeType type = GraphUtilities.AnalyzeString(this.Text);

            if (type == SnapshotNodeType.Identifier)
            {
                return(ErrorType.None);
            }
            else
            {
                error = "Invalid variable name.";
                return(ErrorType.Syntax);
            }
        }
Beispiel #14
0
        /// <summary>Adds obstacles for a grid graph</summary>
        void AddGraphObstacles(Pathfinding.RVO.Simulator sim, GridGraph grid)
        {
            bool reverse = Vector3.Dot(grid.transform.TransformVector(Vector3.up), sim.movementPlane == MovementPlane.XY ? Vector3.back : Vector3.up) > 0;

            GraphUtilities.GetContours(grid, vertices => {
                // Check if the contour is traced in the wrong direction from the one we want it in.
                // If we did not do this then instead of the obstacles keeping the agents OUT of the walls
                // they would keep them INSIDE the walls.
                if (reverse)
                {
                    System.Array.Reverse(vertices);
                }
                obstacles.Add(sim.AddObstacle(vertices, wallHeight, true));
            }, wallHeight * 0.4f);
        }
        private void OnGraphSaved(object sender, EventArgs e)
        {
            if (null == this.runner) // Running in headless mode.
            {
                return;
            }
            GraphController controller = sender as GraphController;

            if (null != controller)
            {
                LiveRunner liveRunner = runner as LiveRunner;
                //Update the options with new path.
                liveRunner.SetOptions(LiveRunnerFactory.CreateLiveRunnerOptions(controller));
                GraphUtilities.SetRootModulePath(controller.FilePath);
            }
        }
 private void CreateImportNodeIfRequired(string library, string hashKey = null)
 {
     if (null == hashKey)
     {
         string libraryPath = string.Empty;
         if (GraphUtilities.TryGetImportLibraryPath(library, out libraryPath, out hashKey))
         {
             library = libraryPath;
         }
     }
     if (!importNodesMapping.ContainsKey(hashKey))
     {
         importNodesMapping.Add(hashKey, GraphUtilities.GenerateUID());
     }
     gc.CreateImportNode(importNodesMapping[hashKey], library);
 }
        public void TestConstructor3()
        {
            string code = "a[1][2] = 1;";
            Dictionary <int, List <VariableLine> > unboundIdentifiers = null;
            List <ProtoCore.AST.Node> astNodes = null;

            GraphUtilities.ParseCodeBlockNodeStatements(code, unboundIdentifiers, out astNodes);

            Ui.Statement statement = new Ui.Statement(astNodes[0]);

            VariableSlotInfo outputExpression = new VariableSlotInfo("a[1][2].x[2].p", 1, uint.MaxValue);

            Assert.AreEqual("a", statement.DefinedVariable);
            Assert.AreEqual(outputExpression, statement.OutputExpression);
            Assert.AreEqual(0, statement.References.Count);
            Assert.AreEqual(0, statement.Children.Count);
            Assert.AreEqual(false, statement.IsSwappable);
            Assert.AreEqual(false, statement.IsComplex);
        }
Beispiel #18
0
        private void InitRunner(Options options)
        {
            graphCompiler = GraphToDSCompiler.GraphCompiler.CreateInstance();
            graphCompiler.SetCore(GraphUtilities.GetCore());
            runner = new ProtoScriptTestRunner();

            executionOptions = options;
            InitOptions();
            InitCore();


            taskQueue = new Queue <Task>();

            workerThread = new Thread(new ThreadStart(TaskExecMethod));
            workerThread.IsBackground = true;
            workerThread.Start();

            staticContext = new ProtoCore.CompileTime.Context();
        }
Beispiel #19
0
        internal override string ToCode(out GraphToDSCompiler.SnapshotNodeType type)
        {
            string assemblyPath = graphController.MapAssemblyPath(this.Assembly);

            // only external library need to convert the assembly path
            if (this.Assembly != assemblyPath)
            {
                assemblyPath = GraphUtilities.ConvertAbsoluteToRelative(assemblyPath);
            }

            type = GraphToDSCompiler.SnapshotNodeType.Property;
            if (this.MemberType == LibraryItem.MemberType.InstanceProperty)
            {
                return(string.Format("{0};{1};{2}", assemblyPath, this.Caption, this.Text));
            }
            else  //this.MemberType == LibraryItem.MemberType.StaticProperty
            {
                return(string.Format("{0};{1};{2}", assemblyPath, this.QualifiedName, this.Text));
            }
        }
        internal override ErrorType ValidateInputString(out string error)
        {
            if (!this.graphController.FileLoadInProgress && !this.graphController.IsInUndoRedoCommand)
            {
                this.UpdateInternalData(false);
            }

            error = string.Empty;
            SnapshotNodeType type = GraphUtilities.AnalyzeString(this.Caption);

            if (type == SnapshotNodeType.Identifier)
            {
                return(ErrorType.None);
            }
            else
            {
                error = "Invalid variable name.";
                return(ErrorType.Syntax);
            }
        }
        public void RouteBetweenNodesTest()
        {
            int n = 10;

            Func <bool[, ], int, int, bool>[] functions = new Func <bool[, ], int, int, bool>[]
            {
                RouteBetweenNodes.BFS,
                RouteBetweenNodes.DFS
            };

            for (int i = 0; i < 10; i++)
            {
                bool[,] graph = new bool[n, n];

                for (int j = 0; j < n * n; j++)
                {
                    GraphUtilities.SetRandomEdge(graph, n);
                    Tests.TestFunctions(graph, 0, n - 1, functions);
                }
            }
        }
        public void DepthFirstSearchTest()
        {
            Func <Vertex[], int, bool[]>[] functions = new Func <Vertex[], int, bool[]>[]
            {
                DepthFirstSearchTestClass.RunDepthFirstSearch,
                DepthFirstSearchTestClass.RunBreadthFirstSearch,
                DepthFirstSearchTestClass.RunBellmanFord,
                DepthFirstSearchTestClass.RunDjikstra,
                DepthFirstSearchTestClass.RunFloydWarshall,
            };

            Vertex[] vertices = new Vertex[10];
            for (int i = 0; i < vertices.Length; i++)
            {
                vertices[i] = new Vertex();
            }

            for (int i = 0; i <= vertices.Length * (vertices.Length - 1); i++)
            {
                for (int j = 0; j < vertices.Length; j++)
                {
                    bool[][] results = new bool[vertices.Length][];

                    for (int k = 0; k < functions.Length; k++)
                    {
                        foreach (Vertex vertex in vertices)
                        {
                            vertex.Reset();
                        }

                        results[k] = functions[k](vertices, j);
                        Assert.IsTrue(ArrayUtilities.AreEqual(results[0], results[k]));
                    }
                }

                GraphUtilities.SetRandomEdge(vertices);
            }
        }
Beispiel #23
0
        public void ShortestPathTest()
        {
            Func <Vertex[], int[, ]>[] functions = new Func <Vertex[], int[, ]>[]
            {
                ShortestPathTestClass.RunBellmanFord,
                ShortestPathTestClass.RunDjikstra,
                ShortestPathTestClass.RunFloydWarshall,
            };

            Vertex[] vertices = new Vertex[10];
            for (int i = 0; i < vertices.Length; i++)
            {
                vertices[i] = new Vertex();
            }

            for (int i = 0; i <= vertices.Length * (vertices.Length - 1); i++)
            {
                for (int j = 0; j < vertices.Length; j++)
                {
                    int[][,] results = new int[vertices.Length][, ];

                    for (int k = 0; k < functions.Length; k++)
                    {
                        foreach (Vertex vertex in vertices)
                        {
                            vertex.Reset();
                        }

                        results[k] = functions[k](vertices);
                        Assert.IsTrue(ArrayUtilities.AreEqual(results[0], results[k]));
                    }
                }

                GraphUtilities.SetRandomEdge(vertices);
            }
        }
        // Method to remove this graphvertex from graph and to remove all edges which point to it
        // from other nodes in the graphT
        public void RemoveFromGraph(List <GraphVertex <K, T> > graph)
        {
            //collect all edges
            var allGraphEdges = GraphUtilities.GetAllGraphEdges(graph);
            var edgesToRemove = new List <GraphEdge <K, T> >();

            // mark all edges we need to remove
            foreach (var edge in allGraphEdges)
            {
                if (edge.Head == this)
                {
                    edgesToRemove.Add(edge);
                }
            }
            // iterate the graph again, if during traversal we see
            // a marked edge, remove it

            foreach (var vertex in graph)
            {
                vertex.GraphEdges.ExceptWith(edgesToRemove);
            }
            //finally remove the node
            graph.Remove(this);
        }
Beispiel #25
0
        //
        // TODO Jun: Re-evaluate the topsort implementation
        //
        static void DFSVisit(Node node, Dictionary <Node, int> nodeStateMap, List <Node> list, AST statementList)
        {
            nodeStateMap.Add(node, VISITING);
            List <Node>            nodes   = node.GetChildren();
            Dictionary <int, Node> nodeDic = node.GetChildrenWithIndices();
            IEnumerable            iter    = nodes;
            int j = 0;

            foreach (Node nodeI in iter)
            {
                if (node is IdentNode && nodeI is LiteralNode)
                {
                    BuildIdentToLiteralStatement(node, nodeI, statementList);
                }
                else if (node is IdentNode && nodeI is IdentNode)
                {
                    BuildIdentToIdentStatement(node, nodeI, statementList);
                }
                else if (node is IdentNode && nodeI is Block)
                {
                    Block blocknode = (Block)nodeI;
                    if (GraphUtilities.AnalyzeString(blocknode.Name) == SnapshotNodeType.Literal)
                    {
                        LiteralNode literal = new LiteralNode(blocknode.content, nodeI.Guid);
                        BuildIdentToLiteralStatement(node, literal, statementList);
                    }
                    else
                    {
                        j = BuildIdentToCodeBlockIdentStatement(node, nodeI, nodes, statementList, j);
                    }
                }
                else if (node is Operator && nodeI is Block)
                {
                    j = BuildOperatorToBlockStatement(node, nodeI, nodeDic, statementList, j);
                }
                else if (node is Func && nodeI is Block)
                {
                    j = BuildFuncToBlockStatement(node, nodeI, nodeDic, statementList, j);
                }
                else if (node is Func && nodeI is IdentNode)
                {
                    j = BuildFuncToIdentStatement(node, nodeI, nodeDic, statementList, j);
                }
                else if (node is IdentNode && nodeI is Operator)
                {
                    BuildIdentToOperatorStatement(node, statementList, nodeI);
                }
                else if (node is Operator && nodeI is Operator)
                {
                    j = BuildOperatorToOperatorStatement(node, nodeI, nodeDic, statementList, j);
                }
                else if (node is IdentNode && nodeI is Func)
                {
                    BuildIdentToFuncStatement(node, nodeI, statementList);
                }
                else if (node is Func && nodeI is Func)
                {
                    j = BuildFuncToFuncStatement(node, nodeI, nodeDic, statementList, j);
                }
                else if (node is Operator && nodeI is Func)
                {
                    j = BuildOperatorToOperatorStatement(node, nodeI, nodeDic, statementList, j);
                }
                else if (node is Func && nodeI is Operator)
                {
                    j = BuildFuncToFuncStatement(node, nodeI, nodeDic, statementList, j);
                }
                else if ((node is Operator && nodeI is ArrayNode) || (node is Operator && nodeI is LiteralNode))
                {
                    j = BuildOperatorToOperatorStatement(node, nodeI, nodeDic, statementList, j);
                }
                else if ((node is Func && nodeI is ArrayNode) || (node is Func && nodeI is LiteralNode))
                {
                    j = BuildFuncToFuncStatement(node, nodeI, nodeDic, statementList, j);
                }
                else if ((node is Block && nodeI is Block))
                {
                    BuildBlockToBlockStatement(node, nodeI, statementList);
                }
                else if ((node is Block && nodeI is Func))
                {
                    BuildBlockToFuncStatement(node, nodeI, statementList);
                }
                else if ((node is Block && nodeI is Operator))
                {
                    BuildBlockToFuncStatement(node, nodeI, statementList);
                }
                else if ((node is Block && nodeI is IdentNode))
                {
                    BuildBlockToIdentStatement(node, nodeI, statementList);
                }
                /*Block to Operator*/
                else if (node is Block && nodeI is Operator)
                {
                    //BuildBlockToOperatorStatement(node, nodeI, statementList);
                }
                //else if ((node is Block && nodeI is Func))
                //{
                //    BuildBlockToBlockStatement(node, nodeI, statementList);
                //}
                else
                {
                    if (node is Operator)
                    {
                        if (nodes.IndexOf(nodeI, j) == 0)
                        {
                            Assignment a = (Assignment)statementList.GetNode(node.Guid);
                            ((BinExprNode)a.right).left = nodeI;
                            ++j;
                        }
                        else
                        {
                            Assignment a = (Assignment)statementList.GetNode(node.Guid);
                            ((BinExprNode)a.right).right = nodeI;
                        }
                    }
                    else if (node is Func)
                    {
                        Assignment   a = (Assignment)statementList.GetNode(node.Guid);
                        FunctionCall f = ((FunctionCall)a.right);
                        f.parameters[nodes.IndexOf(nodeI, j)] = nodeI;
                        j = 0;
                    }
                }

                if (IsNotVisited(nodeI, nodeStateMap))
                {
                    DFSVisit(nodeI, nodeStateMap, list, statementList);
                }
            }
            nodeStateMap[node] = VISITED;
            list.Add(node);
        }
        /// <summary>
        /// Create BinaryExpressionNode
        /// </summary>
        /// <param name="node"></param>
        /// <param name="outnode"></param>
        private void EmitBlockNode(Block node, out AssociativeNode outnode)
        {
            Validity.Assert(node != null);

            // TODO: Confirm that these children are returned in the order that they
            // appear in the code
            Dictionary <int, Node> childNodes = node.GetChildrenWithIndices();

            // Parse program statement in node.Name
            string code = node.Name + ";";

            ProtoCore.AST.AssociativeAST.CodeBlockNode commentNode   = null;
            ProtoCore.AST.AssociativeAST.CodeBlockNode codeBlockNode = (ProtoCore.AST.AssociativeAST.CodeBlockNode)GraphUtilities.Parse(code, out commentNode);
            Validity.Assert(codeBlockNode != null);

            List <ProtoCore.AST.AssociativeAST.AssociativeNode> astList = codeBlockNode.Body;

            Validity.Assert(astList.Count == 1);

            if (astList[0] is ProtoCore.AST.AssociativeAST.IdentifierNode)
            {
                ProtoCore.AST.AssociativeAST.BinaryExpressionNode ben = new ProtoCore.AST.AssociativeAST.BinaryExpressionNode();
                ben.LeftNode = astList[0];
                ben.Optr     = ProtoCore.DSASM.Operator.assign;
                ProtoCore.AST.AssociativeAST.AssociativeNode statement = null;
                foreach (KeyValuePair <int, Node> kvp in childNodes)
                {
                    DFSTraverse(kvp.Value, out statement);
                }
                ben.RightNode = statement;
                astList[0]    = ben;
            }

            //I don't know what I am doing
            if (astList[0] is BinaryExpressionNode)
            {
                BinaryExpressionNode tempBen = astList[0] as BinaryExpressionNode;
                if (tempBen.LeftNode is IdentifierNode)
                {
                    IdentifierNode identitiferNode = tempBen.LeftNode as IdentifierNode;
                    if (identitiferNode.ArrayDimensions != null)
                    {
                        ArrayIndexerNode arrIndex = new ArrayIndexerNode();
                        arrIndex.ArrayDimensions = identitiferNode.ArrayDimensions;
                        arrIndex.Array           = identitiferNode;
                        tempBen.LeftNode         = arrIndex;
                    }
                }
                if (tempBen.RightNode is IdentifierNode)
                {
                    IdentifierNode identitiferNode = tempBen.RightNode as IdentifierNode;
                    if (identitiferNode.ArrayDimensions != null)
                    {
                        ArrayIndexerNode arrIndex = new ArrayIndexerNode();
                        arrIndex.ArrayDimensions = identitiferNode.ArrayDimensions;
                        arrIndex.Array           = identitiferNode;
                        tempBen.RightNode        = arrIndex;
                    }
                }
                astList[0] = tempBen;
            }
            //it should be correct, if not, debug?

            ProtoCore.AST.AssociativeAST.BinaryExpressionNode bNode = astList[0] as ProtoCore.AST.AssociativeAST.BinaryExpressionNode;
            Validity.Assert(bNode != null);
            bNode.Guid = node.Guid;
            //bNode.SplitFromUID = node.splitFomUint;

            // Child nodes are arguments to expression in bNode.RightNode.
            // Match child nodes with IdentifierNode's in bNode.RightNode - pratapa
            foreach (Node n in childNodes.Values)
            {
                AssociativeNode argNode = null;
                DFSTraverse(n, out argNode);

                // DFS traverse the bNode.RightNode and check for IdentifierNode's
                // and if their names match with the names of argNode, then replace
                // the IdentifierNode in bNode.RightNode with argNode
                BinaryExpressionNode ben = argNode as BinaryExpressionNode;
                Validity.Assert(ben != null);
                //ProtoCore.CodeGenDS codeGen = new ProtoCore.CodeGenDS(ben);
                AstCodeBlockTraverse sourceGen = new AstCodeBlockTraverse(ben);
                ProtoCore.AST.AssociativeAST.AssociativeNode right = bNode.RightNode;
                sourceGen.DFSTraverse(ref right);
                bNode.RightNode = right;
            }

            //(AstRootNode as CodeBlockNode).Body.Add(expressionNode);

            Validity.Assert(gc != null);
            gc.HandleNewNode(bNode);

            outnode = bNode;
        }
Beispiel #27
0
        internal void UpdateModifiedNodes()
        {
            IEnumerable         iter         = nodesToModify;
            List <uint>         nodesRemoved = new List <uint>();
            List <SnapshotNode> hasUndefinedVariableNodes = new List <SnapshotNode>();

            //Tron's
            #if TESTING_COMPARE
            List <List <string> > oldNodeContent = new List <List <string> >();
            foreach (SnapshotNode modifiedNode in nodesToModify)
            {
                List <string> checkEmptyContent = new List <string>();
                if (gc.codeBlockUIDMap.ContainsKey(modifiedNode.Id))
                {
                    foreach (KeyValuePair <int, uint> kvp in gc.codeBlockUIDMap[modifiedNode.Id])
                    {
                        if (gc.Graph.GetNode(kvp.Value) is Statement)
                        {
                            checkEmptyContent.Add(gc.Graph.GetNode(kvp.Value).Name);
                        }
                    }
                }
                else
                {
                    if (gc.Graph.GetNode(modifiedNode.Id) is Statement)
                    {
                        checkEmptyContent.Add(gc.Graph.GetNode(modifiedNode.Id).Name);
                    }
                }
                oldNodeContent.Add(checkEmptyContent);
            }
            #endif

            foreach (SnapshotNode node in iter)
            {
                if (node.Type == SnapshotNodeType.CodeBlock)
                {
                    // Get all guids associated with the main codeblocks' guid
                    Dictionary <int, uint> slotUIDMap = new Dictionary <int, uint>();
                    if (gc.codeBlockUIDMap.TryGetValue(node.Id, out slotUIDMap))
                    {
                        foreach (KeyValuePair <int, uint> slotUID in slotUIDMap)
                        {
                            nodesRemoved.Add(slotUID.Value);
                        }
                        gc.codeBlockUIDMap.Remove(node.Id);
                    }
                    else
                    {
                        nodesRemoved.Add(node.Id);
                    }
                }
                else
                {
                    nodesRemoved.Add(node.Id);
                }

                if (node.UndefinedVariables != null)
                {
                    hasUndefinedVariableNodes.Add(node);
                }
            }
            bool removeFromRemovedNodes = false;
            RemoveNodes(nodesRemoved, removeFromRemovedNodes);
            AddNodesToAST(nodesToModify);

            #if TESTING_COMPARE
            List <List <KeyValuePair <uint, string> > > newNodeContents = new List <List <KeyValuePair <uint, string> > >();
            foreach (SnapshotNode ssn in nodesToModify)
            {
                List <KeyValuePair <uint, string> > temp = new List <KeyValuePair <uint, string> >();
                if (gc.codeBlockUIDMap.ContainsKey(ssn.Id))
                {
                    foreach (KeyValuePair <int, uint> kvp in gc.codeBlockUIDMap[ssn.Id])
                    {
                        if (gc.Graph.GetNode(kvp.Value) is Statement)
                        {
                            temp.Add(new KeyValuePair <uint, string>(kvp.Value, gc.Graph.GetNode(kvp.Value).Name));
                        }
                    }
                }
                else
                {
                    if (gc.Graph.GetNode(ssn.Id) is Statement)
                    {
                        temp.Add(new KeyValuePair <uint, string>(ssn.Id, gc.Graph.GetNode(ssn.Id).Name));
                    }
                }
                newNodeContents.Add(temp);
            }

            bool proceed = true;
            for (int i = 0; i < newNodeContents.Count; i++)
            {
                if (newNodeContents[i].Count != oldNodeContent[i].Count)
                {
                    proceed = false;
                }
            }

            if (proceed)
            {
                for (int i = 0; i < newNodeContents.Count; i++)
                {
                    if (oldNodeContent[i].Count == 0)
                    {
                        continue;
                    }
                    for (int j = 0; j < newNodeContents[i].Count; j++)
                    {
                        if (!GraphUtilities.CompareCode(oldNodeContent[i][j], newNodeContents[i][j].Value))
                        {
                            Node modified = gc.Graph.GetNode(newNodeContents[i][j].Key);
                            if (modified is Statement)
                            {
                                (modified as Statement).wasModified = true;
                            }
                        }
                    }
                }
            }
            #endif
            MakeConnectionsForAddedNodes(nodesToModify);

            gc.ResetUndefinedVariables();
            foreach (var node in hasUndefinedVariableNodes)
            {
                // @keyu: undefined variables are those variables that were
                // defined in last run but were undefined in this run, so we
                // need to nullify these varaibles. Add them to graph
                // compiler's UndefinedNameList and later on graph compiler
                // will generate null assignment statements for them.
                gc.UndefineVariablesForNodes(node.UndefinedVariables, node.Id);
            }
        }
Beispiel #28
0
        private void ImportProcedure(string library, ProcedureNode proc)
        {
            string procName = proc.name;

            if (proc.isAutoGeneratedThisProc ||
                CoreUtils.IsSetter(procName) ||
                CoreUtils.IsDisposeMethod(procName) ||
                CoreUtils.StartsWithDoubleUnderscores(procName))
            {
                return;
            }

            int              classScope      = proc.classScope;
            string           className       = string.Empty;
            MethodAttributes methodAttribute = proc.MethodAttribute;
            ClassAttributes  classAttribute  = null;

            if (classScope != ProtoCore.DSASM.Constants.kGlobalScope)
            {
                var classNode = GraphUtilities.GetCore().ClassTable.ClassNodes[classScope];

                classAttribute = classNode.ClassAttributes;
                className      = classNode.name;
            }

            // MethodAttribute's HiddenInLibrary has higher priority than
            // ClassAttribute's HiddenInLibrary
            bool isVisible = true;

            if (methodAttribute != null)
            {
                isVisible = !methodAttribute.HiddenInLibrary;
            }
            else
            {
                if (classAttribute != null)
                {
                    isVisible = !classAttribute.HiddenInLibrary;
                }
            }

            FunctionType type;

            if (classScope == ProtoCore.DSASM.Constants.kGlobalScope)
            {
                type = FunctionType.GenericFunction;
            }
            else
            {
                if (CoreUtils.IsGetter(procName))
                {
                    type = proc.isStatic
                        ? FunctionType.StaticProperty
                        : FunctionType.InstanceProperty;

                    string property;
                    if (CoreUtils.TryGetPropertyName(procName, out property))
                    {
                        procName = property;
                    }
                }
                else
                {
                    if (proc.isConstructor)
                    {
                        type = FunctionType.Constructor;
                    }
                    else if (proc.isStatic)
                    {
                        type = FunctionType.StaticMethod;
                    }
                    else
                    {
                        type = FunctionType.InstanceMethod;
                    }
                }
            }

            IEnumerable <TypedParameter> arguments = proc.argInfoList.Zip(
                proc.argTypeList,
                (arg, argType) =>
            {
                object defaultValue = null;
                if (arg.IsDefault)
                {
                    var binaryExpr = arg.DefaultExpression as BinaryExpressionNode;
                    if (binaryExpr != null)
                    {
                        AssociativeNode vnode = binaryExpr.RightNode;
                        if (vnode is IntNode)
                        {
                            defaultValue = (vnode as IntNode).Value;
                        }
                        else if (vnode is DoubleNode)
                        {
                            defaultValue = (vnode as DoubleNode).Value;
                        }
                        else if (vnode is BooleanNode)
                        {
                            defaultValue = (vnode as BooleanNode).Value;
                        }
                        else if (vnode is StringNode)
                        {
                            defaultValue = (vnode as StringNode).value;
                        }
                    }
                }

                return(new TypedParameter(arg.Name, argType.ToString(), defaultValue));
            });

            IEnumerable <string> returnKeys = null;

            if (proc.MethodAttribute != null && proc.MethodAttribute.ReturnKeys != null)
            {
                returnKeys = proc.MethodAttribute.ReturnKeys;
            }

            var function = new FunctionDescriptor(
                library,
                className,
                procName,
                arguments,
                proc.returntype.ToString(),
                type,
                isVisible,
                returnKeys,
                proc.isVarArg);

            AddImportedFunctions(library, new[] { function });
        }
Beispiel #29
0
        /// <summary>
        ///     Import a library (if it hasn't been imported yet).
        /// </summary>
        /// <param name="library"></param>
        public void ImportLibrary(string library, ILogger logger)
        {
            if (null == library)
            {
                throw new ArgumentNullException();
            }

            if (!library.EndsWith(".dll", StringComparison.InvariantCultureIgnoreCase) &&
                !library.EndsWith(".ds", StringComparison.InvariantCultureIgnoreCase))
            {
                const string errorMessage = "Invalid library format.";
                OnLibraryLoadFailed(new LibraryLoadFailedEventArgs(library, errorMessage));
                return;
            }

            if (importedFunctionGroups.ContainsKey(library))
            {
                string errorMessage = string.Format("Library {0} has been loaded.", library);
                OnLibraryLoadFailed(new LibraryLoadFailedEventArgs(library, errorMessage));
                return;
            }

            if (!DynamoPathManager.Instance.ResolveLibraryPath(ref library))
            {
                string errorMessage = string.Format("Cannot find library path: {0}.", library);
                OnLibraryLoadFailed(new LibraryLoadFailedEventArgs(library, errorMessage));
                return;
            }

            OnLibraryLoading(new LibraryLoadingEventArgs(library));

            try
            {
                int globalFunctionNumber = GraphUtilities.GetGlobalMethods(string.Empty).Count;

                DLLFFIHandler.Register(FFILanguage.CSharp, new CSModuleHelper());
                IList <ClassNode> importedClasses = GraphUtilities.GetClassesForAssembly(library);

                if (GraphUtilities.BuildStatus.ErrorCount > 0)
                {
                    string errorMessage = string.Format("Build error for library: {0}", library);
                    logger.LogWarning(errorMessage, WarningLevel.Moderate);
                    foreach (ErrorEntry error in GraphUtilities.BuildStatus.Errors)
                    {
                        logger.LogWarning(error.Message, WarningLevel.Moderate);
                        errorMessage += error.Message + "\n";
                    }

                    OnLibraryLoadFailed(new LibraryLoadFailedEventArgs(library, errorMessage));
                    return;
                }

                foreach (ClassNode classNode in importedClasses)
                {
                    ImportClass(library, classNode);
                }

                // GraphUtilities.GetGlobalMethods() ignores input and just
                // return all global functions. The workaround is to get
                // new global functions after importing this assembly.
                List <ProcedureNode> globalFunctions = GraphUtilities.GetGlobalMethods(string.Empty);
                for (int i = globalFunctionNumber; i < globalFunctions.Count; ++i)
                {
                    ImportProcedure(library, globalFunctions[i]);
                }
            }
            catch (Exception e)
            {
                OnLibraryLoadFailed(new LibraryLoadFailedEventArgs(library, e.Message));
                return;
            }

            OnLibraryLoaded(new LibraryLoadedEventArgs(library));
        }
Beispiel #30
0
 private void PreloadLibraries()
 {
     GraphUtilities.Reset();
     libraries = DynamoPathManager.Instance.PreloadLibraries;
     GraphUtilities.PreloadAssembly(libraries);
 }