/// <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) { IAttributesOwnerDeclaration declaration = Utils.GetTypeClosestToTextControl <IAttributesOwnerDeclaration>(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); 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); IPropertyAssignment propertyAssignment = factory.CreatePropertyAssignment( "Justification", factory.CreateExpression("\"$0\"", justificationText)); attribute.AddPropertyAssignmentAfter(propertyAssignment, null); declaration.AddAttributeAfter(attribute, null); } }
public static IAttribute GetAttribute <TAttribute>([NotNull] this IAttributesOwnerDeclaration attributesOwner) where TAttribute : Attribute { Type reflectionType = typeof(TAttribute); return(attributesOwner.Attributes.FirstOrDefault(x => AttributeMatchedReflectionType(x, reflectionType))); }
public static IType GetAttributeArgumentTypeValue <TAttribute>( [NotNull] this IAttributesOwnerDeclaration attributesOwner, int argumentPosition) where TAttribute : Attribute { return(attributesOwner.GetAttribute <TAttribute>()?.GetArgumentTypeValue(argumentPosition)); }
public static IAttribute AddAttributeToSingleDeclaration([CanBeNull] IAttributesOwnerDeclaration fieldDeclaration, IClrTypeName attributeTypeName, [NotNull] AttributeValue[] attributeValues, IPsiModule module, CSharpElementFactory elementFactory, bool allowMultiply = false) { if (fieldDeclaration == null) { return(null); } // TODO: Should we do this check here? var existingAttribute = GetAttribute(fieldDeclaration, attributeTypeName); if (existingAttribute != null && !allowMultiply) { return(null); } var attribute = CreateAttribute(attributeTypeName, attributeValues, module, elementFactory); if (attribute != null) { // This will split a multiple declaration, if necessary return(fieldDeclaration.AddAttributeAfter(attribute, null)); } return(null); }
public static void RemoveSpecificAttributes( [NotNull] IAttributesOwnerDeclaration attributesOwner, [NotNull, ItemNotNull] IEnumerable <string> shortNames, [NotNull] CodeAnnotationsConfiguration codeAnnotationConfig) { var candidatesToRemove = attributesOwner.AttributesEnumerable .Where(attr => shortNames.Any(name => codeAnnotationConfig.IsAnnotationAttribute(attr.GetAttributeInstance(), name))) .ToList(); candidatesToRemove.ForEach(attributesOwner.RemoveAttribute); }
private protected AttributeHighlighting( [NotNull] IAttributesOwnerDeclaration attributesOwnerDeclaration, [NotNull] IAttribute attribute, bool includeAttributeBracketsInRange, [NotNull] string message) : base(message) { AttributesOwnerDeclaration = attributesOwnerDeclaration; Attribute = attribute; this.includeAttributeBracketsInRange = includeAttributeBracketsInRange; }
static void TryGetContainerTypeAndAsyncKeyword( [NotNull] IParametersOwnerDeclaration container, [CanBeNull] out IType type, [CanBeNull] out ITokenNode asyncKeyword, [CanBeNull] out Action removeAsync, [CanBeNull] out IAttributesOwnerDeclaration attributesOwnerDeclaration) { switch (container) { case IMethodDeclaration methodDeclaration: type = methodDeclaration.Type; asyncKeyword = methodDeclaration.ModifiersList?.Modifiers.FirstOrDefault( node => node?.GetTokenType() == CSharpTokenType.ASYNC_KEYWORD); removeAsync = () => methodDeclaration.SetAsync(false); attributesOwnerDeclaration = type.IsValueTask() || type.IsGenericValueTask() || methodDeclaration.IsNullableAnnotationsContextEnabled() ? null : methodDeclaration; return; case ILambdaExpression lambdaExpression: type = lambdaExpression.ReturnType; asyncKeyword = lambdaExpression.AsyncKeyword; removeAsync = () => lambdaExpression.SetAsync(false); attributesOwnerDeclaration = null; return; case IAnonymousMethodExpression anonymousMethodExpression: type = anonymousMethodExpression.ReturnType; asyncKeyword = anonymousMethodExpression.AsyncKeyword; removeAsync = () => anonymousMethodExpression.SetAsync(false); attributesOwnerDeclaration = null; return; case ILocalFunctionDeclaration localFunctionDeclaration: type = localFunctionDeclaration.Type; asyncKeyword = localFunctionDeclaration.ModifiersList?.Modifiers.FirstOrDefault( node => node?.GetTokenType() == CSharpTokenType.ASYNC_KEYWORD); removeAsync = () => localFunctionDeclaration.SetAsync(false); attributesOwnerDeclaration = null; return; default: type = null; asyncKeyword = null; removeAsync = null; attributesOwnerDeclaration = null; return; } }
public static IType GetAttributeArgumentTypeValue <TAttribute, TPropertyType>( [NotNull] this IAttributesOwnerDeclaration attributesOwner, [NotNull] Expression <Func <TAttribute, TPropertyType> > propertyExpression) where TAttribute : Attribute { string propertyName = GetPropertyNameFromExpression(propertyExpression); if (propertyName != null) { return(attributesOwner.GetAttribute <TAttribute>()?.GetArgumentTypeValue(propertyName)); } return(null); }
internal RedundantAwaitSuggestion( [NotNull] string message, [NotNull] Action removeAsync, [NotNull] IAwaitExpression awaitExpression, [CanBeNull] IExpressionStatement statementToBeReplacedWithReturnStatement, [NotNull] ICSharpExpression expressionToReturn, [CanBeNull] IAttributesOwnerDeclaration attributesOwnerDeclaration) : base(message) { RemoveAsync = removeAsync; AwaitExpression = awaitExpression; StatementToBeReplacedWithReturnStatement = statementToBeReplacedWithReturnStatement; ExpressionToReturn = expressionToReturn; AttributesOwnerDeclaration = attributesOwnerDeclaration; }
/// <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) { IDeclaration declaration = Utils.GetDeclarationClosestToTextControl(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; if (attributesOwnerDeclaration != null) { 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); IFile file = declaration.GetContainingFile(); if (file != null) { LanguageService languageService = CSharpLanguage.Instance.LanguageService(); if (languageService != null) { ICSharpCodeFormatter codeFormatter = (ICSharpCodeFormatter)languageService.CodeFormatter; if (codeFormatter != null) { codeFormatter.FormatFile(file, CodeFormatProfile.DEFAULT, NullProgressIndicator.Instance); } } } } } }
public static bool ContainsAttribute([NotNull] this IAttributesOwnerDeclaration declaration, IEnumerable <string> attributeNames) { var clrTypeNames = attributeNames.Select(x => new ClrTypeName(x)).ToHashSet(); if (clrTypeNames.IsNullOrEmpty()) { return(false); } return(declaration .AttributesEnumerable .Select(attribute => attribute.Name.Reference.Resolve().DeclaredElement) .OfType <IClass>() .Select(attributeClass => attributeClass.GetClrName()) .Any(clrTypeNames.Contains)); }
public static void CreateAndAddAnnotationAttribute([NotNull] IAttributesOwnerDeclaration ownerDeclaration, [NotNull] string newAttributeShortName) { var codeAnnotationConfig = ownerDeclaration.GetPsiServices().GetComponent <CodeAnnotationsConfiguration>(); var pureAttributeType = codeAnnotationConfig.GetAttributeTypeForElement(ownerDeclaration, newAttributeShortName); if (pureAttributeType == null) { return; } var elementFactory = CSharpElementFactory.GetInstance(ownerDeclaration); var attribute = elementFactory.CreateAttribute(pureAttributeType); ownerDeclaration.AddAttributeAfter(attribute, null); }
/// <summary>Sets the attribute.</summary> /// <param name="owner">The owner.</param> /// <param name="attributeShortName">Short name of the attribute.</param> public static void SetAttribute([NotNull] IAttributesOwnerDeclaration owner, [NotNull] string attributeShortName) { if (owner == null) { throw new ArgumentNullException("owner"); } if (!owner.IsValid()) { return; } if (attributeShortName == null) { throw new ArgumentNullException("attributeShortName"); } var psiServices = owner.GetPsiServices(); if (psiServices == null) { throw new InvalidOperationException("psiServices"); } var cache = psiServices.GetCodeAnnotationsCache(); if (cache == null) { return; } var attributeTypeElement = cache.GetAttributeTypeForElement(owner, attributeShortName); if (attributeTypeElement == null) { return; } var factory = CSharpElementFactory.GetInstance(owner.GetPsiModule()); var attribute = factory.CreateAttribute(attributeTypeElement); owner.AddAttributeAfter(attribute, null); }
static void AddRedundantAwaitHighlightings( [NotNull] IHighlightingConsumer consumer, [NotNull] ITokenNode asyncKeyword, [NotNull] Action removeAsync, [NotNull] IAwaitExpression awaitExpression, [CanBeNull] IExpressionStatement statementToBeReplacedWithReturnStatement, [NotNull] ICSharpExpression expressionToReturn, [CanBeNull] IAttributesOwnerDeclaration attributesOwnerDeclaration, [CanBeNull] IInvocationExpression configureAwaitInvocationExpression = null) { var configureAwaitNode = configureAwaitInvocationExpression?.InvokedExpression?.LastChild; var highlightConfigureAwait = configureAwaitNode != null && configureAwaitInvocationExpression.ArgumentList != null; var highlighting = new RedundantAwaitSuggestion( $"Redundant 'await' (remove 'async'/'await'{(highlightConfigureAwait ? "/'" + nameof(Task.ConfigureAwait) + "(...)'" : "")})", removeAsync, awaitExpression, statementToBeReplacedWithReturnStatement, expressionToReturn, attributesOwnerDeclaration); consumer.AddHighlighting(highlighting, awaitExpression.AwaitKeyword.GetDocumentRange()); consumer.AddHighlighting(highlighting, asyncKeyword.GetDocumentRange(), isSecondaryHighlighting: true); if (highlightConfigureAwait) { var dotToken = configureAwaitNode.GetPreviousMeaningfulToken(); var leftParenthesisToken = configureAwaitInvocationExpression.ArgumentList.GetPreviousMeaningfulToken(); var rightParenthesisToken = configureAwaitInvocationExpression.ArgumentList.GetNextMeaningfulToken(); consumer.AddHighlighting( highlighting, configureAwaitNode.GetDocumentRange() .JoinLeft(dotToken.GetDocumentRange()) .JoinRight( configureAwaitInvocationExpression.ArgumentList.GetDocumentRange() .JoinLeft(leftParenthesisToken.GetDocumentRange()) .JoinRight(rightParenthesisToken.GetDocumentRange())), isSecondaryHighlighting: true); } }
public static IEnumerable <IAttribute> GetAttributes([CanBeNull] IAttributesOwnerDeclaration attributesOwner, IClrTypeName requiredAttributeTypeName) { if (attributesOwner == null) { yield break; } foreach (var attribute in attributesOwner.AttributesEnumerable) { if (attribute.TypeReference?.Resolve().DeclaredElement is ITypeElement typeElement) { var attributeTypeName = typeElement.GetClrName(); if (Equals(attributeTypeName, requiredAttributeTypeName)) { yield return(attribute); } } } }
public sealed override bool IsAvailable(JetBrains.Util.IUserDataHolder cache) { attributesOwnerDeclaration = provider.GetSelectedElement<IAttributesOwnerDeclaration>(true, false); if (attributesOwnerDeclaration != null && attributesOwnerDeclaration.GetNameRange().Contains(provider.SelectedTreeRange) && !attributesOwnerDeclaration.OverridesInheritedMember() && !attributesOwnerDeclaration.AttributesEnumerable.Any(IsAttribute)) { createAttributeFactory = CreateAttributeFactoryIfAvailable(attributesOwnerDeclaration, provider.PsiModule, out attributeToRemove); if (createAttributeFactory != null) { return true; } } attributeToRemove = null; createAttributeFactory = null; attributesOwnerDeclaration = null; return false; }
protected sealed override Func <CSharpElementFactory, IAttribute> CreateAttributeFactoryIfAvailable( IAttributesOwnerDeclaration attributesOwnerDeclaration, IPsiModule psiModule, out IAttribute attributeToReplace) { attributeToReplace = null; if (CanBeAnnotated(attributesOwnerDeclaration.DeclaredElement)) { return(factory => { Debug.Assert(factory != null); var fullName = typeof(A).FullName; Debug.Assert(fullName != null); return factory.CreateAttribute(new SpecialAttributeInstance(new ClrTypeName(fullName), psiModule)); }); } return(null); }
/// <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) { IDeclaration declaration = Utils.GetDeclarationClosestToTextControl(solution, textControl); if (declaration != null) { string rulesNamespace = this.Rule.Namespace; string ruleText = string.Format("{0}:{1}", this.Rule.CheckId, this.Rule.Name); string justificationText = StyleCopOptions.Instance.SuppressStyleCopAttributeJustificationText; IAttributesOwnerDeclaration attributesOwnerDeclaration = declaration as IAttributesOwnerDeclaration; if (attributesOwnerDeclaration != null) { 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); IFile file = declaration.GetContainingFile(); CSharpFormatterHelper.FormatterInstance.FormatFile( file, SolutionCodeStyleSettings.GetInstance(solution).CodeStyleSettings, CodeFormatProfile.DEFAULT, NullProgressIndicator.Instance); } } }
protected sealed override Func<CSharpElementFactory, IAttribute> CreateAttributeFactoryIfAvailable( IAttributesOwnerDeclaration attributesOwnerDeclaration, IPsiModule module, out IAttribute attributeToRemove) { var attributeType = attributesOwnerDeclaration.GetPsiServices() .GetComponent<CodeAnnotationsConfiguration>() .GetAttributeTypeForElement(attributesOwnerDeclaration, AnnotationAttributeTypeName); if (attributeType != null && CanBeAnnotated(attributesOwnerDeclaration.DeclaredElement, attributesOwnerDeclaration, module)) { attributeToRemove = TryGetAttributeToReplace(attributesOwnerDeclaration); return factory => { Debug.Assert(factory != null); return factory.CreateAttribute(attributeType); }; } attributeToRemove = null; return null; }
protected sealed override Func <CSharpElementFactory, IAttribute> CreateAttributeFactoryIfAvailable( IAttributesOwnerDeclaration attributesOwnerDeclaration, IPsiModule psiModule, out IAttribute attributeToRemove) { var attributeType = attributesOwnerDeclaration.GetPsiServices() .GetComponent <CodeAnnotationsConfiguration>() .GetAttributeTypeForElement(attributesOwnerDeclaration, AnnotationAttributeTypeName); if (attributeType != null && CanBeAnnotated(attributesOwnerDeclaration.DeclaredElement, attributesOwnerDeclaration, psiModule)) { attributeToRemove = TryGetAttributeToReplace(attributesOwnerDeclaration); return(factory => { Debug.Assert(factory != null); return factory.CreateAttribute(attributeType); }); } attributeToRemove = null; return(null); }
protected override IAttribute TryGetAttributeToReplace(IAttributesOwnerDeclaration ownerDeclaration) => ownerDeclaration.AttributesEnumerable.FirstOrDefault( attribute => attribute.AssertNotNull().GetAttributeInstance().GetAttributeType().GetClrName().ShortName == PureAnnotationProvider.PureAttributeShortName);
/// <summary> /// If the declaration or its parent has the rule provided suppressed it returns true. /// </summary> /// <param name="attributesOwnerDeclaration"> /// The declaration to check. /// </param> /// <param name="ruleId"> /// The ruleId to see if its suppressed. /// </param> /// <returns> /// True if suppressed. /// </returns> private static bool IsRuleSuppressedInternal(IAttributesOwnerDeclaration attributesOwnerDeclaration, string ruleId) { if (attributesOwnerDeclaration != null) { CSharpElementFactory factory = CSharpElementFactory.GetInstance(attributesOwnerDeclaration.GetPsiModule()); ITypeElement typeElement = Utils.GetTypeElement(attributesOwnerDeclaration, "System.Diagnostics.CodeAnalysis.SuppressMessageAttribute"); IAttribute attribute = factory.CreateAttribute(typeElement); foreach (IAttribute s in attributesOwnerDeclaration.Attributes) { if (s.Name.ShortName == attribute.Name.ShortName) { ICSharpLiteralExpression b = s.ConstructorArgumentExpressions[1] as ICSharpLiteralExpression; if (b == null) { return false; } string d = b.GetText(); if (string.IsNullOrEmpty(d)) { return false; } string e = d.Trim('\"').Substring(2); // removes the 'SA' bit string f = ruleId.Substring(2); // removes the 'SA' bit return e == f; } } } return false; }
internal RedundantAnnotationHighlighting( [NotNull] IAttributesOwnerDeclaration attributesOwnerDeclaration, [NotNull] IAttribute attribute, [NotNull] string message) : base(attributesOwnerDeclaration, attribute, false, message) { }
internal MissingAnnotationHighlighting([NotNull] string message, [NotNull] IAttributesOwnerDeclaration declaration) : base(message) => this.declaration = declaration;
internal MissingSuppressionJustificationHighlighting( [NotNull] IAttributesOwnerDeclaration attributesOwnerDeclaration, [NotNull] IAttribute attribute, [NotNull] string message) : base(attributesOwnerDeclaration, attribute, false, message) { }
public static IAttribute GetAttribute([NotNull] this IAttributesOwnerDeclaration attributesOwner, [NotNull] string name) { return(attributesOwner.Attributes.FirstOrDefault(x => x.Name.QualifiedName == name)); }
internal ConflictingAnnotationWarning( [NotNull] IAttributesOwnerDeclaration attributesOwnerDeclaration, [NotNull] IAttribute attribute, [NotNull] string message) : base(attributesOwnerDeclaration, attribute, false, message) { }
protected override IAttribute TryGetAttributeToReplace(IAttributesOwnerDeclaration ownerDeclaration) => ownerDeclaration.Attributes.FirstOrDefault( attribute => attribute.AssertNotNull().GetAttributeInstance().GetAttributeType().GetClrName().ShortName == MustUseReturnValueAnnotationProvider.MustUseReturnValueAttributeShortName);
internal ConditionalAnnotationHint( [NotNull] IAttributesOwnerDeclaration attributesOwnerDeclaration, [NotNull] IAttribute attribute, [NotNull] string message) : base(attributesOwnerDeclaration, attribute, true, message) { }
public static IAttribute AddAttributeToSingleDeclaration([CanBeNull] IAttributesOwnerDeclaration fieldDeclaration, IClrTypeName attributeTypeName, IPsiModule module, CSharpElementFactory elementFactory) { return(AddAttributeToSingleDeclaration(fieldDeclaration, attributeTypeName, EmptyArray <AttributeValue> .Instance, module, elementFactory)); }
protected sealed override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) { Debug.Assert(attributesOwnerDeclaration != null); Debug.Assert(createAttributeFactory != null); try { using (WriteLockCookie.Create()) { var factory = CSharpElementFactory.GetInstance(provider.PsiModule); var attribute = createAttributeFactory(factory); Debug.Assert(attribute != null); attributesOwnerDeclaration.AddAttributeAfter(attribute, attributeToRemove); if (attributeToRemove != null) { attributesOwnerDeclaration.RemoveAttribute(attributeToRemove); } ContextActionUtils.FormatWithDefaultProfile(attribute); } return _ => { }; } finally { attributeToRemove = null; createAttributeFactory = null; attributesOwnerDeclaration = null; } }
protected virtual IAttribute TryGetAttributeToReplace([NotNull] IAttributesOwnerDeclaration ownerDeclaration) => null;
public static bool HasAttribute([NotNull] this IAttributesOwnerDeclaration attributesOwner, [NotNull] string name) { return(attributesOwner.GetAttribute(name) != null); }
public static bool HasAttribute <TAttribute>([NotNull] this IAttributesOwnerDeclaration attributesOwner) where TAttribute : Attribute { return(attributesOwner.GetAttribute <TAttribute>() != null); }
public static IAttribute GetAttribute([CanBeNull] IAttributesOwnerDeclaration attributesOwner, IClrTypeName requiredAttributeTypeName) { return(GetAttributes(attributesOwner, requiredAttributeTypeName).FirstOrDefault(null)); }