Ejemplo n.º 1
0
        public static void PatchCheckFlags(List <CodeInstruction> codes, int occurance, MethodInfo method)
        {
            Assertion.Assert(mDrawMesh != null, "mDrawMesh!=null failed");
            Assertion.Assert(fNodeMaterial != null, "fNodeMaterial!=null failed");
            Assertion.Assert(fNodeMesh != null, "fNodeMesh!=null failed");
            Assertion.Assert(mCalculateMaterial != null, "mCalculateMaterial!=null failed");
            Assertion.Assert(mCalculateMesh != null, "mCalculateMesh!=null failed");
            Assertion.Assert(mCheckRenderDistance != null, "mCheckRenderDistance!=null failed");
            Assertion.Assert(mShouldContinueMedian != null, "mShouldContinueMedian!=null failed");

            int index = 0;

            // returns the position of First DrawMesh after index.
            index = SearchInstruction(codes, new CodeInstruction(OpCodes.Call, mDrawMesh), index, counter: occurance);
            Assertion.Assert(index != 0, "index!=0");


            // find ldfld node.m_nodeMaterial
            index = SearchInstruction(codes, new CodeInstruction(OpCodes.Ldfld, fNodeMaterial), index, dir: -1);
            int insertIndex3 = index + 1;

            // fine node.m_NodeMesh

            /*  IL_07ac: ldloc.s      node_V_16
             *  IL_07ae: ldfld        class [UnityEngine]UnityEngine.Mesh NetInfo/Node::m_nodeMesh
             */
            index = SearchInstruction(codes, new CodeInstruction(OpCodes.Ldfld, fNodeMesh), index, dir: -1);
            int insertIndex2 = index + 1;

            // find: if (cameraInfo.CheckRenderDistance(data.m_position, node.m_lodRenderDistance))

            /* IL_0627: callvirt instance bool RenderManager CameraInfo::CheckRenderDistance(Vector3, float32)
             * IL_062c brfalse      IL_07e2 */
            index = SearchInstruction(codes, new CodeInstruction(OpCodes.Callvirt, mCheckRenderDistance), index, dir: -1);
            int insertIndex1 = index + 1;                                                               // at this point boloean is in stack

            CodeInstruction LDArg_NodeID    = GetLDArg(method, "nodeID");                               // push nodeID into stack
            CodeInstruction LDLoc_segmentID = BuildSegnentLDLocFromPrevSTLoc(codes, index, counter: 1); // push segmentID into stack

            {                                                                                           // Insert material = CalculateMaterial(material, nodeID, segmentID)
                var newInstructions = new[] {
                    LDArg_NodeID,
                    LDLoc_segmentID,
                    new CodeInstruction(OpCodes.Call, mCalculateMaterial), // call Material CalculateMaterial(material, nodeID, segmentID).
                };
                InsertInstructions(codes, newInstructions, insertIndex3);
            }

            { // Insert material = CalculateMesh(mesh, nodeID, segmentID)
                var newInstructions = new[] {
                    LDArg_NodeID,
                    LDLoc_segmentID,
                    new CodeInstruction(OpCodes.Call, mCalculateMesh), // call Mesh CalculateMesh(mesh, nodeID, segmentID).
                };
                InsertInstructions(codes, newInstructions, insertIndex2);
            }

            { // Insert ShouldHideCrossing(nodeID, segmentID)
                var newInstructions = new[] {
                    LDArg_NodeID,
                    LDLoc_segmentID,
                    new CodeInstruction(OpCodes.Call, mShouldContinueMedian), // call Material mShouldHideCrossing(nodeID, segmentID).
                    new CodeInstruction(OpCodes.Or)
                };

                InsertInstructions(codes, newInstructions, insertIndex1);
            } // end block
        }     // end method
Ejemplo n.º 2
0
        static PsiLexer()
        {
            OurKeywordTextMap[PsiTokenType.ABSTRACT]      = "abstract";
            OurKeywordTextMap[PsiTokenType.ERRORHANDLING] = "errorhandling";
            OurKeywordTextMap[PsiTokenType.EXTRAS]        = "extras";
            OurKeywordTextMap[PsiTokenType.GET]           = "get";
            OurKeywordTextMap[PsiTokenType.GETTER]        = "getter";
            OurKeywordTextMap[PsiTokenType.OPTIONS]       = "options";
            OurKeywordTextMap[PsiTokenType.INTERFACE]     = "interface";
            OurKeywordTextMap[PsiTokenType.INTERFACES]    = "interfaces";
            OurKeywordTextMap[PsiTokenType.PRIVATE]       = "private";
            OurKeywordTextMap[PsiTokenType.PATHS]         = "paths";
            OurKeywordTextMap[PsiTokenType.RETURN_TYPE]   = "returnType";
            OurKeywordTextMap[PsiTokenType.ROLE_KEYWORD]  = "ROLE";
            OurKeywordTextMap[PsiTokenType.NULL_KEYWORD]  = "null";
            OurKeywordTextMap[PsiTokenType.LIST_KEYWORD]  = "LIST";
            OurKeywordTextMap[PsiTokenType.SEP_KEYWORD]   = "SEP";

            OurTokenTextMap[PsiTokenType.LPARENTH]     = "(";
            OurTokenTextMap[PsiTokenType.RPARENTH]     = ")";
            OurTokenTextMap[PsiTokenType.LBRACE]       = "{";
            OurTokenTextMap[PsiTokenType.RBRACE]       = "}";
            OurTokenTextMap[PsiTokenType.LBRACKET]     = "[";
            OurTokenTextMap[PsiTokenType.RBRACKET]     = "]";
            OurTokenTextMap[PsiTokenType.SEMICOLON]    = ";";
            OurTokenTextMap[PsiTokenType.COMMA]        = ",";
            OurTokenTextMap[PsiTokenType.DOT]          = ".";
            OurTokenTextMap[PsiTokenType.EQ]           = "=";
            OurTokenTextMap[PsiTokenType.GT]           = ">";
            OurTokenTextMap[PsiTokenType.LT]           = "<";
            OurTokenTextMap[PsiTokenType.EXCL]         = "!";
            OurTokenTextMap[PsiTokenType.TILDE]        = "~";
            OurTokenTextMap[PsiTokenType.AT]           = "@";
            OurTokenTextMap[PsiTokenType.SHARP]        = "#";
            OurTokenTextMap[PsiTokenType.BACK_QUOTE]   = "`";
            OurTokenTextMap[PsiTokenType.QUEST]        = "?";
            OurTokenTextMap[PsiTokenType.COLON]        = ":";
            OurTokenTextMap[PsiTokenType.PLUS]         = "+";
            OurTokenTextMap[PsiTokenType.MINUS]        = "-";
            OurTokenTextMap[PsiTokenType.ASTERISK]     = "*";
            OurTokenTextMap[PsiTokenType.DIV]          = "/";
            OurTokenTextMap[PsiTokenType.AND]          = "&";
            OurTokenTextMap[PsiTokenType.OR]           = "|";
            OurTokenTextMap[PsiTokenType.XOR]          = "^";
            OurTokenTextMap[PsiTokenType.PERC]         = "%";
            OurTokenTextMap[PsiTokenType.EQEQ]         = "==";
            OurTokenTextMap[PsiTokenType.LE]           = "<=";
            OurTokenTextMap[PsiTokenType.GE]           = ">=";
            OurTokenTextMap[PsiTokenType.NE]           = "!=";
            OurTokenTextMap[PsiTokenType.ANDAND]       = "&&";
            OurTokenTextMap[PsiTokenType.OROR]         = "||";
            OurTokenTextMap[PsiTokenType.PLUSPLUS]     = "++";
            OurTokenTextMap[PsiTokenType.MINUSMINUS]   = "--";
            OurTokenTextMap[PsiTokenType.LTLT]         = "<<";
            OurTokenTextMap[PsiTokenType.GTGT]         = ">>";
            OurTokenTextMap[PsiTokenType.PLUSEQ]       = "+=";
            OurTokenTextMap[PsiTokenType.MINUSEQ]      = "-=";
            OurTokenTextMap[PsiTokenType.ASTERISKEQ]   = "*=";
            OurTokenTextMap[PsiTokenType.DIVEQ]        = "/=";
            OurTokenTextMap[PsiTokenType.ANDEQ]        = "&=";
            OurTokenTextMap[PsiTokenType.OREQ]         = "|=";
            OurTokenTextMap[PsiTokenType.XOREQ]        = "^=";
            OurTokenTextMap[PsiTokenType.PERCEQ]       = "%=";
            OurTokenTextMap[PsiTokenType.LTLTEQ]       = "<<=";
            OurTokenTextMap[PsiTokenType.GTGTEQ]       = ">>=";
            OurTokenTextMap[PsiTokenType.DOUBLE_COLON] = "::";
            OurTokenTextMap[PsiTokenType.DOUBLE_QUEST] = "??";
            OurTokenTextMap[PsiTokenType.ARROW]        = "->";
            OurTokenTextMap[PsiTokenType.LAMBDA_ARROW] = "=>";

            for (int i = 0; i < OurHash.Length; i++)
            {
                OurHash[i] = PsiTokenType.IDENTIFIER;
            }
            for (IDictionaryEnumerator ide = keywords.GetEnumerator(); ide.MoveNext();)
            {
                ushort hash = CalcHash((string)ide.Entry.Key);
                Assertion.Assert(OurHash[hash] == PsiTokenType.IDENTIFIER,
                                 "The condition (ourHash[hash] == PsiTokenType.IDENTIFIER) is false.");
                OurHash[hash] = (TokenNodeType)ide.Entry.Value;
            }
        }
Ejemplo n.º 3
0
 public void Regress_Mutation_TrailingPartMustMatch()
 {
     Assertion.Assert(!TypeLoader.IsPartialTypeNameMatch("net.r_eg.IeXod.Tasks.Csc", "Vbc"));
 }
Ejemplo n.º 4
0
        /// <summary>
        /// Amazingly sophisticated :) helper function to determine if the set of ITaskItems returned from
        /// a task match the expected set of ITaskItems.  It can also check that the ITaskItems have the expected
        /// metadata, and that the ITaskItems are returned in the correct order.
        ///
        /// The "expectedItemsString" is a formatted way of easily specifying which items you expect to see.
        /// The format is:
        ///
        ///         itemspec1 :   metadataname1=metadatavalue1 ; metadataname2=metadatavalue2 ; ...
        ///         itemspec2 :   metadataname3=metadatavalue3 ; metadataname4=metadatavalue4 ; ...
        ///         itemspec3 :   metadataname5=metadatavalue5 ; metadataname6=metadatavalue6 ; ...
        ///
        /// (Each item needs to be on its own line.)
        ///
        /// </summary>
        /// <param name="expectedItemsString"></param>
        /// <param name="actualItems"></param>
        /// <param name="orderOfItemsShouldMatch"></param>
        /// <owner>RGoel</owner>
        static internal void AssertItemsMatch(string expectedItemsString, ITaskItem[] actualItems, bool orderOfItemsShouldMatch)
        {
            List <ITaskItem> expectedItems = ParseExpectedItemsString(expectedItemsString);

            // Form a string of expected item specs.  For logging purposes only.
            StringBuilder expectedItemSpecs = new StringBuilder();

            foreach (ITaskItem expectedItem in expectedItems)
            {
                if (expectedItemSpecs.Length > 0)
                {
                    expectedItemSpecs.Append("; ");
                }

                expectedItemSpecs.Append(expectedItem.ItemSpec);
            }

            // Form a string of expected item specs.  For logging purposes only.
            StringBuilder actualItemSpecs = new StringBuilder();

            foreach (ITaskItem actualItem in actualItems)
            {
                if (actualItemSpecs.Length > 0)
                {
                    actualItemSpecs.Append("; ");
                }

                actualItemSpecs.Append(actualItem.ItemSpec);
            }

            bool outOfOrder = false;

            // Loop through all the actual items.
            for (int actualItemIndex = 0; actualItemIndex < actualItems.Length; actualItemIndex++)
            {
                ITaskItem actualItem = actualItems[actualItemIndex];

                // Loop through all the expected items to find one with the same item spec.
                ITaskItem expectedItem = null;
                int       expectedItemIndex;
                for (expectedItemIndex = 0; expectedItemIndex < expectedItems.Count; expectedItemIndex++)
                {
                    if (expectedItems[expectedItemIndex].ItemSpec == actualItem.ItemSpec)
                    {
                        expectedItem = expectedItems[expectedItemIndex];

                        // If the items are expected to be in the same order, then the expected item
                        // should always be found at index zero, because we remove items from the expected
                        // list as we find them.
                        if ((expectedItemIndex != 0) && (orderOfItemsShouldMatch))
                        {
                            outOfOrder = true;
                        }

                        break;
                    }
                }

                Assertion.Assert(String.Format("Item '{0}' was returned but not expected.", actualItem.ItemSpec), expectedItem != null);

                // Make sure all the metadata on the expected item matches the metadata on the actual item.
                // Don't check built-in metadata ... only check custom metadata.
                foreach (string metadataName in expectedItem.MetadataNames)
                {
                    // This check filters out any built-in item metadata, like "RelativeDir", etc.
                    if (!IsBuiltInItemMetadataName(metadataName))
                    {
                        string expectedMetadataValue = expectedItem.GetMetadata(metadataName);
                        string actualMetadataValue   = actualItem.GetMetadata(metadataName);

                        Assertion.Assert(string.Format("Item '{0}' does not have expected metadata '{1}'.", actualItem.ItemSpec, metadataName),
                                         actualMetadataValue.Length > 0 || expectedMetadataValue.Length == 0);

                        Assertion.Assert(string.Format("Item '{0}' has unexpected metadata {1}={2}.", actualItem.ItemSpec, metadataName, actualMetadataValue),
                                         actualMetadataValue.Length == 0 || expectedMetadataValue.Length > 0);

                        Assertion.Assert(string.Format("Item '{0}' has metadata {1}={2} instead of expected {1}={3}.",
                                                       actualItem.ItemSpec, metadataName, actualMetadataValue, expectedMetadataValue),
                                         actualMetadataValue == expectedMetadataValue);
                    }
                }
                expectedItems.RemoveAt(expectedItemIndex);
            }

            // Log an error for any leftover items in the expectedItems collection.
            foreach (ITaskItem expectedItem in expectedItems)
            {
                Assertion.Assert(String.Format("Item '{0}' was expected but not returned.", expectedItem.ItemSpec), false);
            }

            if (outOfOrder)
            {
                Console.WriteLine("ERROR:  Items were returned in the incorrect order...");
                Console.WriteLine("Expected:  " + expectedItemSpecs);
                Console.WriteLine("Actual:    " + actualItemSpecs);
                Assertion.Assert("Items were returned in the incorrect order.  See 'Standard Out' tab for more details.", false);
            }
        }
Ejemplo n.º 5
0
        private void Install(UnityPluginDetector.InstallationInfo installationInfo, bool force)
        {
            if (!force)
            {
                if (!installationInfo.ShouldInstallPlugin)
                {
                    Assertion.Assert(false, "Should not be here if installation is not required.");
                    return;
                }

                if (myPluginInstallations.Contains(mySolution.SolutionFilePath))
                {
                    myLogger.Verbose("Installation already done.");
                    return;
                }
            }

            myLogger.Info("Installing Rider Unity editor plugin: {0}", installationInfo.InstallReason);

            if (!TryCopyFiles(installationInfo, out var installedPath))
            {
                myLogger.Warn("Plugin was not installed");
            }
            else
            {
                string userTitle;
                string userMessage;

                switch (installationInfo.InstallReason)
                {
                case UnityPluginDetector.InstallReason.FreshInstall:
                    userTitle   = "Unity Editor plugin installed";
                    userMessage = $@"Please switch to Unity Editor to load the plugin.
                            Rider plugin v{myCurrentVersion} can be found at:
                            {installedPath.MakeRelativeTo(mySolution.SolutionDirectory)}.";
                    break;

                case UnityPluginDetector.InstallReason.Update:
                    userTitle   = "Unity Editor plugin updated";
                    userMessage = $@"Please switch to the Unity Editor to reload the plugin.
                            Rider plugin v{myCurrentVersion} can be found at:
                            {installedPath.MakeRelativeTo(mySolution.SolutionDirectory)}.";
                    break;

                case UnityPluginDetector.InstallReason.ForceUpdateForDebug:
                    userTitle   = "Unity Editor plugin updated (debug build)";
                    userMessage = $@"Please switch to the Unity Editor to reload the plugin.
                            Rider plugin v{myCurrentVersion} can be found at:
                            {installedPath.MakeRelativeTo(mySolution.SolutionDirectory)}.";
                    break;

                case UnityPluginDetector.InstallReason.UpToDate:
                    userTitle   = "Unity Editor plugin updated (up to date)";
                    userMessage = $@"Please switch to the Unity Editor to reload the plugin.
                            Rider plugin v{myCurrentVersion} can be found at:
                            {installedPath.MakeRelativeTo(mySolution.SolutionDirectory)}.";
                    break;

                default:
                    myLogger.Error("Unexpected install reason: {0}", installationInfo.InstallReason);
                    return;
                }

                myLogger.Info(userTitle);

                var notification = new NotificationModel(userTitle, userMessage, true, RdNotificationEntryType.INFO);

                myShellLocks.ExecuteOrQueueEx(myLifetime, "UnityPluginInstaller.Notify", () => myNotifications.Notification(notification));
            }
        }
Ejemplo n.º 6
0
 public static T Get <T>()
 {
     Assertion.Assert(factoryMap.ContainsKey(typeof(T)));
     return((T)factoryMap[typeof(T)]);
 }
Ejemplo n.º 7
0
        protected override void Run(IDeclaration declaration, ElementProblemAnalyzerData data, IHighlightingConsumer consumer)
        {
            var declaredElement = declaration.DeclaredElement;
            var attributesSet   = declaredElement as IAttributesSet;

            var hasOveriddenImplicitNullability = false;

            if (attributesSet != null)
            {
                Assertion.Assert(declaredElement != null, "declaredElement != null");

                var attributeInstances = attributesSet.GetAttributeInstances(inherit: false);

                switch (declaration)
                {
                case IParameterDeclaration parameterDeclaration:
                    var parameter = parameterDeclaration.DeclaredElement.NotNull();
                    CheckForNotNullOnImplicitCanBeNull(consumer, parameter, attributeInstances, declaration);
                    CheckForParameterSuperMemberConflicts(consumer, parameter, attributeInstances, declaration);
                    break;

                case IMethodDeclaration methodDeclaration:
                    var method = methodDeclaration.DeclaredElement.NotNull();
                    CheckForNotNullOnImplicitCanBeNull(consumer, method, attributeInstances, methodDeclaration.NameIdentifier);
                    CheckForMethodSuperMemberConflicts(consumer, method, attributeInstances, methodDeclaration.NameIdentifier);
                    break;

                case IOperatorDeclaration operatorDeclaration:
                    var operatorKeyword = operatorDeclaration.OperatorKeyword;
                    CheckForNotNullOnImplicitCanBeNull(consumer, declaredElement, attributeInstances, operatorKeyword);
                    break;

                case IDelegateDeclaration delegateDeclaration:
                    var delegateName = delegateDeclaration.NameIdentifier;
                    CheckForNotNullOnImplicitCanBeNull(consumer, declaredElement, attributeInstances, delegateName);
                    break;

                case IFieldDeclaration fieldDeclaration:
                    var fieldName = fieldDeclaration.NameIdentifier;
                    CheckForNotNullOnImplicitCanBeNull(consumer, declaredElement, attributeInstances, fieldName);
                    break;

                case IPropertyDeclaration propertyDeclaration:
                    var property     = propertyDeclaration.DeclaredElement.NotNull();
                    var propertyName = propertyDeclaration.NameIdentifier;
                    CheckForNotNullOnImplicitCanBeNull(consumer, declaredElement, attributeInstances, propertyName);
                    CheckForPropertySuperMemberConflicts(consumer, property, attributeInstances, propertyName);
                    break;

                case IIndexerDeclaration indexerDeclaration:
                    var indexerProperty    = indexerDeclaration.DeclaredElement.NotNull();
                    var indexerThisKeyword = indexerDeclaration.ThisKeyword;
                    CheckForNotNullOnImplicitCanBeNull(consumer, declaredElement, attributeInstances, indexerThisKeyword);
                    CheckForPropertySuperMemberConflicts(consumer, indexerProperty, attributeInstances, indexerThisKeyword);
                    break;
                }

                hasOveriddenImplicitNullability |=
                    _annotationAttributesChecker.ContainsAnyExplicitNullabilityAttributes(attributeInstances) &&
                    _implicitNullabilityProvider.AnalyzeDeclaredElement(declaredElement) != null;

                hasOveriddenImplicitNullability |=
                    _annotationAttributesChecker.ContainsAnyExplicitItemNullabilityAttributes(attributeInstances) &&
                    _implicitNullabilityProvider.AnalyzeDeclaredElementContainerElement(declaredElement) != null;
            }

            DelegateToIncorrectNullableAttributeUsageAnalyzer(declaration, data, consumer, hasOveriddenImplicitNullability);
        }
        private void Install(UnityPluginDetector.InstallationInfo installationInfo)
        {
            if (!installationInfo.ShouldInstallPlugin)
            {
                Assertion.Assert(false, "Should not be here if installation is not required.");
                return;
            }

            if (myPluginInstallations.Contains(mySolution.SolutionFilePath))
            {
                myLogger.Verbose("Installation already done.");
                return;
            }

            if (currentVersion == installationInfo.Version)
            {
                myLogger.Verbose($"Plugin v{installationInfo.Version} already installed.");
                return;
            }

            var isFreshInstall = installationInfo.Version == UnityPluginDetector.ZeroVersion;

            if (isFreshInstall)
            {
                myLogger.Info("Fresh install");
            }

            FileSystemPath installedPath;

            if (!TryCopyFiles(installationInfo, out installedPath))
            {
                myLogger.Warn("Plugin was not installed");
            }
            else
            {
                string userTitle;
                string userMessage;

                if (isFreshInstall)
                {
                    userTitle   = "Unity: plugin installed";
                    userMessage =
                        $@"Rider plugin v{
                                currentVersion
                            } for the Unity Editor was automatically installed for the project '{mySolution.Name}'
This allows better integration between the Unity Editor and Rider IDE.
The plugin file can be found on the following path:
{installedPath.MakeRelativeTo(mySolution.SolutionFilePath)}.
Please switch back to Unity to make plugin file appear in the solution.";
                }
                else
                {
                    userTitle   = "Unity: plugin updated";
                    userMessage = $"Rider plugin was succesfully upgraded to version {currentVersion}";
                }

                myLogger.Info(userTitle);

                var notification = new RdNotificationEntry(userTitle,
                                                           userMessage, true,
                                                           RdNotificationEntryType.INFO);

                myShellLocks.ExecuteOrQueueEx(myLifetime, "UnityPluginInstaller.Notify", () => myNotifications.Notification.Fire(notification));
            }
        }
Ejemplo n.º 9
0
        private void ThreadProc()
        {
            while (true)
            {
                lock (myLock)
                {
                    if (State >= StateKind.Terminating)
                    {
                        return;
                    }

                    while (myAllDataProcessed || myPauseReasons.Count > 0)
                    {
                        if (State >= StateKind.Stopping)
                        {
                            return;
                        }
                        Monitor.Wait(myLock);
                        if (State >= StateKind.Terminating)
                        {
                            return;
                        }
                    }

                    //In case of only put requests, we could write Assertion.Assert(chunk.Ptr > 0, "chunk.Ptr > 0");
                    //But in case of clear, we could get "Wait + Put(full)  + Clear + Put" before this line and 'chunkToProcess' will point to empty chunk.
                    //RIDER-15223
                    while (myChunkToProcess.CheckEmpty(this)) //should never be endless, because `myAllDataProcessed` is 'false', that means that we MUST have ptr > 0 somewhere
                    {
                        myChunkToProcess = myChunkToProcess.Next;
                    }

                    if (myChunkToFill == myChunkToProcess)
                    {
                        //it's possible that next chuck is occupied by entry with seqN > acknowledgedSeqN
                        GrowConditionally();

                        myChunkToFill = myChunkToProcess.Next;
                    }

                    ShrinkConditionally(myChunkToProcess);

                    Assertion.Assert(myChunkToProcess.Ptr > 0, "chunkToProcess.Ptr > 0");
                    Assertion.Assert(myChunkToFill != myChunkToProcess && myChunkToFill.IsNotProcessed, "myChunkToFill != chunkToProcess && myChunkToFill.IsNotProcessed");

                    myProcessing = true;
                }


                long seqN = myChunkToProcess.IsNotProcessed ? 0 : myChunkToProcess.SeqN;
                try
                {
                    myProcessor(myChunkToProcess.Data, 0, myChunkToProcess.Ptr, ref seqN);
                }
                catch (Exception e)
                {
                    LogLog.Error(e);
                }
                finally
                {
                    lock (myLock)
                    {
                        myProcessing = false;

                        if (myChunkToProcess == null)
                        {
                            LogLog.Error($"{nameof(myChunkToProcess)} is null. State: {State}");
                        }
                        else
                        {
                            myChunkToProcess.SeqN = seqN;
                            myChunkToProcess      = myChunkToProcess.Next;
//            Assertion.Assert(myChunkToProcess.IsNotProcessed, "chunkToProcess.IsNotProcessed"); not true in case of reprocessing
                            if (myChunkToProcess.Ptr == 0)
                            {
                                myAllDataProcessed = true;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 10
0
 public static CurrentStack <S> ApplyTransitionToStack <A>(Transition <A, S> transition, CurrentStack <S> stackBefore) where A : IEquatable <A>
 {
     Assertion.Assert(!stackBefore.IsEmpty(), "a transition cannot be applied to an empty stack");
     Assertion.Assert(transition.StackSymbolIn.Equals(stackBefore.StackSymbols.First()), "the input-stack-symbol of the transition has to be the same as the first one of current stack");
     return(new CurrentStack <S>(transition.StackSymbolsWritten.Concat(stackBefore.StackSymbols.Skip(1)).ToList()));
 }
Ejemplo n.º 11
0
        [Test] public void testPubCloseReOpen()
        {
            TestUtil.INIT_TESTCASE("testPubCloseReOpen");
            TestUtil.resetCounters();

            string serverUrl = TestUtil.getServer();
            string topic     = "/what/Tests/functional_NET/csharp/"
                               + TestUtil.getTestsuiteName() + "/" + TestUtil.getTestcaseName();

            Connector pubConn = new Connector();

            TestUtil.PubRequestStatusHandler pubReqSH = new TestUtil.PubRequestStatusHandler();
            Parameters pubITParams = new Parameters();
            Message    pubMsg      = new Message();

            // This is only necessary to get pubConnSH_OnConnStatus
            TestUtil.PubConnStatusHandler pubConnSH = new TestUtil.PubConnStatusHandler();
            pubConn.AddConnectionStatusHandler(pubConnSH);

            pubITParams.ServerUrl = serverUrl;
            if (!pubConn.Open(pubITParams))
            {
                Assertion.Fail("tp=1 Open(pubITParams) failed.");
            }

            Assertion.Assert("tp=2", pubConn.EnsureConnected());

            // Publish one message
            pubMsg.Set("do_method", "notify");
            pubMsg.Set("kn_to", topic);
            pubMsg.Set("kn_payload", "Hello-X");
            pubMsg.Set("nickname", "abc");
            pubMsg.Set("kn_response_format", "simple");

            Assertion.Assert("tp=3", pubConn.Publish(pubMsg, pubReqSH));
            Assertion.Assert("tp=4", pubConn.IsConnected());
            Assertion.Assert("tp=5", pubConn.EnsureConnected());

            Assertion.Assert("tp=6", pubConn.Close());
            Assertion.Assert("tp=7", !pubConn.IsConnected());

            Assertion.Assert("tp=8", pubConn.Publish(pubMsg, pubReqSH));             //Publish will re open.
            Assertion.Assert("tp=9", pubConn.IsConnected());

            Assertion.Assert("tp=10", pubConn.Close());
            Assertion.Assert("tp=11", !pubConn.IsConnected());

            Assertion.Assert("tp=12", pubConn.EnsureConnected());             //EnsureConnected will re open.
            Assertion.Assert("tp=13", pubConn.IsConnected());

            //Close and Publish one more time to make sure really working
            Assertion.Assert("tp=14", pubConn.Close());
            Assertion.Assert("tp=15", !pubConn.IsConnected());

            Assertion.Assert("tp=16", pubConn.Publish(pubMsg, pubReqSH));             //Publish will re open.
            Assertion.Assert("tp=17", pubConn.IsConnected());

            TestUtil.dumpCounters();
            //pubReqSH    OnSuccess    : 3 pub connections ------------------+
            //pubReqSH    OnError      : ---------------------------------+  |
            //pubConnSH   OnConnStatus : 3 pub connections ------------+  |  |
            //subReqSH    OnSuccess    : No sub --------------------+  |  |  |
            //subReqSH    OnError      : No sub -----------------+  |  |  |  |
            //subConnSH   OnConnStatus : No sub --------------+  |  |  |  |  |
            //subListener OnUpdate     : No sub -----------+  |  |  |  |  |  |
            string counterResult1 = TestUtil.checkCounters(0, 0, 0, 0, 3, 0, 3);

            Assertion.Assert("tp=18" + counterResult1, counterResult1 == TestUtil.TU_OK);
        }
Ejemplo n.º 12
0
        //on poller thread
        public void Dispatch(RdId id, byte[] msg)
        {
            Assertion.Require(!id.IsNil, "!id.IsNil");

            lock (myLock)
            {
                var s = mySubscriptions.GetOrDefault(id);
                if (s == null)
                {
                    var currentBroker = myBroker.GetOrCreate(id, () => new Mq());
                    currentBroker.DefaultSchedulerMessages.Add(msg);

                    myScheduler.Queue(() =>
                    {
                        byte[] msg1;

                        IRdWireable subscription;
                        bool hasSubscription;

                        lock (myLock)
                        {
                            if (currentBroker.DefaultSchedulerMessages.Count > 0)
                            {
                                msg1 = currentBroker.DefaultSchedulerMessages[0];
                                currentBroker.DefaultSchedulerMessages.RemoveAt(0);
                            }
                            else
                            {
                                msg1 = null;
                            }

                            hasSubscription = mySubscriptions.TryGetValue(id, out subscription);
                        }

                        if (!hasSubscription)
                        {
                            myLogger.Trace("No handler for id: {0}", id);
                        }
                        else if (msg1 != null)
                        {
                            Invoke(subscription, msg1, sync: subscription.WireScheduler == myScheduler);
                        }

                        lock (myLock)
                        {
                            if (currentBroker.DefaultSchedulerMessages.Count == 0)
                            {
                                if (myBroker.Remove(id))
                                {
                                    if (subscription != null)
                                    {
                                        foreach (var m in currentBroker.CustomSchedulerMessages)
                                        {
                                            Assertion.Assert(subscription.WireScheduler != myScheduler,
                                                             "subscription.Scheduler != myScheduler for {0}", subscription);
                                            Invoke(subscription, m);
                                        }
                                    }
                                }
                            }
                        }
                    });
                }


                else // s != null
                {
                    if (s.WireScheduler == myScheduler || s.WireScheduler.OutOfOrderExecution)
                    {
                        Invoke(s, msg);
                    }
                    else
                    {
                        var mq = myBroker.GetOrDefault(id);
                        if (mq != null)
                        {
                            mq.CustomSchedulerMessages.Add(msg);
                        }
                        else
                        {
                            Invoke(s, msg);
                        }
                    }
                }
            }
        }
 public Object GetParameter(string key)
 {
     Assertion.Assert(IsActive());             // "This instance is no longer active."
     return(parameterMap[key]);
 }
 public string GetId()
 {
     Assertion.Assert(IsActive());             // "This instance is no longer active."
     return(id);
 }
Ejemplo n.º 15
0
Archivo: RdMap.cs Proyecto: epeshk/rd
 public static void Write(SerializationCtx ctx, UnsafeWriter writer, RdMap <K, V> value)
 {
     Assertion.Assert(!value.RdId.IsNil, "!value.RdId.IsNil");
     writer.Write(value.RdId);
 }
Ejemplo n.º 16
0
 public Retain(int offset)
 {
     Assertion.Assert(offset >= 0, "offset >= 0");
     Offset = offset;
 }
Ejemplo n.º 17
0
        protected override bool AddLookupItems(CSharpCodeCompletionContext context, IItemsCollector collector)
        {
            var generationContext = TryBuildMemberGenerationContext(context);

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

            // Assert base class preconditions. We only add items in the light pass, which gives us higher relevance,
            // putting us above types that are in the full pass. We need to be super fast in Light mode, and we are -
            // we're just looking things up
            Assertion.Assert(context.BasicContext.Parameters.EvaluationMode == EvaluationMode.Light,
                             "evaluationMode == EvaluationMode.Light");
            Assertion.Assert(context.BasicContext.Parameters.Multiplier == 1, "multiplier == 1");

            var unityApi = context.BasicContext.Solution.GetComponent <UnityApi>();

            if (!CheckPosition(context, unityApi, out var classDeclaration, out var accessRights, out var hasReturnType))
            {
                return(false);
            }

            var typeElement     = classDeclaration.DeclaredElement;
            var baseTypeElement = typeElement?.GetBaseClassType()?.GetTypeElement();

            if (typeElement == null || baseTypeElement == null)
            {
                return(false);
            }

            var unityVersionApi  = context.BasicContext.Solution.GetComponent <UnityVersion>();
            var project          = context.BasicContext.File.GetProject();
            var actualVersion    = unityVersionApi.GetActualVersion(project);
            var thisMethods      = typeElement.Methods.ToList();
            var inheritedMethods = baseTypeElement.GetAllClassMembers <IMethod>().ToList();

            var addedFunctions = new HashSet <string>();

            foreach (var function in unityApi.GetEventFunctions(typeElement, actualVersion))
            {
                if (HasAnyPartiallyMatchingExistingMethods(thisMethods, function))
                {
                    continue;
                }

                if (HasAnyExactMatchInheritedMethods(inheritedMethods, function))
                {
                    continue;
                }

                if (addedFunctions.Contains(function.Name))
                {
                    continue;
                }

                var item = CreateMethodItem(context, function, classDeclaration, hasReturnType, accessRights, generationContext);
                if (item == null)
                {
                    continue;
                }

                item = SetRelevanceSortPriority(item, function);
                item = SetLexicographicalSortPriority(item, function);

                addedFunctions.Add(function.Name);
                collector.Add(item);
            }

            return(true);
        }
Ejemplo n.º 18
0
        public void AddInspectorHighlighting(IHighlightingConsumer consumer, ICSharpDeclaration element,
                                             IDeclaredElement declaredElement, string baseDisplayName, string baseTooltip, string moreText, IconModel iconModel,
                                             IEnumerable <BulbMenuItem> items, List <CodeLensEntryExtraActionModel> extraActions)
        {
            string displayName = null;
            string tooltip     = "Values from Unity Editor Inspector";

            var solution = element.GetSolution();

            Assertion.Assert(solution.Locks.IsReadAccessAllowed(), "ReadLock required");

            var result = GetAssetGuidAndPropertyName(solution, declaredElement);

            if (!result.HasValue)
            {
                return;
            }

            var guid         = result.Value.guid;
            var propertyName = result.Value.propertyName;

            var cache = solution.GetComponent <UnitySceneDataLocalCache>();

            var field            = (declaredElement as IField).NotNull();
            var type             = field.Type;
            var presentationType = GetUnityPresentationType(type);

            if (ShouldShowUnknownPresentation(presentationType))
            {
                base.AddHighlighting(consumer, element, field, baseDisplayName, baseTooltip, moreText, iconModel, items, extraActions);
                return;
            }

            var initializer = (element as IFieldDeclaration).NotNull("element as IFieldDeclaration != null").Initial;
            var initValue   = (initializer as IExpressionInitializer)?.Value?.ConstantValue.Value;

            var initValueUnityPresentation = GetUnitySerializedPresentation(presentationType, initValue);
            var initValueCount             = cache.GetValueCount(guid, propertyName, initValueUnityPresentation);

            if (initValueCount == 0 && cache.GetPropertyUniqueValuesCount(guid, propertyName) == 1) // only modified value
            {
                var valueWithLocations = cache.GetUniqueValuesWithLocation(guid, propertyName).ToArray();
                Assertion.Assert(valueWithLocations.Length == 1, "valueWithLocations.Length == 1"); //performance assertion
                displayName = GetPresentation(valueWithLocations[0], presentationType, type, solution, element.GetPsiModule(), false);
            }
            else if (initValueCount > 0 && cache.GetPropertyUniqueValuesCount(guid, propertyName) == 2)
            {
                // original value & only one modified value
                var values = cache.GetUniqueValuesWithLocation(guid, propertyName).ToArray();
                Assertion.Assert(values.Length == 2, "values.Length == 2"); //performance assertion

                var anotherValueWithLocation = values[0].Value.Value.Equals(initValueUnityPresentation) ? values[1] : values[0];
                displayName = GetPresentation(anotherValueWithLocation, presentationType, type, solution, element.GetPsiModule(), false);
            }

            if (displayName == null)
            {
                var count = cache.GetFilesWithPropertyCount(guid, propertyName) - cache.GetFilesCountWithoutChanges(guid, propertyName, initValueUnityPresentation);
                if (count == 0)
                {
                    displayName = "Unchanged";
                }
                else
                {
                    var word = count == 1 ? "asset" : "assets";
                    displayName = $"Changed in {count} {word}";
                }
            }


            consumer.AddHighlighting(new UnityInspectorCodeInsightsHighlighting(element.GetNameDocumentRange(),
                                                                                displayName, tooltip, "Property Inspector values", this,
                                                                                declaredElement, iconModel, presentationType, initValue));
        }
Ejemplo n.º 19
0
 public static void Clean <T>()
 {
     Assertion.Assert(factoryMap.ContainsKey(typeof(T)));
     factoryMap.Remove(typeof(T));
 }
Ejemplo n.º 20
0
 /**
  * Returns the InputLayer instance that is at the top.
  */
 public InputLayer Top()
 {
     Assertion.Assert(!IsEmpty(), "Can't get top if stack is empty.");
     return(layerStack[layerStack.Count - 1]);
 }
Ejemplo n.º 21
0
        /**
         * Asserts that the provided set of Mappings matches the one that was
         * created in createMappings();
         */

        private void assertMappings(Mappings m)
        {
            Mappings test = m.GetMappings("Test");

            Assertion.AssertNotNull("Test mappings is not present", test);
            Assertion.AssertEquals("Should have a single Object Mapping", 1, test.GetObjectMappings().Length);

            // TODO: Test the version and sourceId filters more carefully

            /*
             * Assertion.AssertEquals( "SifVersion attr should be empty", 0,
             * test.SifVersionFilter().Length ); Assertion.AssertEquals( "SourceId attr
             * should be empty", 0, test.SourceIdFilter().Length ); Assertion.AssertEquals(
             * "Zone attr should be empty", 0, test.ZoneIdFilter().Length );
             */

            // assert the object mapping
            ObjectMapping om = test.GetObjectMapping("StudentPersonal", false);

            Assertion.AssertNotNull("StudentPersonal mappings", om);
            Assertion.AssertEquals("There should be five rules", 5, om.RuleCount);
            IList <FieldMapping> rules = om.GetRulesList(false);

            // Field 1
            Assertion.AssertEquals("FIELD1 name", "FIELD1", rules[0].FieldName);
            Assertion.AssertEquals("FIELD1 rule", "Name/FirstName", rules[0].GetRule().ToString());
            Assertion.AssertEquals("FIELD1 ifNull", MappingBehavior.IfNullUnspecified, rules[0].NullBehavior);

            // Field 2
            Assertion.AssertEquals("FIELD2 name", "FIELD2", rules[1].FieldName);
            Assertion.AssertEquals("FIELD2 rule", "Name/LastName", rules[1].GetRule().ToString());
            Assertion.AssertEquals("FIELD2 valueset", "VS1", rules[1].ValueSetID);
            Assertion.AssertEquals("FIELD2 alias", "ALIAS1", rules[1].Alias);
            Assertion.AssertEquals("FIELD2 default", "DEFAULT1", rules[1].DefaultValue);
            MappingsFilter filter = rules[1].Filter;

            Assertion.AssertNotNull("FIELD2 filter is null", filter);
            Assertion.AssertEquals("filter direction", MappingDirection.Inbound, filter
                                   .Direction);
            Assertion.AssertEquals("filter sif version", "=" + SifVersion.SIF11.ToString(),
                                   filter.SifVersion);

            // Field 3
            Assertion.AssertEquals("FIELD3 name", "FIELD3", rules[2].FieldName);
            Assertion.AssertEquals("FIELD3 rule", "Name/MiddleName", rules[2].GetRule().ToString());
            Assertion.AssertEquals("FIELD3 valueset", "VS2", rules[2].ValueSetID);
            Assertion.AssertEquals("FIELD3 alias", "ALIAS2", rules[2].Alias);
            Assertion.AssertEquals("FIELD3 default", "DEFAULT2", rules[2].DefaultValue);
            Assertion.AssertEquals("FIELD3 ifNull", MappingBehavior.IfNullDefault, rules[2].NullBehavior);
            MappingsFilter filter2 = rules[2].Filter;

            Assertion.AssertNotNull("FIELD3 filter is null", filter2);
            Assertion.AssertEquals("filter2 direction", MappingDirection.Outbound, filter2.Direction);
            Assertion.AssertEquals("filter2 sif version",
                                   "=" + SifVersion.SIF15r1.ToString(), filter2.SifVersion);

            // Field 4
            Assertion.AssertEquals("FIELD4 name", "FIELD4", rules[3].FieldName);
            Assertion.AssertNull("FIELD4 valueset", rules[3].ValueSetID);
            Assertion.AssertNull("FIELD4 alias", rules[3].Alias);
            Assertion.AssertNull("FIELD4 default", rules[3].DefaultValue);
            Assertion.AssertEquals("FIELD4 ifNull", MappingBehavior.IfNullSuppress, rules[3].NullBehavior);
            Rule r = rules[3].GetRule();

            Assertion.Assert("Rule should be OtherIdRule", r is OtherIdRule);

            Assertion.AssertEquals("FIELD5 name", "FIELD5", rules[4].FieldName);
            Assertion.AssertEquals("FIELD5 datatype", SifDataType.Date, rules[4]
                                   .DataType);

            // TODO: The OtherIdRule doesn't have an API to get at the
            // OtherIdMapping. For now, just
            // convert it to a string and assert the results
            String ruleStr = r.ToString();

            Assertion.Assert("prefix should be BUSROUTE", ruleStr
                             .IndexOf("prefix='BUSROUTE'") > 1);
            Assertion.Assert("type should be ZZ", ruleStr.IndexOf("type='ZZ'") > 1);

            ValueSet vs = test.GetValueSet("VS1", false);

            Assertion.AssertNotNull("ValueSet VS1 should not be null", vs);
            Assertion.AssertEquals("VS1 should have 12 entries", 12, vs.Entries.Length);
            for (int a = 0; a < 10; a++)
            {
                Assertion.AssertEquals("Mapping by appvalue", "SifValue" + a, vs.Translate("Value" + a));
                Assertion.AssertEquals("Mapping by sifvalue", "Value" + a, vs.TranslateReverse("SifValue" + a));
            }
            // Test the default value entries
            Assertion.AssertEquals("Expecting app default value", "AppDefault", vs.TranslateReverse("abcdefg"));
            Assertion.AssertEquals("Expecting app default value", "AppDefault", vs.TranslateReverse(null));
            Assertion.AssertEquals("Expecting sif default value", "SifDefault", vs.Translate("abcdefg"));
            Assertion.AssertNull("Expecting NULL value", vs.Translate(null));

            vs = test.GetValueSet("VS2", false);
            Assertion.AssertNotNull("ValueSet VS2 should not be null", vs);
            Assertion.AssertEquals("VS2 should have 4 entries", 4, vs.Entries.Length);
            for (int a = 0; a < 3; a++)
            {
                Assertion.AssertEquals("Mapping by appvalue", "w" + a, vs.Translate("q" + a));
                Assertion.AssertEquals("Mapping by sifvalue", "q" + a, vs
                                       .TranslateReverse("w" + a));
            }
            // Test the default value entries
            Assertion.AssertEquals("Expecting app default value", "AppDefault", vs
                                   .TranslateReverse("abcdefg"));
            Assertion.AssertEquals("Expecting app default value", "AppDefault", vs
                                   .TranslateReverse(null));
            Assertion.AssertEquals("Expecting sif default value", "0000", vs
                                   .Translate("abcdefg"));
            Assertion.AssertEquals("Expecting sif default value", "0000", vs.Translate(null));
        }
 public void MethodAccess()
 {
     Assertion.Assert("Method on normal object", XmlRpcExposedAttribute.ExposedMethod(this, "MethodAccess"));
     Assertion.Assert("Exposed method on exposed object", XmlRpcExposedAttribute.ExposedMethod(_e, "Open"));
     Assertion.Assert("Closed method on exposed object", !XmlRpcExposedAttribute.ExposedMethod(_e, "Closed"));
 }
Ejemplo n.º 23
0
 /// <summary>
 /// Assert that a given file exists (or not) within the temp project directory.
 /// </summary>
 /// <param name="fileRelativePath"></param>
 /// <param name="message">Can be null.</param>
 private static void AssertFileExistenceInTempProjectDirectory(string fileRelativePath, string message, bool exists)
 {
     Assertion.Assert(message, (exists == File.Exists(Path.Combine(TempProjectDir, fileRelativePath))));
 }
Ejemplo n.º 24
0
        private bool ReformatForSmartEnter(string dummyText, ITextControl textControl, IFile file, TreeTextRange reparseTreeOffset, TreeOffset lBraceTreePos, TreeOffset rBraceTreePos, bool insertEnterAfter = false)
        {
            // insert dummy text and reformat
            TreeOffset newCaretPos;
            var        codeFormatter = GetCodeFormatter(file);

            using (PsiTransactionCookie.CreateAutoCommitCookieWithCachesUpdate(PsiServices, "Typing assist"))
            {
                string newLine      = Environment.NewLine;
                string textToInsert = newLine + dummyText;
                if (insertEnterAfter)
                {
                    textToInsert = textToInsert + newLine;
                }
                file = file.ReParse(reparseTreeOffset, textToInsert);
                if (file == null)
                {
                    return(false);
                }

                ITreeNode lBraceNode = file.FindTokenAt(lBraceTreePos);
                if (lBraceNode == null)
                {
                    return(false);
                }

                var dummyNode = file.FindTokenAt(reparseTreeOffset.StartOffset + newLine.Length) as ITokenNode;

                var languageService = file.Language.LanguageService();
                if (languageService == null)
                {
                    return(false);
                }

                while (dummyNode != null && languageService.IsFilteredNode(dummyNode))
                {
                    dummyNode = dummyNode.GetNextToken();
                }

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

                var rBraceNode = file.FindTokenAt(rBraceTreePos + newLine.Length + dummyText.Length + (insertEnterAfter ? newLine.Length : 0));

                var boundSettingsStore = SettingsStore.BindToContextTransient(textControl.ToContextRange());

                codeFormatter.Format(lBraceNode, CodeFormatProfile.DEFAULT, null, boundSettingsStore);
                codeFormatter.Format(
                    rBraceNode.FindFormattingRangeToLeft(),
                    rBraceNode,
                    CodeFormatProfile.DEFAULT,
                    null,
                    boundSettingsStore);
                codeFormatter.Format(lBraceNode.Parent, CodeFormatProfile.INDENT, null);

                newCaretPos = dummyNode.GetTreeStartOffset();
                file        = file.ReParse(new TreeTextRange(newCaretPos, newCaretPos + dummyText.Length), "");
                Assertion.Assert(file != null, "file != null");
            }

            // dposition cursor
            DocumentRange newCaretPosition = file.GetDocumentRange(newCaretPos);

            if (newCaretPosition.IsValid())
            {
                textControl.Caret.MoveTo(newCaretPosition.TextRange.StartOffset, CaretVisualPlacement.DontScrollIfVisible);
            }

            return(true);
        }
Ejemplo n.º 25
0
 public void test_ConstructorLjava_lang_String()
 {
     // Test for method java.util.StringTokenizer(java.lang.String)
     Assertion.Assert("Used in tests", true);
 }
Ejemplo n.º 26
0
 public void AssertValid() => Assertion.Assert(IsValid(), "IsValid()");
 private static StackSymbolSequence<S> GetStackSymbol(PDA<A, StackSymbolSequence<S>> pda, S stackSymbol)
 {
     var res = pda.AllStackSymbols.Where(s => s.StackSequence.SequenceEqual(new S[] { stackSymbol }));
     Assertion.Assert(res.Count() <= 1, "Illegal state: the stack symbol exists twice");
     return res.First();
 }
Ejemplo n.º 28
0
            public void InvalidateCachedValues(IReferenceExpression key)
            {
                if (!myPropertiesMap.ContainsKey(key))
                {
                    return;
                }

                var highlighitingElements = myPropertiesMap[key];

                Assertion.Assert(highlighitingElements.Count > 0, "highlighitingElements.Length > 0");

                // calculate read/write operations for property
                int write = 0;
                int read  = 0;
                int startHighlightIndex = -1;

                ICSharpTreeNode      readAnchor          = null;
                bool                 inlineCacheValue    = false;
                ICSharpTreeNode      writeAnchor         = null;
                IReferenceExpression lastWriteExpression = null;
                bool                 inlineRestoreValue  = false;

                for (int i = 0; i < highlighitingElements.Count; i++)
                {
                    var referenceExpression = highlighitingElements[i];

                    var accessType = referenceExpression.GetAccessType();

                    if (read == 0 && write == 0)
                    {
                        readAnchor = referenceExpression.GetContainingStatementLike().NotNull("readAnchor != null");
                        var previousRelatedExpression = GetPreviousRelatedExpression(referenceExpression, readAnchor);
                        // if we have related expression before considered reference expression, we can only inline reading into statement
                        // Example:
                        // transform.Position = (transform.localPosition = Vector3.Up) + transform.position + transform.position;
                        //                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                        // transform.localPosition is related to transform.position, but we need cache our variable
                        // The result is:
                        // var cache = transform.position;
                        // transform.position = (transform.localPosition = Vector3.Up) + (cache = transform.position) + cache;

                        inlineCacheValue = previousRelatedExpression != null;
                    }

                    if (accessType.HasFlag(ExpressionAccessType.Write))
                    {
                        write++;
                        lastWriteExpression = referenceExpression;
                    }
                    if (accessType.HasFlag(ExpressionAccessType.Read))
                    {
                        read++;
                    }

                    if (startHighlightIndex == -1 && (read == 2 || write == 2 | read + write == 3))
                    {
                        startHighlightIndex = i;
                    }
                }

                if (lastWriteExpression != null)
                {
                    writeAnchor = lastWriteExpression.GetContainingStatementLike().NotNull("writeAnchor != null");
                    if (writeAnchor is IReturnStatement ||
                        writeAnchor is IYieldStatement yieldStatement && yieldStatement.StatementType == YieldStatementType.YIELD_RETURN)
                    {
                        inlineRestoreValue = true;
                    }
                    else
                    {
                        var relatedExpressions = GetFinder(lastWriteExpression).GetRelatedExpressions(writeAnchor, lastWriteExpression);
                        inlineRestoreValue = relatedExpressions.Any();
                    }
                }
Ejemplo n.º 29
0
 public void Regress_Mutation_ParameterOrderDoesntMatter()
 {
     Assertion.Assert(TypeLoader.IsPartialTypeNameMatch("Csc", "net.r_eg.IeXod.Tasks.Csc"));
 }
        protected override ITreeNode ExpandPostfix(PostfixExpressionContext context)
        {
            var csharpContext = (CSharpPostfixExpressionContext)context;
            var psiModule     = csharpContext.PostfixContext.PsiModule;
            var psiServices   = psiModule.GetPsiServices();
            var factory       = CSharpElementFactory.GetInstance(psiModule);

            var targetStatement = csharpContext.GetContainingStatement();
            var expressionRange = csharpContext.Expression.GetDocumentRange();

            // Razor issue - hard to convert expression to statement
            if (!targetStatement.GetDocumentRange().IsValid())
            {
                var newStatement = psiServices.DoTransaction(ExpandCommandName, () =>
                {
                    // todo: pass original context?
                    var expression = csharpContext.Expression.GetOperandThroughParenthesis().NotNull();
                    return(CreateStatement(factory, expression));
                });

                var razorStatement = RazorUtil.FixExpressionToStatement(expressionRange, psiServices);
                if (razorStatement != null)
                {
                    return(psiServices.DoTransaction(ExpandCommandName, () =>
                    {
                        var statement = razorStatement.ReplaceBy(newStatement);

                        // force Razor's bracing style
                        var languageService = statement.Language.LanguageService().NotNull();
                        var formatter = languageService.CodeFormatter.NotNull();
                        formatter.Format(statement, CodeFormatProfile.SOFT, NullProgressIndicator.Instance);

                        return statement;
                    }));
                }

                Logger.Fail("Failed to resolve target statement to replace");
                return(null);
            }

            return(psiServices.DoTransaction(ExpandCommandName, () =>
            {
                var expression = csharpContext.Expression.GetOperandThroughParenthesis().NotNull();
                var newStatement = CreateStatement(factory, expression);

                Assertion.AssertNotNull(targetStatement, "targetStatement != null");
                Assertion.Assert(targetStatement.IsPhysical(), "targetStatement.IsPhysical()");

                // Sometimes statements produced by templates are unfinished (for example, because of
                // parentheses insertion mode in R#), so the created statements has error element at and,
                // prefixed with single-characted whitespace. We remove this whitespace here:
                var errorElement = newStatement.LastChild as IErrorElement;
                if (errorElement != null)
                {
                    var whitespaceNode = errorElement.PrevSibling as IWhitespaceNode;
                    if (whitespaceNode != null && !whitespaceNode.IsNewLine && whitespaceNode.GetText() == " ")
                    {
                        using (WriteLockCookie.Create(newStatement.IsPhysical()))
                        {
                            LowLevelModificationUtil.DeleteChild(whitespaceNode);
                        }
                    }
                }

                return targetStatement.ReplaceBy(newStatement);
            }));
        }