public void Test()
        {
             var gen = new XmlResultsGenerator(null,null,null, null, null);

            var muSession = new MutationTestingSession();
            
            var mutar = new MutationTarget(new MutationVariant());


            var ass = new AssemblyNode("Assembly");
            muSession.MutantsGrouped.Add(ass);
            var nodeNamespace = new TypeNamespaceNode(ass, "Namespace");
            ass.Children.Add(nodeNamespace);
            var nodeType = new TypeNode(nodeNamespace, "Type");
            nodeNamespace.Children.Add(nodeType);
            var nodeMethod = new MethodNode(nodeType, "Method", null, true);
            nodeType.Children.Add(nodeMethod);
            var nodeGroup = new MutantGroup("Gr1", nodeMethod);
            nodeMethod.Children.Add(nodeGroup);
            var nodeMutant = new Mutant("m1", nodeGroup, mutar);
            nodeGroup.Children.Add(nodeMutant);

            XDocument generateResults = gen.GenerateResults(muSession, false, false, ProgressCounter.Inactive(), CancellationToken.None).Result;

            Console.WriteLine(generateResults.ToString());
            //gen.
        }
Exemplo n.º 2
0
 public Mutant CreateEquivalentMutant(out AssemblyNode assemblyNode)
 {
     
     assemblyNode = new AssemblyNode("All modules");
     var nsNode = new TypeNamespaceNode(assemblyNode, "");
     assemblyNode.Children.Add(nsNode);
     var typeNode = new TypeNode(nsNode, "");
     nsNode.Children.Add(typeNode);
     var methodNode = new MethodNode(typeNode, "", null, true);
     typeNode.Children.Add(methodNode);
     var group = new MutantGroup("Testing original program", methodNode);
     var target = new MutationTarget(new MutationVariant())
                  {
                      Name = "Original program",
                  };
     var mutant = new Mutant("0", group, target);
    
     group.Children.Add(mutant);
     methodNode.Children.Add(group);
     group.UpdateDisplayedText();
     return mutant;
 }
        /// <summary>
        /// Creates an Method node in the address space.
        /// </summary>
        public NodeId CreateMethod(
            NodeId           parentId,
            NodeId           referenceTypeId,
            NodeId           nodeId,
            QualifiedName    browseName,
            MethodAttributes attributes)
        {
            if (browseName == null) throw new ArgumentNullException("browseName");

            try
            {
                m_lock.Enter();

                // check for null node id.
                if (NodeId.IsNull(nodeId))
                {
                    nodeId = CreateUniqueNodeId();
                }

                // check if node id exists.
                if (m_nodes.Exists(nodeId))
                {
                    throw ServiceResultException.Create(StatusCodes.BadNodeIdExists, "NodeId '{0}' already exists.", nodeId);
                }

                // find parent.
                ILocalNode parent = null;

                if (!NodeId.IsNull(parentId))
                {
                    parent = GetManagerHandle(parentId) as ILocalNode;

                    if (parent == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadParentNodeIdInvalid, "Parent node '{0}' does not exist.", parentId);
                    }

                    // validate reference.
                    ValidateReference(parent, referenceTypeId, false, NodeClass.Method);
                }

                // validate browse name.
                if (QualifiedName.IsNull(browseName))
                {
                    throw ServiceResultException.Create(StatusCodes.BadBrowseNameInvalid, "BrowsName must not be empty.");
                }               

                // verify instance declarations.
                ILocalNode instanceDeclaration = FindInstanceDeclaration(parent, browseName);

                if (instanceDeclaration != null)
                {
                    if (instanceDeclaration.NodeClass != NodeClass.Method)
                    {                        
                        throw ServiceResultException.Create(
                            StatusCodes.BadNodeClassInvalid, 
                            "The type model requires that node with a browse name of {0} have a NodeClass of {1}.", 
                            browseName,
                            instanceDeclaration.NodeClass);
                    }
                }

                // get the variable.
                IMethod method = instanceDeclaration as IMethod;

                // create node.
                MethodNode node = new MethodNode();

                // set defaults.
                node.NodeId         = nodeId;
                node.NodeClass      = NodeClass.Method;
                node.BrowseName     = browseName;
                node.DisplayName    = browseName.Name;
                node.Description    = null;
                node.WriteMask      = 0;
                node.UserWriteMask  = 0;
                node.Executable     = false;
                node.UserExecutable = false;

                // set defaults from instance declaration.
                if (method != null)
                {
                    node.DisplayName    = method.DisplayName;
                    node.Description    = method.Description;
                    node.WriteMask      = (uint)method.WriteMask;
                    node.UserWriteMask  = (uint)method.UserWriteMask;
                    node.Executable     = method.Executable;
                    node.UserExecutable = method.UserExecutable;
                }            
                      
                // update attributes.
                UpdateAttributes(node, attributes);
      
                // Executable    
                if (attributes != null && (attributes.SpecifiedAttributes & (uint)NodeAttributesMask.Executable) != 0)
                {
                    node.Executable = attributes.Executable;
                }
  
                // UserExecutable    
                if (attributes != null && (attributes.SpecifiedAttributes & (uint)NodeAttributesMask.UserExecutable) != 0)
                {
                    node.UserExecutable = attributes.UserExecutable;
                }
                
                // add references with parent.
                if (parent != null)
                {
                    AddReference(parent, referenceTypeId, false, node, true);                
                }
                                
                // add to address space.
                AddNode(node);
                                
                // return the new node id.
                return node.NodeId;
            }
            finally
            {
                m_lock.Exit();
            } 
        }     
Exemplo n.º 4
0
            internal virtual void visitMethod(MethodNode method)
            {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'sealed override':
//ORIGINAL LINE: sealed override bool isConstructor = "<init>".equals(method.name);
                bool isConstructor = "<init>".Equals(method.name);

                deleteUpToInsn = null;
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (java.util.ListIterator<?> lit = method.instructions.iterator(); lit.hasNext();)
                for (IEnumerator <object> lit = method.instructions.GetEnumerator(); lit.MoveNext();)
                {
                    AbstractInsnNode insn = (AbstractInsnNode)lit.Current;

                    if (deleteUpToInsn != null)
                    {
                        if (insn == deleteUpToInsn)
                        {
                            deleteUpToInsn = null;
                        }
                        else
                        {
                            // Do not delete labels, they could be used as a target from a previous jump.
                            // Also keep line numbers for easier debugging.
                            if (insn.Type != LABEL && insn.Type != LINE)
                            {
//JAVA TO C# CONVERTER TODO TASK: .NET enumerators are read-only:
                                lit.remove();
                            }
                            continue;
                        }
                    }

                    if (insn.Type == AbstractInsnNode.FRAME)
                    {
                        // Remove all the FRAME information, they will be calculated
                        // anew after the class specialization.
                        lit.remove();
                    }
                    else if (insn.Opcode == Opcodes.GETSTATIC)
                    {
                        FieldInsnNode fieldInsn = (FieldInsnNode)insn;
                        if (variables.ContainsKey(fieldInsn.name))
                        {
                            bool processed = false;
                            value = variables[fieldInsn.name];
                            AbstractInsnNode nextInsn = insn.Next;
                            if (analyseIfTestInt(method, insn))
                            {
                                processed = true;
                            }
                            else if (nextInsn != null && nextInsn.Type == TABLESWITCH_INSN)
                            {
                                TableSwitchInsnNode switchInsn = (TableSwitchInsnNode)nextInsn;
                                LabelNode           label      = null;
                                if (isIntValue(value))
                                {
                                    int n = getIntValue(value);
                                    if (n >= switchInsn.min && n <= switchInsn.max)
                                    {
                                        int i = n - switchInsn.min;
                                        if (i < switchInsn.labels.size())
                                        {
                                            label = (LabelNode)switchInsn.labels.get(i);
                                        }
                                    }
                                }
                                if (label == null)
                                {
                                    label = switchInsn.dflt;
                                }
                                if (label != null)
                                {
                                    // Replace the table switch instruction by a GOTO to the switch label
                                    method.instructions.set(insn, new JumpInsnNode(Opcodes.GOTO, label));
                                    processed = true;
                                }
                            }
                            else if (nextInsn != null && nextInsn.Type == LOOKUPSWITCH_INSN)
                            {
                                LookupSwitchInsnNode switchInsn = (LookupSwitchInsnNode)nextInsn;
                                LabelNode            label      = null;
                                if (isIntValue(value))
                                {
                                    int n = getIntValue(value);
                                    int i = 0;
                                    foreach (object value in switchInsn.keys)
                                    {
                                        if (value is int?)
                                        {
                                            if (((int?)value).Value == n)
                                            {
                                                label = (LabelNode)switchInsn.labels.get(i);
                                                break;
                                            }
                                        }
                                        i++;
                                    }
                                }
                                if (label == null)
                                {
                                    label = switchInsn.dflt;
                                }
                                if (label != null)
                                {
                                    // Replace the table switch instruction by a GOTO to the switch label
                                    method.instructions.set(insn, new JumpInsnNode(Opcodes.GOTO, label));
                                    processed = true;
                                }
                            }
                            else if (nextInsn != null && nextInsn.Type == AbstractInsnNode.INSN)
                            {
                                int   opcode          = nextInsn.Opcode;
                                int   n               = 0;
                                float f               = 0f;
                                bool  isIntConstant   = false;
                                bool  isFloatConstant = false;
                                switch (opcode)
                                {
                                case Opcodes.ICONST_M1:
                                    n             = -1;
                                    isIntConstant = true;
                                    break;

                                case Opcodes.ICONST_0:
                                    n             = 0;
                                    isIntConstant = true;
                                    break;

                                case Opcodes.ICONST_1:
                                    n             = 1;
                                    isIntConstant = true;
                                    break;

                                case Opcodes.ICONST_2:
                                    n             = 2;
                                    isIntConstant = true;
                                    break;

                                case Opcodes.ICONST_3:
                                    n             = 3;
                                    isIntConstant = true;
                                    break;

                                case Opcodes.ICONST_4:
                                    n             = 4;
                                    isIntConstant = true;
                                    break;

                                case Opcodes.ICONST_5:
                                    n             = 5;
                                    isIntConstant = true;
                                    break;

                                case Opcodes.FCONST_0:
                                    f = 0f;
                                    isFloatConstant = true;
                                    break;

                                case Opcodes.FCONST_1:
                                    f = 1f;
                                    isFloatConstant = true;
                                    break;

                                case Opcodes.FCONST_2:
                                    f = 2f;
                                    isFloatConstant = true;
                                    break;
                                }
                                if (isIntConstant)
                                {
                                    if (analyseIfTestInt(method, insn, nextInsn, n))
                                    {
                                        processed = true;
                                    }
                                }
                                else if (isFloatConstant)
                                {
                                    if (analyseIfTestFloat(method, insn, nextInsn, f))
                                    {
                                        processed = true;
                                    }
                                }
                            }
                            else if (nextInsn != null && nextInsn.Type == AbstractInsnNode.INT_INSN)
                            {
                                IntInsnNode intInsn = (IntInsnNode)nextInsn;
                                if (analyseIfTestInt(method, insn, nextInsn, intInsn.operand))
                                {
                                    processed = true;
                                }
                            }
                            else if (nextInsn != null && nextInsn.Type == AbstractInsnNode.LDC_INSN)
                            {
                                LdcInsnNode ldcInsn = (LdcInsnNode)nextInsn;
                                if (isIntValue(ldcInsn.cst))
                                {
                                    if (analyseIfTestInt(method, insn, nextInsn, getIntValue(ldcInsn.cst)))
                                    {
                                        processed = true;
                                    }
                                }
                                else if (isFloatValue(ldcInsn.cst))
                                {
                                    if (analyseIfTestFloat(method, insn, nextInsn, getFloatValue(ldcInsn.cst)))
                                    {
                                        processed = true;
                                    }
                                }
                            }

                            if (!processed)
                            {
                                // Replace the FieldInfo access by its constant value
                                AbstractInsnNode constantInsn = getConstantInsn(value);
                                if (constantInsn != null)
                                {
                                    method.instructions.set(insn, constantInsn);
                                }
                            }
                        }
                        else
                        {
                            if (fieldInsn.owner.Equals(className))
                            {
                                // Replace the class name by the specialized class name
                                fieldInsn.owner = specializedClassName;
                            }
                        }
                    }
                    else if (insn.Opcode == Opcodes.PUTSTATIC)
                    {
                        FieldInsnNode fieldInsn = (FieldInsnNode)insn;
                        if (!variables.ContainsKey(fieldInsn.name))
                        {
                            if (fieldInsn.owner.Equals(className))
                            {
                                // Replace the class name by the specialized class name
                                fieldInsn.owner = specializedClassName;
                            }
                        }
                    }
                    else if (insn.Type == AbstractInsnNode.METHOD_INSN)
                    {
                        MethodInsnNode methodInsn = (MethodInsnNode)insn;
                        if (methodInsn.owner.Equals(className))
                        {
                            // Replace the class name by the specialized class name
                            methodInsn.owner = specializedClassName;
                        }
                        else if (isConstructor && methodInsn.owner.Equals(superClassName))
                        {
                            // Update the call to the constructor of the parent class
                            methodInsn.owner = className;
                        }
                    }
                }

                // Delete all the information about local variables, they are no longer correct
                // (the class loader would complain).
                method.localVariables.clear();

                optimizeJumps(method);
                removeDeadCode(method);
                optimizeJumps(method);
                removeUnusedLabels(method);
                removeUselessLineNumbers(method);
            }
Exemplo n.º 5
0
        /// <summary>
        /// Collects the child methods of a Node.
        /// </summary>
        private bool CollectMethods(Node node, bool testErrors, List <TestMethod> methods)
        {
            if (node == null || node.NodeClass != NodeClass.Method)
            {
                return(true);
            }

            MethodNode method = node as MethodNode;

            IList <INode> parents = Session.NodeCache.Find(
                node.NodeId,
                ReferenceTypeIds.HasComponent,
                true,
                true);

            for (int ii = 0; ii < parents.Count; ii++)
            {
                ObjectNode parent = parents[ii] as ObjectNode;

                if (parent != null && method != null)
                {
                    if (!testErrors && parent.BrowseName.Name != "MethodTest")
                    {
                        continue;
                    }

                    bool found = false;

                    for (int jj = 0; jj < methods.Count; jj++)
                    {
                        if (Object.ReferenceEquals(method, methods[jj].Method))
                        {
                            found = true;
                            break;
                        }
                    }

                    if (found)
                    {
                        continue;
                    }

                    TestMethod test = new TestMethod();

                    test.Parent          = parent;
                    test.Method          = method;
                    test.InputArguments  = new Argument[0];
                    test.OutputArguments = new Argument[0];
                    test.Inputs          = new List <object>();

                    methods.Add(test);

                    if (methods.Count % 25 == 0)
                    {
                        Log("Found for {0} Methods to Call", methods.Count);
                    }

                    IList <INode> properties = Session.NodeCache.Find(
                        method.NodeId,
                        ReferenceTypeIds.HasProperty,
                        false,
                        true);

                    for (int jj = 0; jj < properties.Count; jj++)
                    {
                        VariableNode property = properties[jj] as VariableNode;

                        if (property != null)
                        {
                            if (property.BrowseName == BrowseNames.InputArguments)
                            {
                                if (property.Value.Value == null)
                                {
                                    DataValue value = Session.ReadValue(property.NodeId);
                                    property.Value = value.WrappedValue;
                                }

                                test.InputArguments = (Argument[])ExtensionObject.ToArray(property.Value.Value as Array, typeof(Argument));

                                if (test.InputArguments == null)
                                {
                                    Log(
                                        "Could not read input arguments for method '{0}'. NodeId = {1}, Method = {2}",
                                        test.Parent,
                                        test.Parent.NodeId,
                                        test.Method);

                                    return(false);
                                }

                                continue;
                            }

                            if (property.BrowseName == BrowseNames.OutputArguments)
                            {
                                if (property.Value.Value == null)
                                {
                                    DataValue value = Session.ReadValue(property.NodeId);
                                    property.Value = value.WrappedValue;
                                }

                                test.OutputArguments = (Argument[])ExtensionObject.ToArray(property.Value.Value as Array, typeof(Argument));

                                if (test.OutputArguments == null)
                                {
                                    Log(
                                        "Could not read output arguments for method '{0}'. NodeId = {1}, Method = {2}",
                                        test.Parent,
                                        test.Parent.NodeId,
                                        test.Method);

                                    return(false);
                                }

                                continue;
                            }
                        }
                    }
                }
            }

            return(true);
        }
Exemplo n.º 6
0
 public MethodObject(MethodNode node, Dictionary <ObjectType, GameObject> prefabs) : base(node, prefabs)
 {
 }
Exemplo n.º 7
0
        /// <see cref="BaseTreeCtrl.EnableMenuItems" />
        protected override void EnableMenuItems(TreeNode clickedNode)
        {
            BrowseOptionsMI.Enabled   = true;
            ShowReferencesMI.Enabled  = true;
            SelectMI.Visible          = m_allowPick;
            SelectSeparatorMI.Visible = m_allowPick;

            if (clickedNode != null)
            {
                // do nothing if an error is detected.
                if (m_browser.Session.KeepAliveStopped)
                {
                    return;
                }

                SelectMI.Enabled         = true;
                SelectItemMI.Enabled     = true;
                SelectChildrenMI.Enabled = clickedNode.Nodes.Count > 0;
                BrowseRefreshMI.Enabled  = true;

                ReferenceDescription reference = clickedNode.Tag as ReferenceDescription;

                if (reference != null)
                {
                    BrowseMI.Enabled         = (reference.NodeId != null && !reference.NodeId.IsAbsolute);
                    ViewAttributesMI.Enabled = true;

                    NodeId nodeId = ExpandedNodeId.ToNodeId(reference.NodeId, m_browser.Session.NamespaceUris);

                    INode node = m_browser.Session.ReadNode(nodeId);

                    byte accessLevel   = 0;
                    byte eventNotifier = 0;
                    bool executable    = false;

                    VariableNode variableNode = node as VariableNode;

                    if (variableNode != null)
                    {
                        accessLevel = variableNode.UserAccessLevel;
                    }

                    ObjectNode objectNode = node as ObjectNode;

                    if (objectNode != null)
                    {
                        eventNotifier = objectNode.EventNotifier;
                    }

                    ViewNode viewNode = node as ViewNode;

                    if (viewNode != null)
                    {
                        eventNotifier = viewNode.EventNotifier;
                    }

                    MethodNode methodNode = node as MethodNode;

                    if (methodNode != null)
                    {
                        executable = methodNode.UserExecutable;
                    }

                    ReadMI.Visible          = false;
                    HistoryReadMI.Visible   = false;
                    WriteMI.Visible         = false;
                    HistoryUpdateMI.Visible = false;
                    EncodingsMI.Visible     = false;
                    SubscribeMI.Visible     = false;
                    CallMI.Visible          = false;

                    if (accessLevel != 0)
                    {
                        ReadMI.Visible          = true;
                        HistoryReadMI.Visible   = true;
                        WriteMI.Visible         = true;
                        HistoryUpdateMI.Visible = true;
                        EncodingsMI.Visible     = true;
                        SubscribeMI.Visible     = m_SessionTreeCtrl != null;

                        if ((accessLevel & (byte)AccessLevels.CurrentRead) != 0)
                        {
                            ReadMI.Enabled         = true;
                            EncodingsMI.Enabled    = true;
                            SubscribeMI.Enabled    = true;
                            SubscribeNewMI.Enabled = true;
                        }

                        if ((accessLevel & (byte)AccessLevels.CurrentWrite) != 0)
                        {
                            WriteMI.Enabled     = true;
                            EncodingsMI.Enabled = true;
                        }

                        if ((accessLevel & (byte)AccessLevels.HistoryRead) != 0)
                        {
                            HistoryReadMI.Enabled = true;
                        }

                        if ((accessLevel & (byte)AccessLevels.HistoryWrite) != 0)
                        {
                            HistoryUpdateMI.Enabled = true;
                        }
                    }

                    if (eventNotifier != 0)
                    {
                        HistoryReadMI.Visible   = true;
                        HistoryUpdateMI.Visible = true;
                        SubscribeMI.Visible     = true;

                        if ((eventNotifier & (byte)EventNotifiers.HistoryRead) != 0)
                        {
                            HistoryReadMI.Enabled = true;
                        }

                        if ((eventNotifier & (byte)EventNotifiers.HistoryWrite) != 0)
                        {
                            HistoryUpdateMI.Enabled = true;
                        }

                        SubscribeMI.Enabled    = (eventNotifier & (byte)EventNotifiers.SubscribeToEvents) != 0;
                        SubscribeNewMI.Enabled = SubscribeMI.Enabled;
                    }

                    if (methodNode != null)
                    {
                        CallMI.Visible = true;
                        CallMI.Enabled = executable;
                    }

                    if (variableNode != null && EncodingsMI.Enabled)
                    {
                        ReferenceDescriptionCollection encodings = m_browser.Session.ReadAvailableEncodings(variableNode.NodeId);

                        if (encodings.Count == 0)
                        {
                            EncodingsMI.Visible = false;
                        }
                    }

                    if (SubscribeMI.Enabled)
                    {
                        while (SubscribeMI.DropDown.Items.Count > 1)
                        {
                            SubscribeMI.DropDown.Items.RemoveAt(SubscribeMI.DropDown.Items.Count - 1);
                        }

                        foreach (Subscription subscription in m_browser.Session.Subscriptions)
                        {
                            if (subscription.Created)
                            {
                                ToolStripItem item = SubscribeMI.DropDown.Items.Add(subscription.DisplayName);
                                item.Click += new EventHandler(Subscription_Click);
                                item.Tag    = subscription;
                            }
                        }
                    }
                }
            }
        }
        public async Task <ActionResult> GetChildren(string jstreeNode)
        {
            string[] publishedNodes = await GetListofPublishedNodeIDsforServer();

            // This delimiter is used to allow the storing of the OPC UA parent node ID together with the OPC UA child node ID in jstree data structures and provide it as parameter to
            // Ajax calls.
            string[] delimiter       = { "__$__" };
            string[] jstreeNodeSplit = jstreeNode.Split(delimiter, 3, StringSplitOptions.None);
            string   node;

            if (jstreeNodeSplit.Length == 1)
            {
                node = jstreeNodeSplit[0];
            }
            else
            {
                node = jstreeNodeSplit[1];
            }

            ReferenceDescriptionCollection references;

            Byte[] continuationPoint;
            var    jsonTree = new List <object>();

            bool retry = true;

            while (true)
            {
                try
                {
                    Session session = await OpcSessionHelper.Instance.GetSessionAsync(Session.SessionID, (string)Session["EndpointUrl"]);

                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    session.Browse(
                        null,
                        null,
                        node,
                        0u,
                        BrowseDirection.Forward,
                        ReferenceTypeIds.HierarchicalReferences,
                        true,
                        0,
                        out continuationPoint,
                        out references);

                    Trace.TraceInformation("Browse {0} ms", stopwatch.ElapsedMilliseconds);

                    if (references != null)
                    {
                        var idList = new List <string>();
                        foreach (var nodeReference in references)
                        {
                            bool idFound = false;
                            foreach (var id in idList)
                            {
                                if (id == nodeReference.NodeId.ToString())
                                {
                                    idFound = true;
                                }
                            }
                            if (idFound == true)
                            {
                                continue;
                            }

                            ReferenceDescriptionCollection childReferences = null;
                            Byte[] childContinuationPoint;

                            session.Browse(
                                null,
                                null,
                                ExpandedNodeId.ToNodeId(nodeReference.NodeId, session.NamespaceUris),
                                0u,
                                BrowseDirection.Forward,
                                ReferenceTypeIds.HierarchicalReferences,
                                true,
                                0,
                                out childContinuationPoint,
                                out childReferences);

                            INode currentNode = null;
                            try
                            {
                                currentNode = session.ReadNode(ExpandedNodeId.ToNodeId(nodeReference.NodeId, session.NamespaceUris));
                            }
                            catch (Exception)
                            {
                                // skip this node
                                continue;
                            }

                            byte currentNodeAccessLevel   = 0;
                            byte currentNodeEventNotifier = 0;
                            bool currentNodeExecutable    = false;

                            VariableNode variableNode = currentNode as VariableNode;
                            if (variableNode != null)
                            {
                                currentNodeAccessLevel = variableNode.UserAccessLevel;
                                if (!PermsChecker.HasPermission(Permission.ControlOpcServer))
                                {
                                    currentNodeAccessLevel = (byte)((uint)currentNodeAccessLevel & ~0x2);
                                }
                            }

                            ObjectNode objectNode = currentNode as ObjectNode;
                            if (objectNode != null)
                            {
                                currentNodeEventNotifier = objectNode.EventNotifier;
                            }

                            ViewNode viewNode = currentNode as ViewNode;
                            if (viewNode != null)
                            {
                                currentNodeEventNotifier = viewNode.EventNotifier;
                            }

                            MethodNode methodNode = currentNode as MethodNode;
                            if (methodNode != null && PermsChecker.HasPermission(Permission.ControlOpcServer))
                            {
                                currentNodeExecutable = methodNode.UserExecutable;
                            }

                            var published = false;
                            foreach (var nodeId in publishedNodes)
                            {
                                if (nodeId == nodeReference.NodeId.ToString())
                                {
                                    published = true;
                                }
                            }

                            jsonTree.Add(new
                            {
                                id            = ("__" + node + delimiter[0] + nodeReference.NodeId.ToString()),
                                text          = nodeReference.DisplayName.ToString(),
                                nodeClass     = nodeReference.NodeClass.ToString(),
                                accessLevel   = currentNodeAccessLevel.ToString(),
                                eventNotifier = currentNodeEventNotifier.ToString(),
                                executable    = currentNodeExecutable.ToString(),
                                children      = (childReferences.Count == 0) ? false : true,
                                publishedNode = published
                            });
                            idList.Add(nodeReference.NodeId.ToString());
                        }

                        // If there are no children, then this is a call to read the properties of the node itself.
                        if (jsonTree.Count == 0)
                        {
                            INode currentNode = session.ReadNode(new NodeId(node));

                            byte currentNodeAccessLevel   = 0;
                            byte currentNodeEventNotifier = 0;
                            bool currentNodeExecutable    = false;

                            VariableNode variableNode = currentNode as VariableNode;

                            if (variableNode != null)
                            {
                                currentNodeAccessLevel = variableNode.UserAccessLevel;
                                if (!PermsChecker.HasPermission(Permission.ControlOpcServer))
                                {
                                    currentNodeAccessLevel = (byte)((uint)currentNodeAccessLevel & ~0x2);
                                }
                            }

                            ObjectNode objectNode = currentNode as ObjectNode;

                            if (objectNode != null)
                            {
                                currentNodeEventNotifier = objectNode.EventNotifier;
                            }

                            ViewNode viewNode = currentNode as ViewNode;

                            if (viewNode != null)
                            {
                                currentNodeEventNotifier = viewNode.EventNotifier;
                            }

                            MethodNode methodNode = currentNode as MethodNode;

                            if (methodNode != null && PermsChecker.HasPermission(Permission.ControlOpcServer))
                            {
                                currentNodeExecutable = methodNode.UserExecutable;
                            }

                            jsonTree.Add(new
                            {
                                id            = jstreeNode,
                                text          = currentNode.DisplayName.ToString(),
                                nodeClass     = currentNode.NodeClass.ToString(),
                                accessLevel   = currentNodeAccessLevel.ToString(),
                                eventNotifier = currentNodeEventNotifier.ToString(),
                                executable    = currentNodeExecutable.ToString(),
                                children      = false
                            });
                        }
                    }

                    stopwatch.Stop();
                    Trace.TraceInformation("GetChildren took {0} ms", stopwatch.ElapsedMilliseconds);

                    return(Json(jsonTree, JsonRequestBehavior.AllowGet));
                }
                catch (Exception exception)
                {
                    OpcSessionHelper.Instance.Disconnect(Session.SessionID);
                    if (!retry)
                    {
                        return(Content(CreateOpcExceptionActionString(exception)));
                    }
                    retry = false;
                }
            }
        }
Exemplo n.º 9
0
 private void DrawConnection(GameObject one, GameObject two, ParameterNode paraNode, MethodNode methodNode)
 {
     if (one.transform.parent == two.transform.parent)
     {
         this.drawer.DrawDynamicCurve(one.transform, two.transform, two.transform.parent.transform.position, 0.1f, Color.cyan, 1);
     }
     else
     {
         this.drawer.DrawDynamicLine(one.transform, two.transform, 0.1f, Color.green, paraNode, methodNode);
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// Processes the specified root.
        /// </summary>
        /// <param name="file">The filename.</param>
        /// <param name="root">The root.</param>
        internal static void Process(Options options, string source)
        {
            string filename = Path.GetFileName(source);

            string originalFile = source.Insert(source.Length - 3, ".Original");
            string mosaFile = source.Insert(source.Length - 3, ".Mosa");
            string monoFile = source.Insert(source.Length - 3, ".Internal");

            bool same = CompareFile.Compare(Path.Combine(options.Source, source), Path.Combine(options.Destination, originalFile));

            //Console.WriteLine("# " + filename);

            if (!File.Exists(Path.Combine(options.Source, source)))
            {
                Console.WriteLine("0> " + filename);

                if (options.UpdateOnChange)
                {
                    File.Delete(Path.Combine(options.Destination, source));
                    File.Delete(Path.Combine(options.Destination, originalFile));
                    File.Delete(Path.Combine(options.Destination, mosaFile));
                    File.Delete(Path.Combine(options.Destination, monoFile));
                }

                return;
            }

            string[] lines = File.ReadAllLines(Path.Combine(options.Source, source));

            ClassNode rootNode = new ClassNode();
            List<ClassNode> classNodes = new List<ClassNode>();
            List<MethodNode> methodNodes = new List<MethodNode>();

            List<int> namespaces = new List<int>();
            List<int> usings = new List<int>();

            ClassNode currentNode = rootNode;
            bool incomment = false;

            // Analyze File
            for (int linenbr = 0; linenbr < lines.Length; linenbr++)
            {
                string trim = GetLine(lines, linenbr, ref incomment).Replace('\t', ' ');

                if (incomment)
                    continue;

                trim = StripWithInDoubleQuotes(trim);

                int skip = 0;

                if (string.IsNullOrEmpty(trim))
                    continue;
                else if (trim.StartsWith("#"))
                    continue;
                else if ((trim.StartsWith("extern ") || (trim.Contains(" extern "))) && !trim.Contains(" alias "))
                {
                    int start = GetPreviousBlockEnd(lines, linenbr);
                    skip = GetNumberOfMethodDeclarationLines(lines, linenbr, false);
                    MethodNode node = new MethodNode(currentNode, start, linenbr + skip, linenbr);
                    methodNodes.Add(node);
                    currentNode.Methods.Add(node);
                }
                else if (trim.StartsWith("using ") && trim.Contains(";"))
                {
                    usings.Add(linenbr);

                }
                else if (trim.StartsWith("namespace "))
                {
                    namespaces.Add(linenbr);
                }
                else if (trim.Contains(" class ") || (trim.StartsWith("class ")) ||
                         trim.Contains(" struct ") || (trim.StartsWith("struct ")))
                {
                    // Search backwards for the start of the class definition (might not be on the same line as class keyword)
                    int start = GetPreviousBlockEnd(lines, linenbr);

                    string className = GetClassName(lines, start, linenbr);

                    // Attempt to handle #else class definitions
                    if (className == currentNode.Name)
                    {
                        currentNode.OtherDeclare.Add(linenbr);
                        continue;
                    }

                    // Find the last line of the class
                    int end = GetEndOfScope(lines, linenbr);

                    // Go up to parent
                    while (linenbr > currentNode.End)
                        currentNode = currentNode.Parent;

                    // Child
                    ClassNode child = new ClassNode(currentNode, start, end, linenbr);
                    classNodes.Add(child);
                    currentNode.Children.Add(child);
                    currentNode = child;
                    child.Name = className;
                }

                linenbr = linenbr + skip;

                // Go up to parent
                while (linenbr >= currentNode.End)
                    currentNode = currentNode.Parent;
            }

            // Mark all partial nodes
            foreach (ClassNode node in classNodes)
                if (node.Methods.Count != 0)
                {
                    node.Partial = true;
                    ClassNode upNode = node;
                    do
                    {
                        upNode.Parent.Partial = true;
                        upNode = upNode.Parent;
                    } while (upNode != upNode.Parent);
                }

            Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(options.Destination, source)));

            if (methodNodes.Count != 0)
            {
                if (options.CreateOriginalFile && !same)
                {
                    Console.WriteLine("1> " + originalFile);
                    File.Copy(Path.Combine(options.Source, source), Path.Combine(options.Destination, originalFile), true);
                }

                ExpandUsing(lines, usings);

                if (options.CreateMosaFile)
                {
                    if (!File.Exists(Path.Combine(options.Destination, mosaFile)) || (options.UpdateOnChange && !same))
                    {
                        Console.WriteLine("2> " + mosaFile);
                        CreatePartialFileForMosa(lines, rootNode, usings, namespaces, Path.Combine(options.Destination, mosaFile));
                    }
                }

                if (options.CreateMonoFile)
                {
                    if (!File.Exists(Path.Combine(options.Destination, monoFile)) || (options.UpdateOnChange && !same))
                    {
                        Console.WriteLine("3> " + monoFile);
                        CreatePartialFileForMono(lines, rootNode, usings, namespaces, Path.Combine(options.Destination, monoFile));
                    }
                }

                if (options.UpdateOnChange && !same)
                {
                    Console.WriteLine("4> " + source);
                    CreateModifiedFile(lines, classNodes, methodNodes, Path.Combine(options.Destination, source));
                }
            }
            else
            {
                same = CompareFile.Compare(Path.Combine(options.Source, source), Path.Combine(options.Destination, source));

                if (options.UpdateOnChange && !same)
                {
                    Console.WriteLine("5> " + source);
                    File.Copy(Path.Combine(options.Source, source), Path.Combine(options.Destination, source), true);
                    File.Delete(Path.Combine(options.Destination, originalFile));
                    File.Delete(Path.Combine(options.Destination, mosaFile));
                    File.Delete(Path.Combine(options.Destination, monoFile));
                }
            }
        }
Exemplo n.º 11
0
 public void DrawDynamicLine(Transform transOne, Transform transTwo, float thickness, Color color, ParameterNode parentNodeOne, MethodNode parentNodeTwo)
 {
     this.lines.Add(new Line(transOne, transTwo, thickness, color, this.UI.spellcraftParent, parentNodeOne, parentNodeTwo));
 }
Exemplo n.º 12
0
 public virtual List<Tuple<string, string>> TranslateMethod(MethodNode method, ref QueryParser parser, out string scalarMethodName)
 {
     scalarMethodName = null;
     var @params = new List<Tuple<string, string>>();
     switch (method.Name)
     {
         case "Query":
         case "Where":
             @params.Add(new Tuple<string, string>("q", TranslateBody(method.Body)));
             break;
         case "Filter":
             @params.Add(new Tuple<string, string>("fq", TranslateBody(method.Body)));
             break;
         case "Facet":
             var facet = (FacetNode)method.Body;
             var facetFieldName = TranslateBody(facet.Field);
             if (facet.IsMultiFacet && facet.Values.Any())
             {
                 @params.Add(new Tuple<string, string>("facet.field", $"{{!ex={facetFieldName}}}{facetFieldName}"));
                 @params.Add(new Tuple<string, string>("fq", $"{{!tag={facetFieldName}}}{facetFieldName}:{string.Join(" OR ", facet.Values).ToSolrGroup()}"));
             }
             else
             {
                 @params.Add(new Tuple<string, string>("facet.field", facetFieldName));
             }
             break;
         case "PivotFacet":
             var pivotFacet = (PivotFacetNode)method.Body;
             var fields = pivotFacet.Facets.Select(x => TranslateBody(((FacetNode)x.Body).Field));
             @params.Add(new Tuple<string, string>("facet.pivot", string.Join(",", fields)));
             break;
         case "OrderBy":
         case "ThenBy":
         case "OrderByDescending":
         case "ThenByDescending":
             var field = TranslateBody(method.Body);
             var direction = method.Name.EndsWith("Descending") ? "desc" : "asc";
             @params.Add(new Tuple<string, string>("sort", $"{field} {direction}"));
             break;
         case "Take":
             @params.Add(new Tuple<string, string>("rows", TranslateBody(method.Body)));
             break;
         case "Skip":
             @params.Add(new Tuple<string, string>("start", TranslateBody(method.Body)));
             break;
         case "Count":
         case "First":
         case "FirstOrDefault":
         case "Last":
         case "LastOrDefault":
         case "Single":
         case "SingleOrDefault":
             if (method.Body != null)
             {
                 @params.Add(new Tuple<string, string>("q", TranslateBody(method.Body)));
             }
             scalarMethodName = method.Name;
             break;
         case "GetResponse":
             scalarMethodName = method.Name;
             break;
         case "Dismax":
             parser = QueryParser.Dismax;
             break;
         case "BoostQuery":
             @params.Add(new Tuple<string, string>("bq", TranslateBody(method.Body)));
             break;
         case "DismaxQueryAlt":
             @params.Add(new Tuple<string, string>("q.alt", TranslateBody(method.Body)));
             break;
         default:
             throw new NotSupportedException($"'{method.Name}' is not supported");
     }
     return @params;
 }
Exemplo n.º 13
0
        /// <summary>
        /// Returns the value of an attribute.
        /// </summary>
        public void Read(
            ReadValueId request,
            DataValue result,
            DiagnosticInfo diagnosticInfo)
        {
            lock (m_lock)
            {
                // find the node to read.
                Node source = m_nodes.Find(request.NodeId);

                result.ServerTimestamp = DateTime.UtcNow;

                if (source == null)
                {
                    result.StatusCode = new StatusCode(StatusCodes.BadNodeIdUnknown);
                    return;
                }

                result.Value = Variant.Null;

                // switch on the attribute value.
                switch (request.AttributeId)
                {
                case Attributes.NodeId:
                {
                    result.Value = new Variant(source.NodeId);
                    break;
                }

                case Attributes.NodeClass:
                {
                    result.Value = new Variant(DataTypes.EnumToMask(source.NodeClass));
                    break;
                }

                case Attributes.BrowseName:
                {
                    result.Value = new Variant(source.BrowseName);
                    break;
                }

                case Attributes.DisplayName:
                {
                    result.Value = new Variant(source.DisplayName);
                    break;
                }

                case Attributes.Description:
                {
                    result.Value = new Variant(source.Description);
                    break;
                }

                case Attributes.WriteMask:
                {
                    result.Value = new Variant(source.WriteMask);
                    break;
                }

                case Attributes.UserWriteMask:
                {
                    result.Value = new Variant(source.UserWriteMask);
                    break;
                }

                case Attributes.Value:
                {
                    // check if another component has installed a read callback.
                    ReadValueEventHandler callback = null;

                    if (m_callbacks.TryGetValue(source.NodeId.Identifier, out callback))
                    {
                        result.Value = new Variant(callback());
                        break;
                    }

                    // use the value cached in the node otherwise.
                    VariableNode variable = source as VariableNode;

                    if (variable != null)
                    {
                        result.Value           = variable.Value;
                        result.SourceTimestamp = DateTime.UtcNow;     // The Value attribute requires a SourceTimestamp.
                        break;
                    }

                    VariableTypeNode variableType = source as VariableTypeNode;

                    if (variableType != null)
                    {
                        result.Value           = variableType.Value;
                        result.SourceTimestamp = DateTime.UtcNow;     // The Value attribute requires a SourceTimestamp.
                        break;
                    }

                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }

                case Attributes.DataType:
                {
                    VariableNode variable = source as VariableNode;

                    if (variable != null)
                    {
                        result.Value = new Variant(variable.DataType);
                        break;
                    }

                    VariableTypeNode variableType = source as VariableTypeNode;

                    if (variableType != null)
                    {
                        result.Value = new Variant(variableType.DataType);
                        break;
                    }

                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }

                case Attributes.ValueRank:
                {
                    VariableNode variable = source as VariableNode;

                    if (variable != null)
                    {
                        result.Value = new Variant(variable.ValueRank);
                        break;
                    }

                    VariableTypeNode variableType = source as VariableTypeNode;

                    if (variableType != null)
                    {
                        result.Value = new Variant(variableType.ValueRank);
                        break;
                    }

                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }

                case Attributes.MinimumSamplingInterval:
                {
                    VariableNode variable = source as VariableNode;

                    if (variable != null)
                    {
                        result.Value = new Variant(variable.MinimumSamplingInterval);
                        break;
                    }

                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }

                case Attributes.Historizing:
                {
                    VariableNode variable = source as VariableNode;

                    if (variable != null)
                    {
                        result.Value = new Variant(variable.Historizing);
                        break;
                    }

                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }

                case Attributes.AccessLevel:
                {
                    VariableNode variable = source as VariableNode;

                    if (variable != null)
                    {
                        result.Value = new Variant(variable.AccessLevel);
                        break;
                    }

                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }

                case Attributes.UserAccessLevel:
                {
                    VariableNode variable = source as VariableNode;

                    if (variable != null)
                    {
                        result.Value = new Variant(variable.UserAccessLevel);
                        break;
                    }

                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }

                case Attributes.EventNotifier:
                {
                    ObjectNode objectn = source as ObjectNode;

                    if (objectn != null)
                    {
                        result.Value = new Variant(objectn.EventNotifier);
                        break;
                    }

                    ViewNode view = source as ViewNode;

                    if (view != null)
                    {
                        result.Value = new Variant(view.EventNotifier);
                        break;
                    }

                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }

                case Attributes.Executable:
                {
                    MethodNode method = source as MethodNode;

                    if (method != null)
                    {
                        result.Value = new Variant(method.Executable);
                        break;
                    }

                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }

                case Attributes.UserExecutable:
                {
                    MethodNode method = source as MethodNode;

                    if (method != null)
                    {
                        result.Value = new Variant(method.UserExecutable);
                        break;
                    }

                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }

                case Attributes.ContainsNoLoops:
                {
                    ViewNode view = source as ViewNode;

                    if (view != null)
                    {
                        result.Value = new Variant(view.ContainsNoLoops);
                        break;
                    }

                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }

                case Attributes.InverseName:
                {
                    ReferenceTypeNode referenceType = source as ReferenceTypeNode;

                    if (referenceType != null)
                    {
                        result.Value = new Variant(referenceType.InverseName);
                        break;
                    }

                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }

                case Attributes.IsAbstract:
                {
                    DataTypeNode dataType = source as DataTypeNode;

                    if (dataType != null)
                    {
                        result.Value = new Variant(dataType.IsAbstract);
                        break;
                    }

                    ReferenceTypeNode referenceType = source as ReferenceTypeNode;

                    if (referenceType != null)
                    {
                        result.Value = new Variant(referenceType.IsAbstract);
                        break;
                    }

                    ObjectTypeNode objectType = source as ObjectTypeNode;

                    if (objectType != null)
                    {
                        result.Value = new Variant(objectType.IsAbstract);
                        break;
                    }

                    VariableTypeNode variableType = source as VariableTypeNode;

                    if (variableType != null)
                    {
                        result.Value = new Variant(variableType.IsAbstract);
                        break;
                    }

                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }

                case Attributes.Symmetric:
                {
                    ReferenceTypeNode referenceType = source as ReferenceTypeNode;

                    if (referenceType != null)
                    {
                        result.Value = new Variant(referenceType.Symmetric);
                        break;
                    }

                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }

                default:
                {
                    result.StatusCode = new StatusCode(StatusCodes.BadAttributeIdInvalid);
                    break;
                }
                }
            }
        }
Exemplo n.º 14
0
        public void MethodNodeHasMethodNameAsNodeName()
        {
            MethodNode methodNode = new MethodNode("MethodName");

            Assert.AreEqual("MethodName", methodNode.Name);
        }
Exemplo n.º 15
0
        public void MethodNodeHasProperDefaultName()
        {
            MethodNode methodNode = new MethodNode();

            Assert.AreEqual("Method", methodNode.Name);
        }
Exemplo n.º 16
0
            /// <summary>
            /// Remove unused labels, i.e. labels that are not referenced.
            /// </summary>
            /// <param name="method">  the method to be updated </param>
            internal virtual void removeUnusedLabels(MethodNode method)
            {
                // Scan for all the used labels
                ISet <LabelNode> usedLabels = new HashSet <LabelNode>();

//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (java.util.ListIterator<?> lit = method.instructions.iterator(); lit.hasNext();)
                for (IEnumerator <object> lit = method.instructions.GetEnumerator(); lit.MoveNext();)
                {
                    AbstractInsnNode insn = (AbstractInsnNode)lit.Current;
                    if (insn.Type == JUMP_INSN)
                    {
                        JumpInsnNode jumpInsn = (JumpInsnNode)insn;
                        usedLabels.Add(jumpInsn.label);
                    }
                    else if (insn.Type == TABLESWITCH_INSN)
                    {
                        TableSwitchInsnNode tableSwitchInsn = (TableSwitchInsnNode)insn;
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (java.util.Iterator<?> it = tableSwitchInsn.labels.iterator(); it.hasNext();)
                        for (IEnumerator <object> it = tableSwitchInsn.labels.GetEnumerator(); it.MoveNext();)
                        {
                            LabelNode labelNode = (LabelNode)it.Current;
                            if (labelNode != null)
                            {
                                usedLabels.Add(labelNode);
                            }
                        }
                    }
                    else if (insn.Type == LOOKUPSWITCH_INSN)
                    {
                        LookupSwitchInsnNode loopupSwitchInsn = (LookupSwitchInsnNode)insn;
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (java.util.Iterator<?> it = loopupSwitchInsn.labels.iterator(); it.hasNext();)
                        for (IEnumerator <object> it = loopupSwitchInsn.labels.GetEnumerator(); it.MoveNext();)
                        {
                            LabelNode labelNode = (LabelNode)it.Current;
                            if (labelNode != null)
                            {
                                usedLabels.Add(labelNode);
                            }
                        }
                    }
                }

                // Remove all the label instructions not being identified in the scan
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (java.util.ListIterator<?> lit = method.instructions.iterator(); lit.hasNext();)
                for (IEnumerator <object> lit = method.instructions.GetEnumerator(); lit.MoveNext();)
                {
                    AbstractInsnNode insn = (AbstractInsnNode)lit.Current;
                    if (insn.Type == LABEL)
                    {
                        if (!usedLabels.Contains(insn))
                        {
//JAVA TO C# CONVERTER TODO TASK: .NET enumerators are read-only:
                            lit.remove();
                        }
                    }
                }
            }
Exemplo n.º 17
0
 public void ResetToNull()
 {
     this.lastClickedMethod    = null;
     this.lastClickedParameter = null;
     this.lastClickedProperty  = null;
 }
Exemplo n.º 18
0
            internal virtual bool analyseIfTestFloat(MethodNode method, AbstractInsnNode insn, AbstractInsnNode valueInsn, float testValue)
            {
                bool eliminateJump = false;

                AbstractInsnNode nextInsn = valueInsn.Next;

                if (nextInsn != null && (nextInsn.Opcode == Opcodes.FCMPL || nextInsn.Opcode == Opcodes.FCMPG))
                {
                    AbstractInsnNode nextNextInsn = nextInsn.Next;
                    if (nextNextInsn != null && nextNextInsn.Type == JUMP_INSN)
                    {
                        JumpInsnNode jumpInsn = (JumpInsnNode)nextNextInsn;
                        bool         doJump   = false;
                        switch (jumpInsn.Opcode)
                        {
                        case Opcodes.IFEQ:
                            if (isFloatValue(value))
                            {
                                doJump        = getFloatValue(value) == testValue;
                                eliminateJump = true;
                            }
                            break;

                        case Opcodes.IFNE:
                            if (isFloatValue(value))
                            {
                                doJump        = getFloatValue(value) != testValue;
                                eliminateJump = true;
                            }
                            break;

                        case Opcodes.IFLT:
                            if (isFloatValue(value))
                            {
                                doJump        = getFloatValue(value) < testValue;
                                eliminateJump = true;
                            }
                            break;

                        case Opcodes.IFGE:
                            if (isFloatValue(value))
                            {
                                doJump        = getFloatValue(value) >= testValue;
                                eliminateJump = true;
                            }
                            break;

                        case Opcodes.IFGT:
                            if (isFloatValue(value))
                            {
                                doJump        = getFloatValue(value) > testValue;
                                eliminateJump = true;
                            }
                            break;

                        case Opcodes.IFLE:
                            if (isFloatValue(value))
                            {
                                doJump        = getFloatValue(value) <= testValue;
                                eliminateJump = true;
                            }
                            break;
                        }

                        if (eliminateJump)
                        {
                            if (doJump)
                            {
                                // Replace the expression test by a fixed GOTO.
                                // The skipped instructions will be eliminated by dead code analysis.
                                method.instructions.set(insn, new JumpInsnNode(Opcodes.GOTO, jumpInsn.label));
                            }
                            else
                            {
                                method.instructions.remove(insn);
                            }
                            deleteUpToInsn = jumpInsn.Next;
                        }
                    }
                }

                return(eliminateJump);
            }
Exemplo n.º 19
0
 public MethodNodeCreator(ModuleDocumentNode modNode, TypeNode ownerNode, MethodDef method)
 {
     this.ownerNode  = ownerNode;
     this.methodNode = modNode.Context.DocumentTreeView.Create(method);
 }
Exemplo n.º 20
0
        public void ProcessMethodArgs(MethodNode mnode, bool nameonly)
        {
            BaseNode n;
            int paramnum = 0;

            List<string> argnames = ScrapeArgNames(mnode.file, mnode.line);

            foreach (string arg in mnode.arguments)
            {
                string type = ResolveType(arg, out n, true);
                string dtype;

                bool utf8magic = false;

                if ( type == "string" )
                    utf8magic = true;

                if (typeDict.TryGetValue(type, out dtype))
                {
                    type = dtype;
                }

                if (!nameonly && type == "bool")
                    sb.Append("[MarshalAs(UnmanagedType.I1)] ");

                if (n.Type() == typeof(PointerTypeNode))
                    sb.Append("ref ");

                string argname = argnames[paramnum].Trim();

                if (argname.Length == 0 || argname.EndsWith("*") || argname == "bool" || argname == "float" || argname == type || argname == "CSteamID" || argname == "int" || argname == "short" || argname == "uint32" || argname == "\"\"")
                    argname = "arg" + (paramnum + 1);

                if (argname.StartsWith("*") || argname.StartsWith("&"))
                    argname = argname.Substring(1);

                if (argname.StartsWith("*"))
                    argname = argname.Substring(1);

                if (type == "IntPtr" && !(argname.StartsWith("pCallback") || argname.StartsWith("pFunction")) )
                {
                    type = "byte[]";
                }

                if ( nameonly )
                {
                    if ( utf8magic )
                        sb.Append( "Encoding.Default.GetString( Encoding.UTF8.GetBytes( " );

                    sb.Append( argname /*+ ", "*/ );

                    if ( utf8magic )
                        sb.Append( " ) )" );

                    sb.Append( ", " );
                }
                else
                    sb.Append( type + " " + argname + ", " );

                paramnum++;
            }
        }
Exemplo n.º 21
0
        string GetSignatures(string json)
        {
            PosData posData = GetPosData(json);

            if (posData == null)
            {
                return(null);
            }

            MethodNode methodNode = null;

            SignatureHelp signatures = null;

            int methodIndex = 0;
            int parameterIndex;

            if (posData.SelectedNode != null)
            {
                // Get the signature for the method the cursor is on.
                // Check if the selected node is a method node.
                if (posData.SelectedNode.ElementAtOrDefault(0) is MethodNode)
                {
                    methodNode = (MethodNode)posData.SelectedNode[0];

                    // If the parameters of the method node is not selected and the parent is a method node,
                    // select the parent method node.
                    if (!methodNode.IsParametersSelected(posData.Caret) && posData.SelectedNode.ElementAtOrDefault(1) is MethodNode)
                    {
                        methodNode = (MethodNode)posData.SelectedNode[1];
                        // Get the index of the selected node.
                        parameterIndex = Array.IndexOf(methodNode.Parameters, posData.SelectedNode[0]);
                    }
                    else
                    {
                        if (methodNode.IsNameSelected(posData.Caret))
                        {
                            // If the name is selected, -1 will not highlight any parameters.
                            parameterIndex = -1;
                        }
                        else
                        {
                            // The last parameter is selected.
                            parameterIndex = methodNode.Parameters.Length;
                        }
                    }
                }
                else if (/*parser.Bav.SelectedNode.ElementAtOrDefault(0) is IExpressionNode
                          * &&*/posData.SelectedNode.ElementAtOrDefault(1) is MethodNode)
                {
                    methodNode = (MethodNode)posData.SelectedNode[1];
                    // Get the index of the selected node.
                    parameterIndex = Array.IndexOf(methodNode.Parameters, posData.SelectedNode[0]);
                }
                else
                {
                    parameterIndex = 0;
                }

                SignatureInformation information = null;
                if (methodNode != null)
                {
                    IMethod method = parserData.GetMethod(methodNode.Name);

                    if (method != null)
                    {
                        ParameterInformation[] parameterInfo = new ParameterInformation[method.Parameters.Length];
                        for (int i = 0; i < parameterInfo.Length; i++)
                        {
                            parameterInfo[i] = new ParameterInformation(
                                method.Parameters[i].GetLabel(false),
                                // Every value in the tree can potentially be null.
                                method.Wiki?.Parameters?.ElementAtOrDefault(i)?.Description
                                );
                        }

                        information = new SignatureInformation(
                            method.GetLabel(false),
                            // Get the method's documentation
                            method.Wiki?.Description,
                            // Get the parameter data
                            parameterInfo
                            //method.Wiki?.Parameters?.Select(v => v.ToParameterInformation())
                            //    .ToArray()
                            );
                    }
                }

                signatures = new SignatureHelp
                             (
                    new SignatureInformation[] { information },
                    methodIndex,
                    parameterIndex
                             );
            }

            return(JsonConvert.SerializeObject(signatures));
        }
Exemplo n.º 22
0
 public Executer(MethodNode nodeToExecute)
 {
     this.Rewind();
     this.m_callStack.Push(nodeToExecute);
 }
Exemplo n.º 23
0
        protected override void VisitMethodNode(MethodNode node)
        {
            AppendIndentation();
            AppendAccesType(node.Visibility);

            if (node.IsStatic)
            {
                Append("static ");
            }

            if (node.IsAbstract)
            {
                Append("abstract ");
            }

            if (node.IsVirtual)
            {
                Append("virtual ");
            }

            if (string.IsNullOrEmpty(node.ReturnType))
            {
                Append("void ");
            }
            else
            {
                Append(node.ReturnType);
            }

            Append(" ");
            Append(node.Name);

            if (node.TypeParameters != null && node.TypeParameters.Length > 0)
            {
                Append("<");
                for (var i = 0; i < node.TypeParameters.Length; i++)
                {
                    if (i != 0)
                    {
                        Append(", ");
                    }
                    Append(node.TypeParameters[i]);
                }
                Append(">");
            }

            Append("(");

            if (node.Parameters != null)
            {
                var isFirst = true;
                foreach (var p in node.Parameters)
                {
                    if (!isFirst)
                    {
                        Append(", ");
                    }

                    VisitParameterNode(p);

                    isFirst = false;
                }
            }

            Append(")");
            AppendLineEnding();

            if (node.TypeConstraints != null && node.TypeConstraints.Length > 0)
            {
                ++_indentation;

                for (var i = 0; i < node.TypeConstraints.Length; i++)
                {
                    AppendIndentation();
                    Append("where ");
                    Append(node.TypeConstraints[i].TypeParameterName);
                    Append(" : ");
                    if (node.TypeConstraints[i].HasStructConstraint)
                    {
                        Append("struct");
                        if (node.TypeConstraints[i].Constraints.Length > 0)
                        {
                            Append(", ");
                        }
                    }
                    for (var j = 0; j < node.TypeConstraints[i].Constraints.Length; j++)
                    {
                        if (j != 0)
                        {
                            Append(", ");
                        }
                        Append(node.TypeConstraints[i].Constraints[j]);
                    }
                    AppendLineEnding();
                }

                --_indentation;
            }

            AppendLine("{");
            ++_indentation;

            VisitMethodBody(node.Body);

            --_indentation;
            AppendLine("}");
            AppendLineEnding();
        }
Exemplo n.º 24
0
        public CentralServerNode load(SystemInfo systemInfo)
        {
            CentralServerNode centralServerNode = csnFactory.CreateExport().Value;

            centralServerNode.Properties = CentralServerProperties.From(systemInfo.CentralServer);

            DatabasesFolderNode databasesFolderNode = dfnFactory.CreateExport().Value;

            foreach (var database in systemInfo.Databases.OrderBy(db => db.Name))
            {
                DatabaseNode databaseNode = dfFactory.CreateExport().Value;
                databaseNode.DatabaseName = database.Name;
                if (database.Classes != null)
                {
                    foreach (var @class in database.Classes.OrderBy(c => c.Name))
                    {
                        var cn = new ClassNode(@class.Name, @class.Interface, @class.ParentClasses);
                        foreach (var f in @class.Fields.OrderBy(f => f.Name))
                        {
                            var fn = new FieldNode(f.Name, f.Type, f.Reference, f.IsArray);
                            cn.Children.Add(fn);
                        }
                        foreach (var m in @class.Methods.OrderBy(m => m.Name))
                        {
                            OrderedDictionary parameters = new OrderedDictionary();
                            foreach (var prop in m.Params)
                            {
                                parameters.Add(prop.Name, prop.Type);
                            }
                            var mn = new MethodNode(m.Name, m.ReturnType, parameters);
                            cn.Children.Add(mn);
                        }
                        databaseNode.Children.Add(cn);
                    }
                }
                databasesFolderNode.Children.Add(databaseNode);
            }

            centralServerNode.Children.Add(databasesFolderNode);

            DataServersFolderNode dataServersFolderNode = new DataServersFolderNode();

            foreach (var dataServer in systemInfo.DataServer)
            {
                DataServerNode dataServerNode = dsnFactory.CreateExport().Value;
                dataServerNode.Properties = DataServerProperties.From(dataServer);


                //DatabasesFolderNode databasesFolderNode2 = dfnFactory.CreateExport().Value;

                //connectionService.DatabasesChanged += delegate(object s, EventArgs e)
                //{
                //    databasesFolderNode2.Children.Clear();
                //    foreach (string database in connectionService.Databases)
                //    {
                //        DatabaseNode databaseNode = new DatabaseNode(database);
                //        databasesFolderNode2.Children.Add(databaseNode);
                //    }
                //};

                //foreach (string database in databasesList)
                //{
                //    DatabaseNode databaseNode = new DatabaseNode(database);
                //    databasesFolderNode2.Children.Add(databaseNode);
                //}
                //dataServerNode.Children.Add(databasesFolderNode2);

                dataServersFolderNode.Children.Add(dataServerNode);
            }
            centralServerNode.Children.Add(dataServersFolderNode);

            return(centralServerNode);
        }
Exemplo n.º 25
0
 protected virtual void VisitMethodNode(MethodNode node)
 {
     WalkMethodNode(node);
 }
Exemplo n.º 26
0
        public Tree GetChildren(string node)
        {
            ReferenceDescriptionCollection references;

            Byte[] continuationPoint;
            Tree   browserTree = new Tree();

            try
            {
                session.Browse(
                    null,
                    null,
                    node,
                    0u,
                    BrowseDirection.Forward,
                    ReferenceTypeIds.HierarchicalReferences,
                    true,
                    0,
                    out continuationPoint,
                    out references);

                if (references != null)
                {
                    foreach (var nodeReference in references)
                    {
                        ReferenceDescriptionCollection childReferences = null;
                        Byte[] childContinuationPoint;

                        session.Browse(
                            null,
                            null,
                            ExpandedNodeId.ToNodeId(nodeReference.NodeId, session.NamespaceUris),
                            0u,
                            BrowseDirection.Forward,
                            ReferenceTypeIds.HierarchicalReferences,
                            true,
                            0,
                            out childContinuationPoint,
                            out childReferences);

                        INode currentNode = null;
                        try
                        {
                            currentNode = session.ReadNode(ExpandedNodeId.ToNodeId(nodeReference.NodeId, session.NamespaceUris));
                        }
                        catch (Exception)
                        {
                            // skip this node
                            continue;
                        }

                        byte currentNodeAccessLevel   = 0;
                        byte currentNodeEventNotifier = 0;
                        bool currentNodeExecutable    = false;

                        VariableNode variableNode = currentNode as VariableNode;
                        if (variableNode != null)
                        {
                            currentNodeAccessLevel = variableNode.UserAccessLevel;
                            currentNodeAccessLevel = (byte)((uint)currentNodeAccessLevel & ~0x2);
                        }

                        ObjectNode objectNode = currentNode as ObjectNode;
                        if (objectNode != null)
                        {
                            currentNodeEventNotifier = objectNode.EventNotifier;
                        }

                        ViewNode viewNode = currentNode as ViewNode;
                        if (viewNode != null)
                        {
                            currentNodeEventNotifier = viewNode.EventNotifier;
                        }

                        MethodNode methodNode = currentNode as MethodNode;
                        if (methodNode != null)
                        {
                            currentNodeExecutable = methodNode.UserExecutable;
                        }

                        browserTree.currentView.Add(new ListNode()
                        {
                            id            = nodeReference.NodeId.ToString(),
                            NodeName      = nodeReference.DisplayName.Text.ToString(),
                            nodeClass     = nodeReference.NodeClass.ToString(),
                            accessLevel   = currentNodeAccessLevel.ToString(),
                            eventNotifier = currentNodeEventNotifier.ToString(),
                            executable    = currentNodeExecutable.ToString(),
                            children      = (references?.Count != 0),
                            ImageUrl      = (nodeReference.NodeClass.ToString() == "Variable") ? "folderOpen.jpg" : "folder.jpg"
                        });
                        if (browserTree.currentView[0].ImageUrl == null)
                        {
                            browserTree.currentView[0].ImageUrl = "";
                        }
                    }
                    if (browserTree.currentView.Count == 0)
                    {
                        INode currentNode = session.ReadNode(new NodeId(node));

                        byte currentNodeAccessLevel   = 0;
                        byte currentNodeEventNotifier = 0;
                        bool currentNodeExecutable    = false;

                        VariableNode variableNode = currentNode as VariableNode;

                        if (variableNode != null)
                        {
                            currentNodeAccessLevel = variableNode.UserAccessLevel;
                            currentNodeAccessLevel = (byte)((uint)currentNodeAccessLevel & ~0x2);
                        }

                        ObjectNode objectNode = currentNode as ObjectNode;

                        if (objectNode != null)
                        {
                            currentNodeEventNotifier = objectNode.EventNotifier;
                        }

                        ViewNode viewNode = currentNode as ViewNode;

                        if (viewNode != null)
                        {
                            currentNodeEventNotifier = viewNode.EventNotifier;
                        }

                        MethodNode methodNode = currentNode as MethodNode;

                        if (methodNode != null)
                        {
                            currentNodeExecutable = methodNode.UserExecutable;
                        }

                        browserTree.currentView.Add(new ListNode()
                        {
                            id            = node,
                            NodeName      = currentNode.DisplayName.Text.ToString(),
                            nodeClass     = currentNode.NodeClass.ToString(),
                            accessLevel   = currentNodeAccessLevel.ToString(),
                            eventNotifier = currentNodeEventNotifier.ToString(),
                            executable    = currentNodeExecutable.ToString(),
                            children      = false,
                            ImageUrl      = null
                        });
                    }
                }
                return(browserTree);
            }
            catch
            {
                Disconnect(session);
                return(null);
            }
        }
Exemplo n.º 27
0
 CreateMethodDefCommand(TypeNode ownerNode, MethodDefOptions options)
 {
     this.ownerNode = ownerNode;
     methodNode     = ownerNode.Create(options.CreateMethodDef(ownerNode.TypeDef.Module));
 }
Exemplo n.º 28
0
        public static ClassNode Parse(string sScript)
        {
            ArrayList aAllLines = new ArrayList();

            string[] aKeywords = new string[] { "for", "else if", "if", "else", "while", "goto", "gosub", "return" };
            //TODO: I don't handle keyword and a statement on the same line right now-
            //e.g. "if (true) blabla();" or "for (;;) put(1);"

            BaseNode  rootNode  = new BaseNode();
            ClassNode classNode = new ClassNode();

            rootNode.AppendChild("Class_01", classNode);
            BaseNode currentNode = classNode;

            //easier parsing if \r\n is replaced by \n
            sScript = sScript.Replace("\r\n", "\n");
            //also a little easier if script always ends with a \n
            if (!sScript.EndsWith("\n"))
            {
                sScript += "\n";
            }


            //structure will be [ScriptName:[MethodName:[LabelName:[clause:[clause]]]]]
            //Labels must be on top level in a method (e.g. not inside an if(){} clause)
            while (sScript.Length > 0)
            {
                //first divide into "lines" - EndOfLine represented by: return ; { or }
                string          sLine        = "";
                string          sDividerChar = "";
                MatchCollection matches      = Regex.Matches(sScript, "[^{};\\n]*[{};\\n]");
                foreach (Match m in matches)
                {
                    sLine        = sScript.Substring(0, m.Index + m.Length);
                    sDividerChar = m.Value.Substring(m.Value.Length - 1, 1);
                    if (sDividerChar == ";")
                    {
                        //must check if the ";" is inside parenthesis - if so, it doesn't count (e.g. "for(;;)")
                        //only when the number of "(" is the same as the number of ")", the ";" is outside
                        string sCheck    = sLine.Replace("(", "");
                        int    nNumRight = sLine.Length - sCheck.Length;
                        sCheck = sLine.Replace(")", "");
                        int nNumLeft = sLine.Length - sCheck.Length;
                        if (nNumRight != nNumLeft)
                        {
                            continue;
                        }
                    }
                    sScript = sScript.Remove(0, sLine.Length);
                    sLine   = sLine.Remove(sLine.Length - 1, 1);
                    break;
                }

                sLine = sLine.Trim();

                //handle if the line only consists of a { or }
                if (sLine.Length == 0)
                {
                    if (HandleNodeBorderChars(sDividerChar, ref currentNode))
                    {
                        continue;
                    }
                }

                //empty and remmed lines are ignored:
                if (sLine.Length == 0 || sLine.IndexOf("//") == 0)
                {
                    continue;
                }

                if (currentNode.GetType() == typeof(ClassNode))                 //.Depth == 1) //class level, i.e. where methods are defined
                {
                    //search for "on method([args])"
                    Match m = Regex.Match(sLine, "on\\s*\\w*\\s*[(][^()]*[)]");
                    if (m.Success)
                    {
                        string sMethod = m.Value.Replace("on ", "").Trim();
                        string sArgs   = sMethod.Remove(0, sMethod.IndexOf("("));
                        sMethod = sMethod.Substring(0, sMethod.IndexOf("("));

                        MethodNode methodNode = new MethodNode();
                        methodNode.DefineArguments(sArgs.Substring(1, sArgs.Length - 2));
                        currentNode.AppendChild(sMethod, methodNode);
                        currentNode = methodNode;
                        continue;
                    }
                }
                //separate code flow keywords/tokens from expressions
                if (sLine.IndexOf(":") == sLine.Length - 1)
                {
                    //it's a label. Labels can currently only occur on Method level
                    if (currentNode.GetType() != typeof(MethodNode))
                    {
                        throw new Exception("Labels must be defined in Method scope!");
                    }
                    //TODO: Labels can't be nodes - they're not defined with {}'s... More like an HTML anchor
                    //sLine.Substring(0,sLine.Length-2)
                }

                #region Check for keywords

                foreach (string sKeyword in aKeywords)
                {
                    //[^\\w]+*[( ]*
                    Match m = Regex.Match(sLine + " ", sKeyword + "[^\\w]+[( ]*");                 //"\\s*[(]*");
                    if (m.Success)
                    {
                        ChunkNode newNode = null;

                        string sArgs = GetStringWithinParenthesis(sLine);

                        switch (sKeyword)
                        {
                        case "for":
                            ForNode forNode = new ForNode();
                            forNode.SetConditions(sArgs);
                            newNode = forNode;
                            //With the current line seek method, the ";" in for(;;) forces us to look ahead in script
                            //TODO: lookahead for(;;)
                            break;

                        case "if":
                            if (sArgs == null)
                            {
                                throw new Exception("If statement incomplete");
                            }
                            IfNode ifNode = new IfNode();
                            ifNode.SetIfStatement(sArgs);
                            newNode = ifNode;
                            break;

                        case "else if":
                        case "else":
                            //is the current node an IfNode?
                            if (currentNode.GetType() != typeof(IfNode))
                            {
                                throw new Exception("\"" + sKeyword + "\" must come after an \"if\" statement");
                            }
                            IfNode elseifNode = new IfNode();
                            if (sKeyword == "else if")
                            {
                                //TODO: don't understand C# scopes... Why can't I define sArgs here too? Can't see any risk for confusion or mistakes!?
                                //And sometimes it's too slack:
                                //a member variable can have the same name as a variable in a method with no complaits,
                                //although that is clearly a mistake in most cases?
                                if (sArgs == null)
                                {
                                    throw new Exception("Else if statement incomplete");
                                }
                                elseifNode.SetIfStatement(sArgs);
                            }
                            IfNode oldIfNode = (IfNode)currentNode;
                            oldIfNode.SetNextIfNode(elseifNode);
                            newNode = elseifNode;
                            break;
                        }
                        if (newNode != null)
                        {
                            newNode.CloseNodeAfterNextLine = true;
                            currentNode.AppendChild(sKeyword, newNode);
                            currentNode = newNode;
                        }
                        break;
                    }
                }
                #endregion


                if (HandleNodeBorderChars(sDividerChar, ref currentNode))
                {
                    continue;
                }

                string         sStatement = sLine;
                ExpressionNode expNode    = new ExpressionNode();
                expNode.SetExpression(sStatement);
                currentNode.AppendChild(sStatement, expNode);

                //TODO: how to check nicely if ChunkNode is one of the base classes of currentNode?? This is ugly (?):
                try
                {
                    ChunkNode chunkNode = (ChunkNode)currentNode;
                    if (chunkNode.CloseNodeAfterNextLine)
                    {
                        currentNode = (BaseNode)currentNode.ParentNode;
                    }
                }
                catch
                {}
            }

//			System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
//			rootNode.AddToXml(doc);
//			doc.Save("Testing.xml");

            return(classNode);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Processes the specified root.
        /// </summary>
        /// <param name="file">The filename.</param>
        /// <param name="root">The root.</param>
        internal static void Process(string file, string root)
        {
            Console.WriteLine(file);

            if (!File.Exists(Path.Combine(root, file)))
                return;

            // Load file into string array
            string[] lines = File.ReadAllLines(Path.Combine(root, file));

            ClassNode rootNode = new ClassNode();
            List<ClassNode> classNodes = new List<ClassNode>();
            List<MethodNode> methodNodes = new List<MethodNode>();

            List<int> namespaces = new List<int>();
            List<int> usings = new List<int>();

            ClassNode currentNode = rootNode;
            bool incomment = false;

            // Analyze File
            for (int linenbr = 0; linenbr < lines.Length; linenbr++) {
                string trim = GetLine(lines, linenbr, ref incomment).Replace('\t', ' ');

                if (incomment)
                    continue;

                trim = StripWithInDoubleQuotes(trim);

                int skip = 0;

                if (string.IsNullOrEmpty(trim))
                    continue;
                else if (trim.StartsWith("#"))
                    continue;
                else if ((trim.StartsWith("extern ") || (trim.Contains(" extern "))) && !trim.Contains(" alias ")) {
                    int start = GetPreviousBlockEnd(lines, linenbr);
                    skip = GetNumberOfMethodDeclarationLines(lines, linenbr, false);
                    MethodNode node = new MethodNode(currentNode, start, linenbr + skip, linenbr);
                    methodNodes.Add(node);
                    currentNode.Methods.Add(node);
                }
                else if (trim.StartsWith("using ") && trim.Contains(";")) {
                    usings.Add(linenbr);
                }
                else if (trim.StartsWith("namespace ")) {
                    namespaces.Add(linenbr);
                }
                else if (trim.Contains(" class ") || (trim.StartsWith("class ")) ||
                         trim.Contains(" struct ") || (trim.StartsWith("struct "))) {
                    // Search backwards for the start of the class definition (might not be on the same line as class keyword)
                    int start = GetPreviousBlockEnd(lines, linenbr);

                    string className = GetClassName(lines, start, linenbr);

                    // Attempt to handle #else class definitions
                    if (className == currentNode.Name) {
                        currentNode.OtherDeclare.Add(linenbr);
                        continue;
                    }

                    // Find the last line of the class
                    int end = GetEndOfScope(lines, linenbr);

                    // Go up to parent
                    while (linenbr > currentNode.End)
                        currentNode = currentNode.Parent;

                    // Child
                    ClassNode child = new ClassNode(currentNode, start, end, linenbr);
                    classNodes.Add(child);
                    currentNode.Children.Add(child);
                    currentNode = child;
                    child.Name = className;
                }

                linenbr = linenbr + skip;

                // Go up to parent
                while (linenbr >= currentNode.End)
                    currentNode = currentNode.Parent;
            }

            // Mark all partial nodes
            foreach (ClassNode node in classNodes)
                if (node.Methods.Count != 0) {
                    node.Partial = true;
                    ClassNode upNode = node;
                    do {
                        upNode.Parent.Partial = true;
                        upNode = upNode.Parent;
                    } while (upNode != upNode.Parent);
                }

            // Create partial file
            if (methodNodes.Count != 0) {
                File.Copy(Path.Combine(root, file), Path.Combine(root, Path.GetFileNameWithoutExtension(file) + ".Original.cs"));

                string partialMosaFile = Path.Combine(root, file.Insert(file.Length - 2, "Mosa.Partial."));
                Console.WriteLine(">" + Path.GetFileName(partialMosaFile));
                CreatePartialFileForMosa(lines, rootNode, usings, namespaces, partialMosaFile);

                string partialMonoFile = Path.Combine(root, file.Insert(file.Length - 2, "Partial."));
                Console.WriteLine(">" + Path.GetFileName(partialMonoFile));
                CreatePartialFileForMono(lines, rootNode, usings, namespaces, partialMonoFile);

                // Modify source file
                CreateModifiedFile(lines, classNodes, methodNodes, Path.Combine(root, file));
            }
        }
Exemplo n.º 30
0
        public Node ReadNode(NodeId nodeId)
        {
            // build list of attributes.
            SortedDictionary<uint,DataValue> attributes = new SortedDictionary<uint,DataValue>();
            
            attributes.Add(Attributes.NodeId, null);
            attributes.Add(Attributes.NodeClass, null);
            attributes.Add(Attributes.BrowseName, null);
            attributes.Add(Attributes.DisplayName, null);
            attributes.Add(Attributes.Description, null);
            attributes.Add(Attributes.WriteMask, null);
            attributes.Add(Attributes.UserWriteMask, null);
            attributes.Add(Attributes.DataType, null);
            attributes.Add(Attributes.ValueRank, null);
            attributes.Add(Attributes.ArrayDimensions, null);
            attributes.Add(Attributes.AccessLevel, null);
            attributes.Add(Attributes.UserAccessLevel, null);
            attributes.Add(Attributes.Historizing, null);
            attributes.Add(Attributes.MinimumSamplingInterval, null);
            attributes.Add(Attributes.EventNotifier, null);
            attributes.Add(Attributes.Executable, null);
            attributes.Add(Attributes.UserExecutable, null);
            attributes.Add(Attributes.IsAbstract, null);
            attributes.Add(Attributes.InverseName, null);
            attributes.Add(Attributes.Symmetric, null);
            attributes.Add(Attributes.ContainsNoLoops, null);

            // build list of values to read.
            ReadValueIdCollection itemsToRead = new ReadValueIdCollection();

            foreach (uint attributeId in attributes.Keys)
            {
                ReadValueId itemToRead = new ReadValueId();

                itemToRead.NodeId      = nodeId;
                itemToRead.AttributeId = attributeId;
                
                itemsToRead.Add(itemToRead);
            }

            // read from server.
            DataValueCollection values = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            ResponseHeader responseHeader = Read(
                null,
                0,
                TimestampsToReturn.Neither,
                itemsToRead,
                out values, 
                out diagnosticInfos);
            
            ClientBase.ValidateResponse(values, itemsToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, itemsToRead);

            // process results.
            int? nodeClass = null;

            for (int ii = 0; ii < itemsToRead.Count; ii++)
            {
                uint attributeId = itemsToRead[ii].AttributeId;
                
                // the node probably does not exist if the node class is not found.
                if (attributeId == Attributes.NodeClass)
                {
                    if (!DataValue.IsGood(values[ii]))
                    {
                        throw ServiceResultException.Create(values[ii].StatusCode, ii, diagnosticInfos, responseHeader.StringTable);
                    }       
     
                    // check for valid node class.
                    nodeClass  = values[ii].Value as int?;

                    if (nodeClass == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not have a valid value for NodeClass: {0}.", values[ii].Value);
                    }
                }
                else
                {
                    if (!DataValue.IsGood(values[ii]))
                    {
                        // check for unsupported attributes.
                        if (values[ii].StatusCode == StatusCodes.BadAttributeIdInvalid)
                        {
                            continue;
                        }

                        // all supported attributes must be readable.
                        if (attributeId != Attributes.Value)
                        {
                            throw ServiceResultException.Create(values[ii].StatusCode, ii, diagnosticInfos, responseHeader.StringTable);
                        }
                    }      
                }

                attributes[attributeId] = values[ii];
            }

            Node node = null;
            DataValue value = null;

            switch ((NodeClass)nodeClass.Value)
            {
                default:
                {
                    throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not have a valid value for NodeClass: {0}.", nodeClass.Value);
                }

                case NodeClass.Object:
                {
                    ObjectNode objectNode = new ObjectNode();

                    value = attributes[Attributes.EventNotifier];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Object does not support the EventNotifier attribute.");
                    }

                    objectNode.EventNotifier = (byte)attributes[Attributes.EventNotifier].GetValue(typeof(byte));
                    node = objectNode;
                    break;
                }

                case NodeClass.ObjectType:
                {
                    ObjectTypeNode objectTypeNode = new ObjectTypeNode();

                    value = attributes[Attributes.IsAbstract];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "ObjectType does not support the IsAbstract attribute.");
                    }

                    objectTypeNode.IsAbstract = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));
                    node = objectTypeNode;
                    break;
                }

                case NodeClass.Variable:
                {
                    VariableNode variableNode = new VariableNode();
                    
                    // DataType Attribute
                    value = attributes[Attributes.DataType];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the DataType attribute.");
                    }

                    variableNode.DataType = (NodeId)attributes[Attributes.DataType].GetValue(typeof(NodeId));     

                    // ValueRank Attribute
                    value = attributes[Attributes.ValueRank];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the ValueRank attribute.");
                    }

                    variableNode.ValueRank = (int)attributes[Attributes.ValueRank].GetValue(typeof(int));                                      
                    
                    // ArrayDimensions Attribute
                    value = attributes[Attributes.ArrayDimensions];

                    if (value != null)
                    {
                        if (value.Value == null)
                        {
                            variableNode.ArrayDimensions = new uint[0];
                        }
                        else
                        {
                            variableNode.ArrayDimensions = (uint[])value.GetValue(typeof(uint[]));
                        }
                    }
                    
                    // AccessLevel Attribute
                    value = attributes[Attributes.AccessLevel];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the AccessLevel attribute.");
                    }

                    variableNode.AccessLevel = (byte)attributes[Attributes.AccessLevel].GetValue(typeof(byte));     
                    
                    // UserAccessLevel Attribute
                    value = attributes[Attributes.UserAccessLevel];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the UserAccessLevel attribute.");
                    }

                    variableNode.UserAccessLevel = (byte)attributes[Attributes.UserAccessLevel].GetValue(typeof(byte));     
                    
                    // Historizing Attribute
                    value = attributes[Attributes.Historizing];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Variable does not support the Historizing attribute.");
                    }

                    variableNode.Historizing = (bool)attributes[Attributes.Historizing].GetValue(typeof(bool));    
                    
                    // MinimumSamplingInterval Attribute
                    value = attributes[Attributes.MinimumSamplingInterval];

                    if (value != null)
                    {
                        variableNode.MinimumSamplingInterval = Convert.ToDouble(attributes[Attributes.MinimumSamplingInterval].Value);
                    }

                    node = variableNode;
                    break;
                }
                    
                case NodeClass.VariableType:
                {
                    VariableTypeNode variableTypeNode = new VariableTypeNode();

                    // IsAbstract Attribute
                    value = attributes[Attributes.IsAbstract];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "VariableType does not support the IsAbstract attribute.");
                    }

                    variableTypeNode.IsAbstract = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));
                    
                    // DataType Attribute
                    value = attributes[Attributes.DataType];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "VariableType does not support the DataType attribute.");
                    }

                    variableTypeNode.DataType = (NodeId)attributes[Attributes.DataType].GetValue(typeof(NodeId));     

                    // ValueRank Attribute
                    value = attributes[Attributes.ValueRank];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "VariableType does not support the ValueRank attribute.");
                    }

                    variableTypeNode.ValueRank = (int)attributes[Attributes.ValueRank].GetValue(typeof(int));                                      
                    
                    // ArrayDimensions Attribute
                    value = attributes[Attributes.ArrayDimensions];

                    if (value != null && value.Value != null)
                    {
                        variableTypeNode.ArrayDimensions = (uint[])attributes[Attributes.ArrayDimensions].GetValue(typeof(uint[]));
                    }
                    
                    node = variableTypeNode;
                    break;
                }
                    
                case NodeClass.Method:
                {
                    MethodNode methodNode = new MethodNode();

                    // Executable Attribute
                    value = attributes[Attributes.Executable];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Method does not support the Executable attribute.");
                    }

                    methodNode.Executable = (bool)attributes[Attributes.Executable].GetValue(typeof(bool));
                    
                    // UserExecutable Attribute
                    value = attributes[Attributes.UserExecutable];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Method does not support the UserExecutable attribute.");
                    }

                    methodNode.UserExecutable = (bool)attributes[Attributes.UserExecutable].GetValue(typeof(bool));

                    node = methodNode;
                    break;
                }
                    
                case NodeClass.DataType:
                {
                    DataTypeNode dataTypeNode = new DataTypeNode();

                    // IsAbstract Attribute
                    value = attributes[Attributes.IsAbstract];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "DataType does not support the IsAbstract attribute.");
                    }

                    dataTypeNode.IsAbstract = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));

                    node = dataTypeNode;
                    break;
                }
                    
                case NodeClass.ReferenceType:
                {
                    ReferenceTypeNode referenceTypeNode = new ReferenceTypeNode();

                    // IsAbstract Attribute
                    value = attributes[Attributes.IsAbstract];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "ReferenceType does not support the IsAbstract attribute.");
                    }

                    referenceTypeNode.IsAbstract = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));

                    // Symmetric Attribute
                    value = attributes[Attributes.Symmetric];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "ReferenceType does not support the Symmetric attribute.");
                    }

                    referenceTypeNode.Symmetric = (bool)attributes[Attributes.IsAbstract].GetValue(typeof(bool));

                    // InverseName Attribute
                    value = attributes[Attributes.InverseName];

                    if (value != null && value.Value != null)
                    {
                        referenceTypeNode.InverseName = (LocalizedText)attributes[Attributes.InverseName].GetValue(typeof(LocalizedText));
                    }
                    
                    node = referenceTypeNode;
                    break;
                }
                    
                case NodeClass.View:
                {
                    ViewNode viewNode = new ViewNode();

                    // EventNotifier Attribute
                    value = attributes[Attributes.EventNotifier];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "View does not support the EventNotifier attribute.");
                    }

                    viewNode.EventNotifier = (byte)attributes[Attributes.EventNotifier].GetValue(typeof(byte));
                    
                    // ContainsNoLoops Attribute
                    value = attributes[Attributes.ContainsNoLoops];

                    if (value == null)
                    {
                        throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "View does not support the ContainsNoLoops attribute.");
                    }

                    viewNode.ContainsNoLoops = (bool)attributes[Attributes.ContainsNoLoops].GetValue(typeof(bool));

                    node = viewNode;
                    break;
                }                    
            }
                
            // NodeId Attribute
            value = attributes[Attributes.NodeId];

            if (value == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not support the NodeId attribute.");
            }

            node.NodeId = (NodeId)attributes[Attributes.NodeId].GetValue(typeof(NodeId));
            node.NodeClass = (NodeClass)nodeClass.Value;

            // BrowseName Attribute
            value = attributes[Attributes.BrowseName];

            if (value == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not support the BrowseName attribute.");
            }

            node.BrowseName = (QualifiedName)attributes[Attributes.BrowseName].GetValue(typeof(QualifiedName));

            // DisplayName Attribute
            value = attributes[Attributes.DisplayName];

            if (value == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadUnexpectedError, "Node does not support the DisplayName attribute.");
            }

            node.DisplayName = (LocalizedText)attributes[Attributes.DisplayName].GetValue(typeof(LocalizedText));
    
            // Description Attribute
            value = attributes[Attributes.Description];

            if (value != null && value.Value != null)
            {
                node.Description = (LocalizedText)attributes[Attributes.Description].GetValue(typeof(LocalizedText));
            }

            // WriteMask Attribute
            value = attributes[Attributes.WriteMask];

            if (value != null)
            {
                node.WriteMask = (uint)attributes[Attributes.WriteMask].GetValue(typeof(uint));
            }

            // UserWriteMask Attribute
            value = attributes[Attributes.UserWriteMask];

            if (value != null)
            {
                node.WriteMask = (uint)attributes[Attributes.UserWriteMask].GetValue(typeof(uint));
            }
                
            return node;
        }
Exemplo n.º 31
0
        private RuntimeResult VisitMethodNode(MethodNode node, Context context)
        {
            string name = "anonymous";

            if (node.Token != null)
            {
                switch (node.Token.Type)
                {
                case TokenType.IDENTIFIER:
                    name = node.Token.Value.ToString();
                    break;

                case TokenType.PLUS:
                    name = "-add-";
                    break;

                case TokenType.MINUS:
                    name = "-sub-";
                    break;

                case TokenType.MULTIPLY:
                    name = "-mul-";
                    break;

                case TokenType.DIVIDE:
                    name = "-div-";
                    break;

                case TokenType.MODULUS:
                    name = "-mod-";
                    break;

                case TokenType.EXPONENT:
                    name = "-exp-";
                    break;

                case TokenType.STRING:
                    name = "-str-";
                    break;

                case TokenType.LEFT_SQB:
                    name = "-sst-";
                    break;

                case TokenType.LESS_THAN:
                    name = "-les-";
                    break;

                case TokenType.LESS_TOE:
                    name = "-lte-";
                    break;

                case TokenType.GREATER_THAN:
                    name = "-gre-";
                    break;

                case TokenType.GREATER_TOE:
                    name = "-gte-";
                    break;

                case TokenType.EQUALS_EQUALS:
                    name = "-eeq-";
                    break;

                case TokenType.NOT_EQUALS:
                    name = "-neq-";
                    break;

                case TokenType.BITWISE_AND:
                    name = "-ban-";
                    break;

                case TokenType.BITWISE_OR:
                    name = "-bor-";
                    break;

                case TokenType.BITWISE_XOR:
                    name = "-xor-";
                    break;

                case TokenType.COMPLEMENT:
                    name = "-com-";
                    break;

                case TokenType.EQUALS:
                    name = "-sse-";
                    break;

                case TokenType.LEFT_SHIFT:
                    name = "-lsh-";
                    break;

                case TokenType.RIGHT_SHIFT:
                    name = "-rsh-";
                    break;

                case TokenType.BOOLEAN_AND:
                    name = "-and-";
                    break;

                case TokenType.BOOLEAN_OR:
                    name = "-orr-";
                    break;

                case TokenType.BOOLEAN_NOT:
                    name = "-not-";
                    break;

                case TokenType.IN:
                    name = "-inn-";
                    break;
                }
            }
            Values.Value method = new Values.MethodValue(name, node.Parameters, node.Body, node.DefaultValues).SetPositionAndContext(node.Position, context);
            if (node.Token != null)
            {
                context.AddSymbol(name, method);
            }
            return(new RuntimeResult(method));
        }
Exemplo n.º 32
0
            /// <summary>
            /// Optimize the jumps from a method:
            /// - jumps to a "GOTO label" instruction
            ///   are replaced with a direct jump to "label";
            /// - a GOTO to the next instruction is deleted;
            /// - a GOTO to a RETURN or ATHROW instruction
            ///   is replaced with this RETURN or ATHROW instruction.
            /// </summary>
            /// <param name="method">  the method to be optimized </param>
            internal virtual void optimizeJumps(MethodNode method)
            {
//JAVA TO C# CONVERTER WARNING: Java wildcard generics have no direct equivalent in .NET:
//ORIGINAL LINE: for (java.util.ListIterator<?> lit = method.instructions.iterator(); lit.hasNext();)
                for (IEnumerator <object> lit = method.instructions.GetEnumerator(); lit.MoveNext();)
                {
                    AbstractInsnNode insn = (AbstractInsnNode)lit.Current;
                    if (insn.Type == JUMP_INSN)
                    {
                        JumpInsnNode     jumpInsn = (JumpInsnNode)insn;
                        LabelNode        label    = jumpInsn.label;
                        AbstractInsnNode target;
                        // while target == goto l, replace label with l
                        while (true)
                        {
                            target = label;
                            while (target != null && target.Opcode < 0)
                            {
                                target = target.Next;
                            }
                            if (target != null && target.Opcode == Opcodes.GOTO)
                            {
                                label = ((JumpInsnNode)target).label;
                            }
                            else
                            {
                                break;
                            }
                        }

                        // update target
                        jumpInsn.label = label;

                        bool removeJump = false;
                        if (jumpInsn.Opcode == Opcodes.GOTO)
                        {
                            // Delete a GOTO to the next instruction
                            AbstractInsnNode next = jumpInsn.Next;
                            while (next != null)
                            {
                                if (next == label)
                                {
                                    removeJump = true;
                                    break;
                                }
                                else if (next.Opcode >= 0)
                                {
                                    break;
                                }
                                next = next.Next;
                            }
                        }

                        if (removeJump)
                        {
//JAVA TO C# CONVERTER TODO TASK: .NET enumerators are read-only:
                            lit.remove();
                        }
                        else
                        {
                            // if possible, replace jump with target instruction
                            if (jumpInsn.Opcode == Opcodes.GOTO && target != null)
                            {
                                switch (target.Opcode)
                                {
                                case Opcodes.IRETURN:
                                case Opcodes.LRETURN:
                                case Opcodes.FRETURN:
                                case Opcodes.DRETURN:
                                case Opcodes.ARETURN:
                                case Opcodes.RETURN:
                                case Opcodes.ATHROW:
                                    // replace instruction with clone of target
                                    method.instructions.set(insn, target.clone(null));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
Exemplo n.º 33
0
        /// <summary>
        /// Sets the nodes in the control.
        /// </summary>
        public bool Update(Session session, NodeId methodId, bool inputArgs)
        {
            if (session == null)
            {
                throw new ArgumentNullException("session");
            }
            if (methodId == null)
            {
                throw new ArgumentNullException("methodId");
            }

            Clear();

            m_session = session;

            // find the method.
            MethodNode method = session.NodeCache.Find(methodId) as MethodNode;

            if (method == null)
            {
                return(false);
            }

            // select the property to find.
            QualifiedName browseName = null;

            if (inputArgs)
            {
                browseName = Opc.Ua.BrowseNames.InputArguments;
            }
            else
            {
                browseName = Opc.Ua.BrowseNames.OutputArguments;
            }

            // fetch the argument list.
            VariableNode argumentsNode =
                session.NodeCache.Find(methodId, ReferenceTypeIds.HasProperty, false, true, browseName) as VariableNode;

            if (argumentsNode == null)
            {
                return(false);
            }

            // read the value from the server.
            DataValue value = m_session.ReadValue(argumentsNode.NodeId);

            ExtensionObject[] argumentsList = value.Value as ExtensionObject[];

            if (argumentsList != null)
            {
                for (int ii = 0; ii < argumentsList.Length; ii++)
                {
                    AddItem(argumentsList[ii].Body as Argument);
                }
            }

            AdjustColumns();

            return(ItemsLV.Items.Count > 0);
        }
Exemplo n.º 34
0
 internal virtual bool analyseIfTestInt(MethodNode method, AbstractInsnNode insn)
 {
     return(analyseIfTestInt(method, insn, insn, null));
 }
Exemplo n.º 35
0
        public BaseNode AddMethod(string id, string name, string ret, string virt, string file, string line)
        {
            MethodNode methodn = new MethodNode(id, name, ret, virt, file, line);

            nodemap.Add(id, methodn);
            return methodn;
        }
Exemplo n.º 36
0
        static void ProcessFunction(IASTNode functionCall, bool inSelect)
        {
            MethodNode methodNode = (MethodNode)functionCall;

            methodNode.Resolve(inSelect);
        }
Exemplo n.º 37
0
        private SyntaxNode Node(SyntaxType parent, int start, int end, List <Token> tokens, List <Error> compileErrors)
        {
            switch (parent)
            {
            case SyntaxType.Program:
            {
                SyntaxNode node = new ProgramNode();
                for (var i = start; i < end; i++)
                {
                    switch (tokens[i].Type)
                    {
                    case TokenType.ClassDeclaration:
                    {
                        var newStart = i + 1;
                        var left     = 1;
                        var right    = 0;
                        while (left != right)
                        {
                            i++;
                            if (i >= end)
                            {
                                compileErrors.Add(new Error("Missing end of class declaration"));

                                return(null);
                            }
                            switch (tokens[i].Type)
                            {
                            case TokenType.ClassDeclaration:
                            case TokenType.InterfaceDeclaration:
                                left++;
                                break;

                            case TokenType.ClassEndDeclaration:
                                right++;
                                break;
                            }
                        }
                        var childNode = Node(SyntaxType.Class, newStart, i, tokens, compileErrors);
                        if (childNode == null)
                        {
                            return(null);
                        }
                        node.Nodes.Add(childNode);
                        break;
                    }

                    case TokenType.InterfaceDeclaration:
                    {
                        var newStart = i + 1;
                        var left     = 1;
                        var right    = 0;
                        while (left != right)
                        {
                            i++;
                            if (i >= end)
                            {
                                compileErrors.Add(new Error("Missing end of interface declaration"));

                                return(null);
                            }
                            switch (tokens[i].Type)
                            {
                            case TokenType.ClassDeclaration:
                            case TokenType.InterfaceDeclaration:
                                left++;
                                break;

                            case TokenType.ClassEndDeclaration:
                                right++;
                                break;
                            }
                        }
                        var childNode = Node(SyntaxType.Interface, newStart, i, tokens, compileErrors);
                        if (childNode == null)
                        {
                            return(null);
                        }
                        node.Nodes.Add(childNode);
                        break;
                    }

                    default:
                    {
                        if (IsTokenWhiteSpace(tokens[i]))
                        {
                            continue;
                        }

                        compileErrors.Add(new Error("Unexpected expression in program body"));

                        return(null);
                    }
                    }
                }
                return(node);
            }

            case SyntaxType.Class:
            {
                SyntaxNode node = new ClassNode(tokens[start - 1], tokens[end]);
                for (var i = start; i < end; i++)
                {
                    switch (tokens[i].Type)
                    {
                    case TokenType.MethodDeclaration:
                    {
                        var newStart = i + 1;
                        var left     = 1;
                        var right    = 0;
                        while (left != right)
                        {
                            i++;
                            if (i >= end)
                            {
                                compileErrors.Add(new Error("Missing end of method declaration"));

                                return(null);
                            }
                            switch (tokens[i].Type)
                            {
                            case TokenType.MethodDeclaration:
                            case TokenType.MainMethodDeclaration:
                                left++;
                                break;

                            case TokenType.MethodEndDeclaration:
                                right++;
                                break;
                            }
                        }
                        var childNode = Node(SyntaxType.MethodDeclaring, newStart, i, tokens, compileErrors);
                        if (childNode == null)
                        {
                            return(null);
                        }
                        node.Nodes.Add(childNode);
                        break;
                    }

                    case TokenType.MainMethodDeclaration:
                    {
                        var newStart = i + 1;
                        var left     = 1;
                        var right    = 0;
                        while (left != right)
                        {
                            i++;
                            if (i >= end)
                            {
                                compileErrors.Add(new Error("Missing end of main method declaration"));
                                return(null);
                            }
                            switch (tokens[i].Type)
                            {
                            case TokenType.MethodDeclaration:
                            case TokenType.MainMethodDeclaration:
                                left++;
                                break;

                            case TokenType.MethodEndDeclaration:
                                right++;
                                break;
                            }
                        }
                        var childNode = Node(SyntaxType.MainMethodDeclaring, newStart, i, tokens, compileErrors);
                        if (childNode == null)
                        {
                            return(null);
                        }
                        node.Nodes.Add(childNode);
                        break;
                    }

                    default:
                    {
                        if (IsTokenWhiteSpace(tokens[i]))
                        {
                            continue;
                        }

                        compileErrors.Add(new Error("Unexpected expression in class body"));

                        return(null);
                    }
                    }
                }
                return(node);
            }

            case SyntaxType.Interface:
            {
                SyntaxNode node = new InterfaceNode(tokens[start - 1], tokens[end]);
                for (var i = start; i < end; i++)
                {
                    if (tokens[i].Type == TokenType.MethodDeclaration)
                    {
                        node.Nodes.Add(new InterfaceMethodNode(tokens[i]));
                    }
                    else if (IsTokenWhiteSpace(tokens[i]))
                    {
                    }
                    else
                    {
                        compileErrors.Add(new Error("Unexpected expression in interface body"));

                        return(null);
                    }
                }
                return(node);
            }

            case SyntaxType.MethodDeclaring:
            case SyntaxType.MainMethodDeclaring:
            {
                SyntaxNode node = new MethodNode(tokens[start - 1], tokens[end], parent == SyntaxType.MainMethodDeclaring);
                Node(parent, start, end, tokens, compileErrors, node, "method");

                return(node);
            }

            case SyntaxType.Switch:
            {
                SyntaxNode node = new SwitchNode(tokens[start - 1], tokens[end]);
                Node(parent, start, end, tokens, compileErrors, node, "switch");

                return(node);
            }

            case SyntaxType.SwitchCase:
            {
                SyntaxNode node = new SwitchCase(tokens[start - 1], tokens[start - 1].Type == TokenType.SwitchDefaultCase);
                Node(parent, start, end, tokens, compileErrors, node, "switch case");

                return(node);
            }

            case SyntaxType.IfTruePart:
            {
                SyntaxNode node = new IfTrueNode(tokens[start - 1].Childs[0]);
                Node(parent, start, end, tokens, compileErrors, node, "if");

                return(node);
            }

            case SyntaxType.IfFalsePart:
            {
                SyntaxNode node = new IfElseNode();
                Node(parent, start, end, tokens, compileErrors, node, "else");

                return(node);
            }

            case SyntaxType.ElifPart:
            {
                SyntaxNode node = new ElifNode(tokens[start - 1].Childs[0]);
                Node(parent, start, end, tokens, compileErrors, node, "else-if");

                return(node);
            }

            case SyntaxType.For:
            {
                SyntaxNode node = new ForNode(tokens[start - 1], tokens[end]);
                Node(parent, start, end, tokens, compileErrors, node, "for");

                return(node);
            }

            case SyntaxType.Foreach:
            {
                SyntaxNode node = new ForeachNode(tokens[start - 1], tokens[end]);
                Node(parent, start, end, tokens, compileErrors, node, "foreach");

                return(node);
            }

            case SyntaxType.While:
            {
                SyntaxNode node = new WhileNode(tokens[start - 1].Childs[0]);
                Node(parent, start, end, tokens, compileErrors, node, "while");

                return(node);
            }

            case SyntaxType.DoWhile:
            {
                SyntaxNode node = new DoWhileNode(tokens[end].Childs[0]);
                Node(parent, start, end, tokens, compileErrors, node, "do-while");

                return(node);
            }

            default:
            {
                compileErrors.Add(new Error("Not implemented parser behaviour"));

                return(null);
            }
            }
        }
Exemplo n.º 38
0
        public void checkParentMethodOnMe(MethodNode my_method, MethodNode parent_method, TypeNode child, TypeNode parent, NamespaceNode currentNamespace)
        {
            if (my_method.evaluated)
            {
                return;
            }
            if (parent is InterfaceTypeNode)
            {
                if (my_method.Modifier != null)
                {
                    if (!validateModifier(my_method.Modifier, TokenType.RW_VIRTUAL, TokenType.RW_ABSTRACT))
                    {
                        Utils.ThrowError("Modifier: " + my_method.Modifier.token.lexeme + " can't be applied to method: "
                                         + buildMethodName(my_method.methodHeaderNode) + " [" + currentNamespace.Identifier.Name + "] " + my_method.Modifier.token.getLine());
                    }
                }
            }
            else if (parent is ClassTypeNode)
            {
                var childMethodName  = child.Identifier.Name + "." + buildMethodName(my_method.methodHeaderNode);
                var parentMethodName = parent.Identifier.Name + "." + buildMethodName(parent_method.methodHeaderNode);
                if (validateModifier(parent_method.Modifier, TokenType.RW_ABSTRACT, TokenType.RW_OVERRIDE, TokenType.RW_VIRTUAL))
                {
                    if (validateModifier(my_method.Modifier, TokenType.RW_OVERRIDE))
                    {
                        if (my_method.encapsulation.token.type == parent_method.encapsulation.token.type)
                        {
                            my_method.evaluated = true;
                        }
                    }
                    else
                    {
                        Utils.ThrowError("'" + childMethodName + "' hides inherited member '" + parentMethodName + "'. To make the current member override that " +
                                         "implementation, add the override keyword. [" + currentNamespace.Identifier.Name + "] " + my_method.token.getLine());
                    }
                }
                else
                {
                }

                // if(!validateModifier(my_method.Modifier,TokenType.RW_OVERRIDE))
                //     Utils.ThrowError("'"+childMethodName+"' hides inherited member '"+parentMethodName+"'. To make the current member override that "+
                //     "implementation, add the override keyword. ["+currentNamespace.Identifier.Name+"] "+my_method.token.getLine());
                if (my_method.statemetBlock == null)
                {
                    Utils.ThrowError("'" + childMethodName + "' must declare a body because it is not marked abstract ["
                                     + currentNamespace.Identifier.Name + "] " + my_method.token.getLine());
                }
                // if(!validateModifier(parent_method.Modifier,TokenType.RW_VIRTUAL,TokenType.RW_ABSTRACT))
                //     Utils.ThrowError("'"+childMethodName+"': cannot override inherited member '"+
                //     parentMethodName+"' because it is not marked virtual, abstract. ["+currentNamespace.Identifier.Name+"] "+my_method.token.getLine());
                if (parent_method.encapsulation.type == TokenType.RW_PRIVATE)
                {
                    Utils.ThrowError("'" + childMethodName + "': no suitable method found to override. [" + currentNamespace.Identifier.Name + "] " + my_method.token.getLine());
                }
                if (!my_method.encapsulation.Equals(parent_method.encapsulation))
                {
                    Utils.ThrowError("'" + childMethodName + "': cannot change access modifiers when overriding '"
                                     + parent_method.encapsulation.token.lexeme + "' inherited member '" + parentMethodName + "' [" + currentNamespace.Identifier.Name + "] " + my_method.token.getLine());
                }
            }

            if (!my_method.methodHeaderNode.returnType.Equals(parent_method.methodHeaderNode.returnType))
            {
                Utils.ThrowError("Method: " + buildMethodName(my_method.methodHeaderNode)
                                 + " hide method " + parent.ToString() + "." + buildMethodName(parent_method.methodHeaderNode)
                                 + ". Not the same return type. [" + currentNamespace.Identifier.Name + "] " + my_method.token.getLine());
            }
            my_method.evaluated = true;
        }
Exemplo n.º 39
0
        public void ProcessVirtualMethod(MethodNode mnode, ClassNode cnode)
        {
            if (mnode.virt == 1)
            {
                BaseNode n;
                bool passtypeasparam = false;
                bool utf8magic = false;

                string type = ResolveType(mnode.ret, out n, true);
                string dtype;

                if (type == "CSteamID")
                {
                    passtypeasparam = true;
                }

                if(type == "string")
                {
                    utf8magic = true;
                }

                if (typeDict.TryGetValue(type, out dtype))
                {
                    type = dtype;
                }

                if (type.StartsWith("I", StringComparison.InvariantCulture) && mnode.name.StartsWith("Get", StringComparison.InvariantCulture) && (cnode.name.StartsWith("ISteamClient") || cnode.name.StartsWith("IClientEngine")))
                    type = "IntPtr";

                string mname = mnode.name;
                string delname = mname;
                int mc;

                if (classmethods.TryGetValue(mname, out mc))
                {
                    classmethods[mname] = mc + 1;
                    delname = delname + mc.ToString();
                } else {
                    classmethods[mname] = 1;
                }

                sb.Append(new String('\t', level) + "[UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate ");

                if (passtypeasparam)
                {
                    sb.Append("void");
                }
                else
                {
                    sb.Append(type);
                }

                sb.Append(" Native" + delname + "(IntPtr thisobj, ");

                if (passtypeasparam)
                {
                    sb.Append("ref " + type + " ret, ");
                }

                ProcessMethodArgs(mnode, false);

                sb.Remove(sb.Length - 2, 2);

                sb.AppendLine(");");

                sb.Append(new String('\t', level));

                if (type == "bool")
                    sb.Append("[return: MarshalAs(UnmanagedType.I1)] ");

                sb.Append("public " + type + " " + mname + "(");

                ProcessMethodArgs(mnode, false);

                if (mnode.arguments.Count > 0)
                    sb.Remove(sb.Length - 2, 2);

                sb.Append(") { ");

                if (passtypeasparam)
                {
                    sb.Append(type + " ret = 0; ");
                }
                
                sb.Append("var call = this.GetFunction<Native" + delname + ">(this.Functions." + delname + "); ");

                if (type != "void" && !passtypeasparam)
                {
                    sb.Append("return ");

                    if(utf8magic)
                    {
                        sb.Append("Encoding.UTF8.GetString( Encoding.Default.GetBytes( ");
                    }
                }

                sb.Append("call(this.ObjectAddress, ");

                if (passtypeasparam)
                {
                    sb.Append("ref ret, ");
                }

                ProcessMethodArgs(mnode, true);
                sb.Remove(sb.Length - 2, 2);

                if (utf8magic)
                {
                    sb.Append(") ) ");
                }

                sb.Append("); ");

                if (passtypeasparam)
                {
                    sb.Append("return ret; ");
                }

                sb.AppendLine("}");
                sb.AppendLine();
            }
        }