protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            IInvocationExpression newExpression;

            using (WriteLockCookie.Create())
            {
                var factory = CSharpElementFactory.GetInstance(myWarningCreationExpression);
                newExpression = (IInvocationExpression)factory.CreateExpression("gameObject.AddComponent<$0>()", myWarningCreationExpression.ExplicitType());
                newExpression = ModificationUtil.ReplaceChild(myWarningCreationExpression, newExpression);
            }

            return(textControl =>
            {
                var qualifier = newExpression.ExtensionQualifier;
                Assertion.AssertNotNull(qualifier, "qualifier != null");
                var hotspotExpression = new MacroCallExpressionNew(new SuggestVariableOfTypeMacroDef());
                hotspotExpression.AddParameter(new ConstantMacroParameter("UnityEngine.GameObject"));
                var field = new TemplateField("gameObject", hotspotExpression, 0);
                HotspotInfo[] fieldInfos =
                {
                    new HotspotInfo(field, qualifier.GetDocumentRange())
                };

                var manager = LiveTemplatesManager.Instance;
                var invalidRange = DocumentRange.InvalidRange;

                var session = manager.CreateHotspotSessionAtopExistingText(solution, invalidRange,
                                                                           textControl, LiveTemplatesManager.EscapeAction.LeaveTextAndCaret, fieldInfos);
                session.Execute();
            });
        }
Exemplo n.º 2
0
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            var literalExpression = _highlighting.Expression;

            if (!literalExpression.IsValid())
            {
                return(null);
            }

            var containingFile = literalExpression.GetContainingFile();
            var psiModule      = literalExpression.GetPsiModule();
            var elementFactory = CSharpElementFactory.GetInstance(literalExpression);

            IExpression newExpression = null;

            literalExpression.GetPsiServices().Transactions.Execute(GetType().Name, () =>
            {
                using (solution.GetComponent <IShellLocks>().UsingWriteLock())
                    newExpression = ModificationUtil.ReplaceChild(
                        literalExpression.Task, elementFactory.CreateExpression("$0.ConfigureAwait($1)", literalExpression.Task,
                                                                                elementFactory.CreateExpressionByConstantValue(CSharpConstantValueFactory.CreateBoolValue(_value, psiModule))));
            });

            if (newExpression != null)
            {
                var marker = newExpression.GetDocumentRange().CreateRangeMarker(solution.GetComponent <DocumentManager>());
                containingFile.OptimizeImportsAndRefs(marker, false, true, NullProgressIndicator.Create());
            }

            return(null);
        }
Exemplo n.º 3
0
        public void Execute(AccessRights accessRights)
        {
            var factory = CSharpElementFactory.GetInstance(Context.ParameterDeclaration);

            CreateStatement(factory, Context.Parameter.CreateExpression(Context.Parameter) as ICSharpExpression,
                            Context.SourceFile, accessRights);
        }
Exemplo n.º 4
0
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            var psiModule = error.CSharpLiteralExpression.GetPsiModule();
            var factory   = CSharpElementFactory.GetInstance(error.CSharpLiteralExpression);
            var taskType  = TypeFactory.CreateTypeByCLRName("System.Threading.Tasks.Task", psiModule);

            if (error.ReturnType.IsTask())
            {
                var completedTask = factory.CreateReferenceExpression("$0.CompletedTask", taskType);
                error.CSharpLiteralExpression.ReplaceBy(completedTask);
            }
            else if (error.ReturnType.IsGenericTask())
            {
                var declaredReturnType = error.ReturnType as IDeclaredType;
                if (declaredReturnType == null)
                {
                    return(null);
                }

                var substitution     = declaredReturnType.GetSubstitution();
                var genericParameter = substitution.Apply(substitution.Domain[0]);
                var wrappedNull      = factory.CreateExpression(
                    genericParameter.IsStructType() ? "$0.FromResult(default($1))" : "$0.FromResult<$1>(null)",
                    taskType,
                    genericParameter);
                error.CSharpLiteralExpression.ReplaceBy(wrappedNull);
            }
            return(null);
        }
Exemplo n.º 5
0
 protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
 {
     using (WriteLockCookie.Create())
     {
         var qualifierOperand    = (myRewriteLeftOperand ? myExpression.LeftOperand : myExpression.RightOperand) as IReferenceExpression;
         var qualifierExpression = qualifierOperand?.QualifierExpression;
         var otherOperand        = myRewriteLeftOperand ? myExpression.RightOperand : myExpression.LeftOperand;
         var factory             = CSharpElementFactory.GetInstance(myExpression);
         ICSharpExpression newExpression;
         if (qualifierExpression != null)
         {
             newExpression = factory.CreateExpression("$0$1.CompareTag($2)",
                                                      myExpression.EqualityType == EqualityExpressionType.EQEQ ? string.Empty : "!",
                                                      qualifierExpression, otherOperand);
         }
         else
         {
             newExpression = factory.CreateExpression("$0CompareTag($1)",
                                                      myExpression.EqualityType == EqualityExpressionType.EQEQ ? string.Empty : "!",
                                                      otherOperand);
         }
         ModificationUtil.ReplaceChild(myExpression, newExpression);
     }
     return(null);
 }
 private IModifiersList GetModifierList(ITreeNode declaration)
 {
     return
         (((IMethodDeclaration)
           CSharpElementFactory.GetInstance(declaration)
           .CreateTypeMemberDeclaration(this.Modifier + " void Foo(){}")).ModifiersList);
 }
Exemplo n.º 7
0
        /// <summary>
        /// The execute inner.
        /// </summary>
        /// <param name="solution">
        /// The solution.
        /// </param>
        /// <param name="textControl">
        /// The text control.
        /// </param>
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            ICSharpModifiersOwnerDeclaration declaration = Utils.GetTypeClosestToTextControl <ICSharpModifiersOwnerDeclaration>(solution, textControl);

            if (declaration != null)
            {
                string rulesNamespace = this.Rule.Namespace;

                string ruleText = string.Format("{0}:{1}", this.Rule.CheckId, this.Rule.Name);

                IContextBoundSettingsStore settingsStore = PsiSourceFileExtensions.GetSettingsStore(null, solution);

                string justificationText = settingsStore.GetValue((StyleCopOptionsSettingsKey key) => key.SuppressStyleCopAttributeJustificationText);

                IAttributesOwnerDeclaration attributesOwnerDeclaration = declaration as IAttributesOwnerDeclaration;

                CSharpElementFactory factory = CSharpElementFactory.GetInstance(declaration.GetPsiModule());

                ITypeElement typeElement = Utils.GetTypeElement(declaration, "System.Diagnostics.CodeAnalysis.SuppressMessageAttribute");

                IAttribute attribute = factory.CreateAttribute(typeElement);

                ICSharpArgument newArg1 = attribute.AddArgumentAfter(Utils.CreateConstructorArgumentValueExpression(declaration.GetPsiModule(), rulesNamespace), null);

                ICSharpArgument newArg2 = attribute.AddArgumentAfter(Utils.CreateConstructorArgumentValueExpression(declaration.GetPsiModule(), ruleText), newArg1);

                attribute.AddArgumentAfter(Utils.CreateArgumentValueExpression(declaration.GetPsiModule(), "Justification = \"" + justificationText + "\""), newArg2);

                attributesOwnerDeclaration.AddAttributeAfter(attribute, null);
            }
        }
        private static ILookupItem CreateMethodItem(CSharpCodeCompletionContext context, UnityEventFunction eventFunction,
                                                    IClassLikeDeclaration declaration)
        {
            if (CSharpLanguage.Instance == null)
            {
                return(null);
            }

            var method = eventFunction.CreateDeclaration(CSharpElementFactory.GetInstance(declaration), declaration);

            if (method.DeclaredElement == null)
            {
                return(null);
            }

            var instance            = new DeclaredElementInstance(method.DeclaredElement);
            var declaredElementInfo = new DeclaredElementInfo(method.DeclaredName, instance, CSharpLanguage.Instance,
                                                              context.BasicContext.LookupItemsOwner, context, context.BasicContext);

            return(LookupItemFactory.CreateLookupItem(declaredElementInfo).
                   WithPresentation(
                       _ => new GenerateMemberPresentation(declaredElementInfo, PresenterStyles.DefaultPresenterStyle)).
                   WithBehavior(_ =>
            {
                var behavior = new UnityEventFunctionBehavior(declaredElementInfo, eventFunction);
                behavior.InitializeRanges(context.CompletionRanges, context.BasicContext);
                return behavior;
            }).
                   WithMatcher(_ => new DeclaredElementMatcher(declaredElementInfo, context.BasicContext.IdentifierMatchingStyle)));
        }
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator _)
        {
            var methodDeclaration = Highlighting.MethodDeclaration;

            var elementFactory = CSharpElementFactory.GetInstance(methodDeclaration);

            var parameterDeclaration = methodDeclaration.AddParameterDeclarationBefore(
                elementFactory.CreateParameterDeclaration(
                    ParameterKind.VALUE,
                    isParametric: false,
                    isVarArg: false,
                    type: Highlighting.ArgumentExpression.Type(),
                    name: "newParameter",
                    defaultValue: null), anchor: null);

            return(textControl =>
            {
                var endSelectionRange = DocumentRange.InvalidRange;
                var hotspotNode = parameterDeclaration.NameIdentifier;

                var hotspotSession = textControl.CreateHotspotSessionAtopExistingText(solution, endSelectionRange, hotspotNode);

                hotspotSession.Execute();
            });
        }
Exemplo n.º 10
0
        public void Execute(ISolution solution, ITextControl textControl)
        {
            if (!_literalExpression.IsValid())
            {
                return;
            }

            var containingFile = _literalExpression.GetContainingFile();
            var psiModule      = _literalExpression.GetPsiModule();
            var elementFactory = CSharpElementFactory.GetInstance(psiModule);

            IExpression newExpression = null;

            _literalExpression.GetPsiServices().Transactions.Execute(GetType().Name, () =>
            {
                using (solution.GetComponent <IShellLocks>().UsingWriteLock())
                    newExpression = ModificationUtil.ReplaceChild(
                        _literalExpression.Task, elementFactory.CreateExpression("$0.ConfigureAwait($1)", _literalExpression.Task,
                                                                                 elementFactory.CreateExpressionByConstantValue(CSharpConstantValueFactory.CreateBoolValue(_value, psiModule))));
            });

            if (newExpression != null)
            {
                IRangeMarker marker = newExpression.GetDocumentRange().CreateRangeMarker(solution.GetComponent <DocumentManager>());
                containingFile.OptimizeImportsAndRefs(marker, false, true, NullProgressIndicator.Instance);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Process local variable declaration.
        /// </summary>
        /// <param name="localVariableDeclaration">
        /// The local variable declaration.
        /// </param>
        private static void ProcessLocalVariableDeclaration(ILocalVariableDeclaration localVariableDeclaration)
        {
            IMultipleLocalVariableDeclaration multipleDeclaration = MultipleLocalVariableDeclarationNavigator.GetByDeclarator(localVariableDeclaration);

            if (multipleDeclaration.Declarators.Count > 1)
            {
                IType newType = CSharpTypeFactory.CreateType(multipleDeclaration.TypeUsage);

                using (WriteLockCookie.Create(true))
                {
                    multipleDeclaration.SetTypeUsage(CSharpElementFactory.GetInstance(localVariableDeclaration.GetPsiModule()).CreateTypeUsageNode(newType));
                }
            }
            else
            {
                ILocalVariable variable = localVariableDeclaration.DeclaredElement;
                if (variable != null)
                {
                    if (!multipleDeclaration.IsVar)
                    {
                        using (WriteLockCookie.Create(true))
                        {
                            localVariableDeclaration.SetType(variable.Type);
                        }
                    }
                }
            }
        }
        public void Process(IPsiSourceFile sourceFile, IRangeMarker rangeMarker, CodeCleanupProfile profile, IProgressIndicator progressIndicator)
        {
            var file = sourceFile.GetNonInjectedPsiFile <CSharpLanguage>();

            if (file == null)
            {
                return;
            }

            if (!profile.GetSetting(DescriptorInstance))
            {
                return;
            }

            CSharpElementFactory elementFactory = CSharpElementFactory.GetInstance(sourceFile.PsiModule);

            file.GetPsiServices().PsiManager.DoTransaction(
                () =>
            {
                using (_shellLocks.UsingWriteLock())
                    file.ProcessChildren <IExpression>(
                        expression =>
                    {
                        ConstantValue value = expression.ConstantValue;
                        if (value.IsInteger() && Convert.ToInt32(value.Value) == int.MaxValue)
                        {
                            ModificationUtil.ReplaceChild(expression, elementFactory.CreateExpression("int.MaxValue"));
                        }
                    }
                        );
            },
                "Code cleanup");
        }
        private bool TryConvertSyncToAwaitWaiting([NotNull] IInvocationExpression invocationExpression)
        {
            var reference = invocationExpression.Parent as IReferenceExpression;

            var factory = CSharpElementFactory.GetInstance(invocationExpression);

            //TODO: AwaitResult our custom method extension, it must be moved to settings
            if (reference?.NameIdentifier?.Name == "AwaitResult" || reference?.NameIdentifier?.Name == "Wait")
            {
                var call = factory.CreateExpression("await $0($1).ConfigureAwait(false)", invocationExpression.ConditionalQualifier,
                                                    invocationExpression.ArgumentList);
                var parentInvocation = reference.Parent as IInvocationExpression;
                if (parentInvocation == null)
                {
                    return(false);
                }
                parentInvocation.ReplaceBy(call);
                return(true);
            }

            if (reference?.NameIdentifier?.Name == "Result")
            {
                var call = factory.CreateExpression("await $0($1).ConfigureAwait(false)", invocationExpression.ConditionalQualifier,
                                                    invocationExpression.ArgumentList);
                reference.ReplaceBy(call);
                return(true);
            }
            return(false);
        }
Exemplo n.º 14
0
        private static IBlock CreateMethodBody(ICSharpDeclaration declaration, MethodImplementationKind implementationKind)
        {
            var factory = CSharpElementFactory.GetInstance(declaration);

            switch (implementationKind)
            {
            case MethodImplementationKind.ThrowNotImplemented:
            {
                var predefinedType = declaration.GetPredefinedType();
                return(factory.CreateBlock("{throw new $0();}", predefinedType.NotImplementedException));
            }

            case MethodImplementationKind.ReturnDefaultValue:
            {
                return(CSharpReturnStatementMemberBodyProvider.CreateBody(declaration));
            }

            case MethodImplementationKind.NotCompiledCode:
            {
                if (declaration.DeclaredElement is IMethod method && !method.ReturnType.IsVoid())
                {
                    return(factory.CreateBlock("{ return TODO_IMPLEMENT_ME; }"));
                }

                return(factory.CreateBlock("{ TODO_IMPLEMENT_ME(); }"));
            }

            default:
            {
                throw new ArgumentOutOfRangeException(nameof(implementationKind));
            }
            }
        }
 public TypeHandlingContext(CSharpGeneratorContext generatorContext)
 {
     GeneratorContext = generatorContext;
     ElementFactory   = CSharpElementFactory.GetInstance(generatorContext.Root.GetPsiModule());
     Builder          = new StringBuilder();
     Args             = new List <Object>();
     Variables        = new VariablesTracker();
 }
Exemplo n.º 16
0
        protected override ICSharpExpression CreateReplacementExpression(ICSharpExpression expression, IDeclaredElement declaredElement)
        {
            CSharpElementFactory factory = CSharpElementFactory.GetInstance(expression);

            return(factory.CreateReferenceExpression("$0.$1",
                                                     ((IReferenceExpression)expression).QualifierExpression,
                                                     declaredElement.ShortName));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Swap base to this unless local implementation.
        /// </summary>
        /// <param name="invocationExpression">
        /// The invocation expression.
        /// </param>
        public static void SwapBaseToThisUnlessLocalImplementation(IInvocationExpression invocationExpression)
        {
            bool isOverride = false;

            bool isNew = false;

            IPrimaryExpression invokedExpression = invocationExpression.InvokedExpression;

            if (invokedExpression != null)
            {
                IReferenceExpression referenceExpressionNode = invokedExpression as IReferenceExpression;

                if (referenceExpressionNode != null)
                {
                    IReferenceExpression referenceExpression = invokedExpression as IReferenceExpression;
                    if (referenceExpression != null)
                    {
                        ICSharpExpression qualifierExpression = referenceExpression.QualifierExpression;
                        if (qualifierExpression is IBaseExpression)
                        {
                            string methodName = referenceExpressionNode.NameIdentifier.Name;

                            ICSharpTypeDeclaration typeDeclaration = invocationExpression.GetContainingNode <ICSharpTypeDeclaration>(true);

                            if (typeDeclaration != null)
                            {
                                foreach (ICSharpTypeMemberDeclaration memberDeclaration in typeDeclaration.MemberDeclarations)
                                {
                                    if (memberDeclaration.DeclaredName == methodName)
                                    {
                                        IMethodDeclaration methodDeclaration = memberDeclaration as IMethodDeclaration;
                                        if (methodDeclaration != null)
                                        {
                                            isOverride = methodDeclaration.IsOverride;
                                            isNew      = methodDeclaration.IsNew();
                                            break;
                                        }
                                    }
                                }

                                if (isOverride || isNew)
                                {
                                    return;
                                }

                                using (WriteLockCookie.Create(true))
                                {
                                    // swap the base to this
                                    ICSharpExpression expression = CSharpElementFactory.GetInstance(invocationExpression.GetPsiModule()).CreateExpression("this");

                                    referenceExpression.SetQualifierExpression(expression);
                                }
                            }
                        }
                    }
                }
            }
        }
 protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
 {
     if (myPropertyDeclaration == null)
     {
         return(null);
     }
     return(AutoPropertyToSerializedBackingFieldAction.Execute(myPropertyDeclaration, solution,
                                                               CSharpElementFactory.GetInstance(myPropertyDeclaration)));
 }
        protected ContextActionExecutorBase(ICSharpStatement statement)
        {
            Contract.Requires(statement != null);

            _psiModule   = statement.GetPsiModule();
            _psiServices = statement.GetPsiServices();
            _factory     = CSharpElementFactory.GetInstance(statement);
            _currentFile = (ICSharpFile)statement.GetContainingFile();
        }
Exemplo n.º 20
0
 public InitializeComponentBulbActionBase(string name, ITypeElement typeElement,
                                          IClassDeclaration classDeclaration, string methodName)
 {
     myName             = name;
     myTypeElement      = typeElement;
     myClassDeclaration = classDeclaration;
     myMethodName       = methodName;
     myFactory          = CSharpElementFactory.GetInstance(classDeclaration);
 }
Exemplo n.º 21
0
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            var awaitExpression     = configureAwaitHighlighting.AwaitExpression;
            var factory             = CSharpElementFactory.GetInstance(awaitExpression);
            var taskWithConfiguring = factory.CreateExpression($"$0.ConfigureAwait({GetConfigureAwaitValueText()})", awaitExpression.Task);

            awaitExpression.Task.ReplaceBy(taskWithConfiguring);
            return(null);
        }
Exemplo n.º 22
0
        public static void SetDocComment(IDocCommentBlockOwnerNode docCommentBlockOwnerNode, string text, ISolution solution)
        {
            text = String.Format("///{0}\r\nclass Tmp {{}}", text.Replace("\n", "\n///"));

            ICSharpTypeMemberDeclaration declaration =
                CSharpElementFactory.GetInstance(docCommentBlockOwnerNode.GetPsiModule()).CreateTypeMemberDeclaration(text, new object[0]);

            docCommentBlockOwnerNode.SetDocCommentBlockNode(
                ((IDocCommentBlockOwnerNode)declaration).GetDocCommentBlockNode());
        }
        private IAttribute createAttributeDeclaration(ITypeElement attributeType, string fixedParamValue, string namedParamName, string namedParamValue, IPsiModule psiModule, IModuleReferenceResolveContext resolveContext, IAttribute originalAttribute)
        {
            var fixedArguments = createFixedArguments(fixedParamValue, psiModule, resolveContext);
            var namedArguments = createNamedArguments(namedParamName, namedParamValue, psiModule, resolveContext, originalAttribute);

            var elementFactory       = CSharpElementFactory.GetInstance(psiModule);
            var attributeDeclaration = elementFactory.CreateAttribute(attributeType, fixedArguments, namedArguments);

            return(attributeDeclaration);
        }
        public override void ProcessParameterReference(IReference reference)
        {
            var referenceExpression = reference as IReferenceExpression;

            if (referenceExpression != null)
            {
                CSharpElementFactory factory = CSharpElementFactory.GetInstance(referenceExpression.GetPsiModule());
                referenceExpression.ReplaceBy(factory.CreateExpression("typeof($0)", Workflow.TypeParameterName));
            }
        }
Exemplo n.º 25
0
            public void Accept(
                ITextControl textControl, TextRange nameRange, LookupItemInsertType lookupItemInsertType,
                Suffix suffix, ISolution solution, bool keepCaretStill)
            {
                textControl.Document.ReplaceText(nameRange, CASE_COMPLETION_NAME + "()");

                var psiServices = solution.GetPsiServices();

                psiServices.Files.CommitAllDocuments();

                var enumMember = Info.PreferredDeclaredElement;

                if (enumMember == null)
                {
                    return;
                }

                var invocationExpression = FindFakeInvocation(textControl, solution, nameRange.EndOffset);

                if (invocationExpression == null)
                {
                    return;
                }

                var factory  = CSharpElementFactory.GetInstance(invocationExpression);
                var template = (Info.IsFlagsEnum && !Info.IsZeroCase)
          ? (Info.IsMultiBitFlagCase ? "($0 & $1) != $1" : "($0 & $1) != 0")
          : "$0 == $1";

                var referenceExpression = (IReferenceExpression)invocationExpression.InvokedExpression;
                var qualifierExpression = referenceExpression.QualifierExpression;

                var enumMemberCheck = factory.CreateExpression(template, qualifierExpression, enumMember);

                var caretPointer = psiServices.DoTransaction(
                    commandName: typeof(EnumCaseCheckBehavior).FullName,
                    func: () =>
                {
                    using (WriteLockCookie.Create())
                    {
                        var memberCheck = invocationExpression.ReplaceBy(enumMemberCheck);
                        return(memberCheck.CreateTreeElementPointer());
                    }
                });

                if (caretPointer != null)
                {
                    var checkExpression = caretPointer.GetTreeNode();
                    if (checkExpression != null)
                    {
                        var offset = checkExpression.GetDocumentRange().TextRange.EndOffset;
                        textControl.Caret.MoveTo(offset, CaretVisualPlacement.DontScrollIfVisible);
                    }
                }
            }
Exemplo n.º 26
0
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            using (WriteLockCookie.Create())
            {
                var factory    = CSharpElementFactory.GetInstance(_stringLiteral.Expression, false);
                var expression = factory.CreateExpression(
                    $"\"{_stringLiteral.Expression.GetUnquotedText().Insert(_namedProperty.StartIndex + 1, "@")}\"");
                ModificationUtil.ReplaceChild(_stringLiteral.Expression, expression);
            }

            return(null);
        }
        protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            var factory = CSharpElementFactory.GetInstance(_theclass.GetPsiModule());

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

            AddProxyClass(_theclass, factory);
            return(null);
        }
 protected override Action <ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
 {
     using (WriteLockCookie.Create())
     {
         var leftOperand   = myExpression.LeftOperand;
         var rightOperand  = myExpression.RightOperand;
         var factory       = CSharpElementFactory.GetInstance(myExpression);
         var newExpression = factory.CreateExpression("$0?$0:$1", leftOperand, rightOperand);
         ModificationUtil.ReplaceChild(myExpression, newExpression);
     }
     return(null);
 }
Exemplo n.º 29
0
        /// <summary>
        /// Swap object creation to built in type.
        /// </summary>
        /// <param name="objectCreationExpressionNode">
        /// The object creation expression node.
        /// </param>
        private static void SwapObjectCreationToBuiltInType(IObjectCreationExpression objectCreationExpressionNode)
        {
            IPsiModule project = objectCreationExpressionNode.GetPsiModule();

            using (WriteLockCookie.Create(true))
            {
                IObjectCreationExpression tmpExpression =
                    (IObjectCreationExpression)
                    CSharpElementFactory.GetInstance(project).CreateExpression("new $0?()", new object[] { objectCreationExpressionNode.Type() });
                objectCreationExpressionNode.SetCreatedTypeUsage(tmpExpression.CreatedTypeUsage);
            }
        }
        public override MethodInvocation ProcessUsage(IReference reference)
        {
            var referenceExpression = reference.GetTreeNode() as IReferenceExpression;

            if (referenceExpression == null)
            {
                Driver.AddConflict(ReferenceConflict.CreateError(reference, "{0} can not be updated correctly.", "Usage"));
                return(null);
            }

            bool isExtensionMethod           = referenceExpression.IsExtensionMethod();
            IInvocationExpression invocation = InvocationExpressionNavigator.GetByInvokedExpression(referenceExpression);

            if (invocation == null)
            {
                Driver.AddConflict(ReferenceConflict.CreateError(reference, "{0} can not be updated correctly.", "Usage"));
                return(null);
            }

            ITreeNode element = GetArgument(invocation, isExtensionMethod);

            var   argument = element as ICSharpArgument;
            IType type     = argument != null?GetTypeOfValue(argument.Value) : GetTypeOfValue(element);

            if (type == null || !type.CanUseExplicitly(invocation))
            {
                Driver.AddConflict(ReferenceConflict.CreateError(
                                       reference, "Argument of {0} is not valid 'typeof' expression.", "usage"));
                return(null);
            }

            // we can rely on resolve result since method declaration is not yet changed.
            ResolveResultWithInfo resolveResult = reference.Resolve();
            ISubstitution         substitution  = resolveResult.Result.Substitution;
            var method = resolveResult.DeclaredElement as IMethod;

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

            if (argument != null)
            {
                invocation.RemoveArgument(argument);
                return(new MethodInvocation(reference, type, method, substitution));
            }

            CSharpElementFactory factory = CSharpElementFactory.GetInstance(invocation.GetPsiModule());
            IReferenceExpression newInvokedExpression =
                invocation.InvokedExpression.ReplaceBy(factory.CreateReferenceExpression("$0", Executer.Method));

            return(new MethodInvocation(newInvokedExpression.Reference, type, method, substitution));
        }