/// <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 override void VisitClassDeclaration(IClassDeclaration classDeclarationParam, IHighlightingConsumer context) { base.VisitClassDeclaration(classDeclarationParam, context); if (!classDeclarationParam.IsSynthetic() || !T4CSharpCodeGenerator.ClassName.Equals(classDeclarationParam.DeclaredName, StringComparison.Ordinal)) { return; } IDeclaredTypeUsage superTypeUsage = classDeclarationParam.SuperTypeUsageNodes.FirstOrDefault(); if (superTypeUsage == null || T4CSharpCodeGenerator.DefaultBaseClassName.Equals(superTypeUsage.GetText(), StringComparison.Ordinal)) { return; } ITypeElement typeElement = CSharpTypeFactory.CreateDeclaredType(superTypeUsage).GetTypeElement(); if (typeElement == null) { return; } if (!typeElement.Methods.Any(IsTransformTextMethod)) { context.AddHighlighting(new MissingTransformTextMethodHighlighting(superTypeUsage)); } }
private static void FixQualifierExpression([NotNull] ITextControl textControl, [NotNull] ICSharpExpression expression, [NotNull] ITypeElement ownerType) { var qualifierRange = expression.GetDocumentRange().TextRange; var comparer = DeclaredElementEqualityComparer.TypeElementComparer; // do not produce type qualifier when static method from containing type completed var typeDeclaration = expression.GetContainingTypeDeclaration(); if (typeDeclaration != null && comparer.Equals(typeDeclaration.DeclaredElement, ownerType)) { var reference = ReferenceExpressionNavigator.GetByQualifierExpression(expression).NotNull("reference != null"); var delimiter = reference.Delimiter; if (delimiter != null) { qualifierRange = qualifierRange.JoinRight(delimiter.GetDocumentRange().TextRange); } textControl.Document.ReplaceText(qualifierRange, string.Empty); } else { var keyword = CSharpTypeFactory.GetTypeKeyword(ownerType.GetClrName()); textControl.Document.ReplaceText(qualifierRange, keyword ?? "T"); } }
private void AddSpecflowStep(IPsiSourceFile targetFile, string classClrName, GherkinStepKind stepKind, string stepText) { var cSharpFile = targetFile.GetProject().GetCSharpFile(targetFile.DisplayName.Substring(targetFile.DisplayName.LastIndexOf('>') + 2)); if (cSharpFile == null) { return; } foreach (var type in cSharpFile.GetChildrenInSubtrees <IClassDeclaration>()) { if (!(type is IClassDeclaration classDeclaration)) { continue; } if (classDeclaration.CLRName != classClrName) { continue; } if (classDeclaration.DeclaredElement?.GetAttributeInstances(AttributesSource.Self).All(x => x.GetAttributeType().GetClrName().FullName != "TechTalk.SpecFlow.Binding") != true) { continue; } var factory = CSharpElementFactory.GetInstance(classDeclaration); var methodName = _stepDefinitionBuilder.GetStepDefinitionMethodNameFromStepText(stepKind, stepText, _reference.IsInsideScenarioOutline()); methodName = cSharpFile.GetPsiServices().Naming.Suggestion.GetDerivedName(methodName, NamedElementKinds.Method, ScopeKind.Common, CSharpLanguage.Instance, new SuggestionOptions(), targetFile); var parameters = _stepDefinitionBuilder.GetStepDefinitionParameters(stepText, _reference.IsInsideScenarioOutline()); var pattern = _stepDefinitionBuilder.GetPattern(stepText, _reference.IsInsideScenarioOutline()); var attributeType = CSharpTypeFactory.CreateType(SpecflowAttributeHelper.GetAttributeClrName(stepKind), classDeclaration.GetPsiModule()); var formatString = $"[$0(@\"$1\")] public void {methodName}() {{ScenarioContext.StepIsPending();}}"; var methodDeclaration = factory.CreateTypeMemberDeclaration(formatString, attributeType, pattern.Replace("\"", "\"\"")) as IMethodDeclaration; if (methodDeclaration == null) { continue; } var psiModule = classDeclaration.GetPsiModule(); foreach (var(parameterName, parameterType) in parameters) { methodDeclaration.AddParameterDeclarationAfter(ParameterKind.VALUE, CSharpTypeFactory.CreateType(parameterType, psiModule), parameterName, null); } IClassMemberDeclaration insertedDeclaration; using (new PsiTransactionCookie(type.GetPsiServices(), DefaultAction.Commit, "Generate specflow step")) { insertedDeclaration = classDeclaration.AddClassMemberDeclaration((IClassMemberDeclaration)methodDeclaration); } var invocationExpression = insertedDeclaration.GetChildrenInSubtrees <IInvocationExpression>().FirstOrDefault(); if (invocationExpression != null) { invocationExpression.NavigateToNode(true); } else { insertedDeclaration.NavigateToNode(true); } } }
public static PropertyDeclarationSyntax DebuggerDisplayPropertyDeclaration(string name, ExpressionSyntax returnExpression) { return(PropertyDeclaration( SingletonList( AttributeList( Attribute( ParseName("System.Diagnostics.DebuggerBrowsableAttribute"), AttributeArgument( SimpleMemberAccessExpression( ParseName("System.Diagnostics.DebuggerBrowsableState").WithSimplifierAnnotation(), IdentifierName("Never")) ) ).WithSimplifierAnnotation() ) ), Modifiers.Private(), CSharpTypeFactory.StringType(), default(ExplicitInterfaceSpecifierSyntax), Identifier(name).WithRenameAnnotation(), AccessorList( GetAccessorDeclaration( Block( ReturnStatement(returnExpression)) ) ) ).WithFormatterAnnotation()); }
protected override void Run(IClassDeclaration classDeclaration, ElementProblemAnalyzerData data, IHighlightingConsumer consumer) { if (!myIsEnabled.Value) { return; } var typeElement = classDeclaration.DeclaredElement; if (typeElement == null || !ZoneConstants.IsZoneClass(typeElement)) { return; } var mark = myMarks.GetMark(typeElement.GetContainingNamespace()); var classes = myMarks.EnumerateClasses(mark).ToList(); // find all base zones var baseZones = new HashSet <IClass>(); foreach (var cls in classes) { foreach (var baseZone in MarksService.EnumerableMarkClasses(cls, true)) { if (!baseZone.Equals(cls)) { baseZones.Add(baseZone); } } } foreach (var typeUsage in classDeclaration.SuperTypeUsageNodes.OfType <IUserDeclaredTypeUsage>()) { IDeclaredType superType = CSharpTypeFactory.CreateDeclaredType(typeUsage); var superTypeElement = superType.GetTypeElement(); if (superTypeElement != null) { if (ZoneConstants.IsIRequire(superTypeElement as IInterface)) { var substitution = superType.GetSubstitution(); foreach (var parameter in substitution.Domain) { var zoneType = substitution[parameter] as IDeclaredType; if (zoneType != null) { var zoneClass = zoneType.GetTypeElement() as IClass; if (zoneClass != null && baseZones.Contains(zoneClass)) { consumer.AddHighlighting(new RedundantDependencySpecificationError(typeUsage), classDeclaration.GetContainingNode <IFile>()); } } } } } } }
private static async Task <Document> RefactorAsync( Document document, AttributeSyntax attribute, CancellationToken cancellationToken) { TypeDeclarationSyntax typeDeclaration = attribute.FirstAncestor <TypeDeclarationSyntax>(); SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); string propertyName = NameGenerator.Default.EnsureUniqueMemberName(PropertyName, semanticModel, typeDeclaration.OpenBraceToken.Span.End, cancellationToken: cancellationToken); AttributeArgumentSyntax argument = attribute.ArgumentList.Arguments.First(); TypeDeclarationSyntax newTypeDeclaration = typeDeclaration.ReplaceNode( argument, argument.WithExpression( StringLiteralExpression($"{{{propertyName},nq}}")).WithTriviaFrom(argument.Expression)); string value = semanticModel .GetDeclaredSymbol(typeDeclaration, cancellationToken) .GetAttribute(semanticModel.GetTypeByMetadataName(MetadataNames.System_Diagnostics_DebuggerDisplayAttribute)) .ConstructorArguments[0] .Value .ToString(); ExpressionSyntax returnExpression = GetReturnExpression(value, SyntaxInfo.StringLiteralExpressionInfo(argument.Expression).IsVerbatim); PropertyDeclarationSyntax propertyDeclaration = PropertyDeclaration( SingletonList( AttributeList( Attribute( ParseName("System.Diagnostics.DebuggerBrowsableAttribute"), AttributeArgument( SimpleMemberAccessExpression( ParseName("System.Diagnostics.DebuggerBrowsableState").WithSimplifierAnnotation(), IdentifierName("Never")) ) ).WithSimplifierAnnotation() ) ), Modifiers.Private(), CSharpTypeFactory.StringType(), default(ExplicitInterfaceSpecifierSyntax), Identifier(propertyName).WithRenameAnnotation(), AccessorList( GetAccessorDeclaration( Block( ReturnStatement(returnExpression))))); propertyDeclaration = propertyDeclaration.WithFormatterAnnotation(); newTypeDeclaration = MemberDeclarationInserter.Default.Insert(newTypeDeclaration, propertyDeclaration); return(await document.ReplaceNodeAsync(typeDeclaration, newTypeDeclaration, cancellationToken).ConfigureAwait(false)); }
private string GetTypeString() { string keyword = CSharpTypeFactory.GetTypeKeyword(new ClrTypeName(TypeToken.GetText())); if (keyword != null) { return(keyword); } return("global::" + GetTypeFqnString()); }
private static object GetTypeObject(UnityTypeSpec typeSpec, KnownTypesCache knownTypesCache, IPsiModule module) { if (typeSpec.TypeParameters.Length == 0) { var keyword = CSharpTypeFactory.GetTypeKeyword(typeSpec.ClrTypeName); if (keyword != null) { return(keyword); } } return(typeSpec.AsIType(knownTypesCache, module)); }
private static Task <Document> UseStringEmptyInsteadOfEmptyStringLiteralAsync( Document document, ExpressionSyntax expression, CancellationToken cancellationToken = default) { MemberAccessExpressionSyntax memberAccessExpression = CSharpFactory.SimpleMemberAccessExpression( CSharpTypeFactory.StringType(), SyntaxFactory.IdentifierName("Empty")); memberAccessExpression = memberAccessExpression.WithTriviaFrom(expression); return(document.ReplaceNodeAsync(expression, memberAccessExpression, cancellationToken)); }
private static ITypeDeclaration GetTargetTypeDeclaration([NotNull] IDeclaredTypeUsage declaredTypeUsage) { if (!declaredTypeUsage.IsValid()) { return(null); } return(CSharpTypeFactory .CreateDeclaredType(declaredTypeUsage) .GetTypeElement() ?.GetDeclarations() .OfType <ITypeDeclaration>() .FirstOrDefault(decl => LanguageManager.Instance.TryGetService <IntentionLanguageSpecific>(decl.Language) != null)); }
private static async Task <Document> UseStringIsNullOrEmptyMethodAsync( Document document, BinaryExpressionSyntax binaryExpression, CancellationToken cancellationToken) { if (binaryExpression.IsKind(SyntaxKind.EqualsExpression)) { SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); BinaryExpressionInfo binaryExpressionInfo = SyntaxInfo.BinaryExpressionInfo(binaryExpression); ExpressionSyntax expression = (CSharpUtility.IsEmptyStringExpression(binaryExpressionInfo.Left, semanticModel, cancellationToken)) ? binaryExpressionInfo.Right : binaryExpressionInfo.Left; ExpressionSyntax newNode = SimpleMemberInvocationExpression( CSharpTypeFactory.StringType(), IdentifierName("IsNullOrEmpty"), Argument(expression)); newNode = newNode .WithTriviaFrom(binaryExpression) .WithFormatterAnnotation(); return(await document.ReplaceNodeAsync(binaryExpression, newNode, cancellationToken).ConfigureAwait(false)); } else { NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(binaryExpression.Left); ExpressionSyntax newNode = SimpleMemberInvocationExpression( CSharpTypeFactory.StringType(), IdentifierName("IsNullOrEmpty"), Argument(nullCheck.Expression)); if (nullCheck.IsCheckingNotNull) { newNode = LogicalNotExpression(newNode); } newNode = newNode .WithTriviaFrom(binaryExpression) .WithFormatterAnnotation(); return(await document.ReplaceNodeAsync(binaryExpression, newNode, cancellationToken).ConfigureAwait(false)); } }
private void AppendDeclaredType([NotNull] IDeclaredType declaredType, QualifierDisplays expectedQualifierDisplay, Context context) { if (declaredType.IsNullable()) { IType underlyingType = declaredType.GetNullableUnderlyingType(); if (underlyingType != null) { AppendTypeWithoutModule(underlyingType, expectedQualifierDisplay, context); AppendText("?", _highlighterIdProvider.Operator); return; } } if (declaredType is IDynamicType) { AppendText("dynamic", _highlighterIdProvider.Keyword); return; } if (context.Options.UseTypeKeywords) { string typeKeyword = CSharpTypeFactory.GetTypeKeyword(declaredType.GetClrName()); if (typeKeyword != null) { AppendText(typeKeyword, _highlighterIdProvider.Keyword); return; } } else if (declaredType.IsVoid()) { AppendText("void", _highlighterIdProvider.Keyword); return; } ITypeElement typeElement = declaredType.GetTypeElement(); if (typeElement == null || !typeElement.IsValid()) { PsiLanguageType language = CSharpLanguage.Instance ?? (PsiLanguageType)UnknownLanguage.Instance; AppendText(declaredType.GetPresentableName(language), null); } else { AppendTypeElement(typeElement, declaredType.GetSubstitution(), expectedQualifierDisplay, context); } }
public MemberGenerationContext( [NotNull] ITypeDeclaration typeDeclaration, [CanBeNull] IModifiersList modifiersList, [CanBeNull] ITypeUsage expectedReturnTypeUsage, [NotNull] TextLookupRanges memberReplaceRanges) { TypeDeclaration = typeDeclaration; PsiModule = typeDeclaration.GetPsiModule(); ModifiersList = modifiersList; MemberReplaceRanges = memberReplaceRanges; ExpectedAccessRights = ModifiersUtil.GetAccessRightsModifiers(modifiersList); if (expectedReturnTypeUsage != null) { ExpectedReturnType = CSharpTypeFactory.CreateType(expectedReturnTypeUsage); } }
public void AppendTypeMapped([NotNull] T4CSharpCodeGenerationResult result) { string typeText = TypeToken.GetText(); string keyword = CSharpTypeFactory.GetTypeKeyword(new ClrTypeName(typeText)); if (keyword != null) { result.Append(keyword); return; } result.Append("global::"); if (CSharpLexer.IsKeyword(typeText)) { result.Append("@"); } result.AppendMapped(TypeToken); }
/// <summary> /// Get return type. /// </summary> /// <param name="declaration"> /// The declaration. /// </param> /// <returns> /// An IType for the return type. /// </returns> public static IType GetReturnType(this IMethodDeclaration declaration) { IMethodDeclaration methodDeclarationNode = declaration; if (methodDeclarationNode == null) { return(null); } ITypeUsage typeUsage = methodDeclarationNode.TypeUsage; if (typeUsage == null) { return(null); } return(CSharpTypeFactory.CreateType(typeUsage)); }
private void AppendDeclaredType([NotNull] IDeclaredType declaredType, NamespaceDisplays expectedNamespaceDisplay) { if (declaredType.IsNullable()) { IType underlyingType = declaredType.GetNullableUnderlyingType(); if (underlyingType != null) { AppendType(underlyingType, expectedNamespaceDisplay); AppendText("?", VsHighlightingAttributeIds.Operator); return; } } if (declaredType is IDynamicType) { AppendText("dynamic", VsHighlightingAttributeIds.Keyword); return; } if (_options.UseTypeKeywords) { string typeKeyword = CSharpTypeFactory.GetTypeKeyword(declaredType.GetClrName()); if (typeKeyword != null) { AppendText(typeKeyword, VsHighlightingAttributeIds.Keyword); return; } } else if (declaredType.IsVoid()) { AppendText("void", VsHighlightingAttributeIds.Keyword); return; } ITypeElement typeElement = declaredType.GetTypeElement(); if (typeElement == null || !typeElement.IsValid()) { AppendText(declaredType.GetPresentableName(UnknownLanguage.Instance), null); return; } AppendTypeElement(typeElement, declaredType.GetSubstitution(), expectedNamespaceDisplay); }
public override ReferenceCollection GetReferences(ITreeNode element, ReferenceCollection oldReferences) { if (ResolveUtil.CheckThatAllReferencesBelongToElement <SyncVarHookReference>(oldReferences, element)) { return(oldReferences); } var literal = element as ILiteralExpression; if (literal == null || !literal.ConstantValue.IsString()) { return(ReferenceCollection.Empty); } var propertyAssignment = literal.GetContainingNode <IPropertyAssignment>(); var propertyAssignmentReference = propertyAssignment?.Reference; if (propertyAssignmentReference == null || propertyAssignmentReference.GetName() != "hook") { return(ReferenceCollection.Empty); } var assignedField = propertyAssignmentReference.Resolve().DeclaredElement as IField; var attributeType = assignedField?.GetContainingType(); if (attributeType == null || !Equals(attributeType.GetClrName(), KnownTypes.SyncVarAttribute)) { return(ReferenceCollection.Empty); } var multipleFieldDeclaration = propertyAssignment.GetContainingNode <IMultipleFieldDeclaration>(); var declaredFieldTypeUsage = multipleFieldDeclaration?.TypeUsage; var containingType = multipleFieldDeclaration?.GetContainingNode <IClassLikeDeclaration>()?.DeclaredElement; if (containingType != null && declaredFieldTypeUsage != null) { var declaredFieldType = CSharpTypeFactory.CreateType(declaredFieldTypeUsage); var reference = new SyncVarHookReference(containingType, declaredFieldType, literal); return(new ReferenceCollection(reference)); } return(ReferenceCollection.Empty); }
protected override void AfterComplete(ITextControl textControl, IObjectCreationExpression expression) { var referencedType = CSharpTypeFactory.CreateDeclaredType(expression.CreatedTypeUsage); var canInstantiate = TypeUtils.CanInstantiateType(referencedType, expression); if ((canInstantiate & CanInstantiate.ConstructorWithParameters) != 0) { var lparRange = expression.LPar.GetDocumentRange(); var rparRange = expression.RPar.GetDocumentRange(); var documentRange = lparRange.SetEndTo(rparRange.TextRange.EndOffset); var argumentsMarker = documentRange.CreateRangeMarker(); var settingsStore = expression.GetSettingsStore(); var invokeParameterInfo = settingsStore.GetValue(PostfixTemplatesSettingsAccessor.InvokeParameterInfo); var solution = expression.GetSolution(); ExecuteRefactoring(textControl, expression, executeAfter: () => { var argumentsRange = argumentsMarker.Range; if (!argumentsRange.IsValid) { return; } var offset = argumentsRange.StartOffset + argumentsRange.Length / 2; // EWW textControl.Caret.MoveTo(offset, CaretVisualPlacement.DontScrollIfVisible); if (invokeParameterInfo) { var lookupItemsOwner = Info.ExecutionContext.LookupItemsOwner; LookupUtil.ShowParameterInfo(solution, textControl, lookupItemsOwner); } }); } else { ExecuteRefactoring(textControl, expression); } }
public IEnumerable <AvailableBindingClass> GetBindingTypes(IPsiModule module) { foreach (var(fullClassName, sourceFile) in _mergeData.SpecflowBindingTypes.SelectMany(e => e.Value.Select(v => (fullClassName: e.Key, sourceFile: v)))) { if (!module.Equals(sourceFile.PsiModule) && !module.References(sourceFile.PsiModule)) { continue; } yield return(new AvailableBindingClass(sourceFile, fullClassName)); } // Since we cannot know when cache are built if a partial class in a given file has an attribute or not. // This is due to the fact that `DeclaredElement` are resolved using cache and we cannot depends ond cache when building a cache. // The check need to be done at this time. foreach (var(fullClassName, sourceFile) in _mergeData.PotentialSpecflowBindingTypes.SelectMany(e => e.Value.Select(v => (fullClassName: e.Key, sourceFile: v)))) { if (!module.Equals(sourceFile.PsiModule) && !module.References(sourceFile.PsiModule)) { continue; } var type = CSharpTypeFactory.CreateType(fullClassName, sourceFile.PsiModule); if (!(type is DeclaredTypeFromCLRName declaredTypeFromClrName)) { continue; } var resolveResult = declaredTypeFromClrName.Resolve(); if (!resolveResult.IsValid()) { continue; } if (!(resolveResult.DeclaredElement is IClass @class)) { continue; } if (@class.GetAttributeInstances(AttributesSource.Self).All(x => x.GetAttributeType().GetClrName().FullName != "TechTalk.SpecFlow.BindingAttribute")) { continue; } yield return(new AvailableBindingClass(sourceFile, fullClassName)); } }
private static Task <Document> UseStringIsNullOrEmptyMethodAsync( Document document, BinaryExpressionSyntax binaryExpression, CancellationToken cancellationToken) { NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(binaryExpression.Left); ExpressionSyntax newNode = SimpleMemberInvocationExpression( CSharpTypeFactory.StringType(), IdentifierName("IsNullOrEmpty"), Argument(nullCheck.Expression)); if (nullCheck.IsCheckingNotNull) { newNode = LogicalNotExpression(newNode); } newNode = newNode .WithTriviaFrom(binaryExpression) .WithFormatterAnnotation(); return(document.ReplaceNodeAsync(binaryExpression, newNode, cancellationToken)); }
private static AfterCompletionHandler BakeAfterComplete([NotNull] ILookupItem lookupItem, [NotNull] ISolution solution, int argumentsCount) { // sorry, ugly as f**k :( return((ITextControl textControl, ref TextRange range, ref TextRange decoration, TailType tailType, ref Suffix suffix, ref IRangeMarker caretMarker) => { var psiServices = solution.GetPsiServices(); psiServices.CommitAllDocuments(); var allMethods = GetAllTargetMethods(lookupItem); if (allMethods.Count == 0) { return; } var reference = TextControlToPsi.GetElement <IReferenceExpression>(solution, textControl.Document, range.StartOffset); if (reference == null) { return; } var decorationText = textControl.Document.GetText(decoration); var decorationRange = new DocumentRange(textControl.Document, decoration); var hasMoreParameters = HasMoreParameters(allMethods, argumentsCount); if (!hasMoreParameters) // put caret 'foo(arg){here};' { caretMarker = decorationRange.EndOffsetRange().CreateRangeMarker(); } else if (argumentsCount > 0) { var parenthesisCloseIndex = decorationText.LastIndexOf(')'); if (parenthesisCloseIndex >= 0) { var delta = decoration.Length - parenthesisCloseIndex; caretMarker = decorationRange.EndOffsetRange().Shift(-delta).CreateRangeMarker(); } } var qualifierExpression = reference.QualifierExpression.NotNull("qualifierExpression != null"); var referencePointer = reference.CreateTreeElementPointer(); var qualifierText = InsertQualifierAsArgument( qualifierExpression, allMethods, argumentsCount, textControl, decoration, decorationText); // TODO: mmm? if (!hasMoreParameters && !decorationText.EndsWith(")", StringComparison.Ordinal)) { caretMarker = caretMarker.DocumentRange.Shift(+qualifierText.Length).CreateRangeMarker(); } // replace qualifier with type (predefined/user type) var ownerType = allMethods[0].GetContainingType().NotNull("ownerType != null"); FixQualifierExpression(textControl, qualifierExpression, ownerType); psiServices.CommitAllDocuments(); var newReference = referencePointer.GetTreeNode(); if (newReference != null) { var keyword = CSharpTypeFactory.GetTypeKeyword(ownerType.GetClrName()); if (keyword == null) // bind user type { var newQualifier = (IReferenceExpression)newReference.QualifierExpression; if (newQualifier != null) { var elementInstance = lookupItem.GetDeclaredElement().NotNull("elementInstance != null"); newQualifier.Reference.BindTo(ownerType, elementInstance.Substitution); } range = newReference.NameIdentifier.GetDocumentRange().TextRange; decoration = TextRange.InvalidRange; } // show parameter info when needed if (hasMoreParameters) { var factory = solution.GetComponent <LookupItemsOwnerFactory>(); var lookupItemsOwner = factory.CreateLookupItemsOwner(textControl); LookupUtil.ShowParameterInfo(solution, textControl, lookupItemsOwner); } } TipsManager.Instance.FeatureIsUsed( "Plugin.ControlFlow.PostfixTemplates.<static>", textControl.Document, solution); }); }
private IType CreateIType([NotNull] string typeName) { var type = CSharpTypeFactory.CreateType(typeName, classDeclaration); return(!type.IsResolved ? null : type); }
private static Task <Document> RefactorAsync( Document document, InterpolatedStringExpressionSyntax interpolatedString, CancellationToken cancellationToken) { StringBuilder sb = StringBuilderCache.GetInstance(); var b = new SyntaxNodeTextBuilder(interpolatedString, sb); var arguments = new List <ArgumentSyntax>() { null }; if (interpolatedString.IsVerbatim()) { b.Append("@"); } b.Append("\""); int index = 0; foreach (InterpolatedStringContentSyntax content in interpolatedString.Contents) { switch (content.Kind()) { case SyntaxKind.Interpolation: { var interpolation = (InterpolationSyntax)content; b.Append("{"); b.Append(index.ToString(CultureInfo.InvariantCulture)); index++; InterpolationAlignmentClauseSyntax alignmentClause = interpolation.AlignmentClause; if (alignmentClause != null) { b.Append(","); b.AppendSpan(alignmentClause.Value); } InterpolationFormatClauseSyntax formatClause = interpolation.FormatClause; if (formatClause != null) { b.Append(":"); b.AppendSpan(formatClause.FormatStringToken); } b.Append("}"); arguments.Add(Argument(interpolation.Expression)); break; } case SyntaxKind.InterpolatedStringText: { b.AppendSpan(content); break; } } } b.Append("\""); arguments[0] = Argument(ParseExpression(StringBuilderCache.GetStringAndFree(sb))); InvocationExpressionSyntax invocation = SimpleMemberInvocationExpression( CSharpTypeFactory.StringType(), IdentifierName("Format"), ArgumentList(SeparatedList(arguments))); invocation = invocation.WithTriviaFrom(interpolatedString).WithFormatterAnnotation(); return(document.ReplaceNodeAsync(interpolatedString, invocation, cancellationToken)); }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false); if (!TryFindFirstAncestorOrSelf(root, context.Span, out ExpressionSyntax expression)) { return; } Document document = context.Document; foreach (Diagnostic diagnostic in context.Diagnostics) { switch (diagnostic.Id) { case DiagnosticIdentifiers.ExpressionIsAlwaysEqualToTrueOrFalse: { if (expression.IsKind( SyntaxKind.LessThanExpression, SyntaxKind.LessThanOrEqualExpression, SyntaxKind.GreaterThanExpression, SyntaxKind.GreaterThanOrEqualExpression)) { var binaryExpression = (BinaryExpressionSyntax)expression; LiteralExpressionSyntax newNode = BooleanLiteralExpression(binaryExpression.IsKind(SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.LessThanOrEqualExpression)); CodeAction codeAction = CodeAction.Create( $"Replace expression with '{newNode}'", ct => document.ReplaceNodeAsync(binaryExpression, newNode.WithTriviaFrom(binaryExpression), ct), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); } else if (diagnostic.Properties.TryGetValue("DoubleNaN", out string leftOrRight)) { var binaryExpression = (BinaryExpressionSyntax)expression; CodeAction codeAction = CodeAction.Create( $"Call 'IsNaN'", ct => { ExpressionSyntax newExpression = SimpleMemberInvocationExpression( CSharpTypeFactory.DoubleType(), IdentifierName("IsNaN"), Argument((leftOrRight == "Left") ? binaryExpression.Left.WithoutLeadingTrivia() : binaryExpression.Right.WithoutTrailingTrivia())); if (binaryExpression.IsKind(SyntaxKind.NotEqualsExpression)) { newExpression = LogicalNotExpression(newExpression); } newExpression = newExpression.Parenthesize().WithTriviaFrom(binaryExpression); return(document.ReplaceNodeAsync(binaryExpression, newExpression, ct)); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); } { CodeAction codeAction = CodeAction.Create( "Remove null check", ct => RemoveUnnecessaryNullCheckAsync(document, expression, ct), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); } break; } } } }
public override bool Execute(IProgressIndicator progressIndicator) { var languageService = CSharpLanguage.Instance.LanguageService(); if (languageService == null) { return(false); } var ctor = _ctor.FindDeclaredElement(); if (ctor == null) { return(false); } var definingClass = _class.FindDeclaredElement(); if (definingClass == null) { return(false); } var factory = CSharpElementFactory.GetInstance(ctor.Module); var ctorDecl = ctor.GetDeclarations().FirstOrDefault(); if (ctorDecl == null) { var typeDecl = definingClass.GetDeclarations().FirstOrDefault() as IClassLikeDeclaration; if (typeDecl == null) { return(false); } var typeBody = typeDecl.Body; ctorDecl = factory.CreateTypeMemberDeclaration("public $0() {}", typeDecl.DeclaredName); if (typeBody.FirstChild == null) { return(false); } ctorDecl = ModificationUtil.AddChildBefore( typeBody, typeBody.FirstChild.NextSibling, ctorDecl).GetContainingNode <IConstructorDeclaration>(true); } if (ctorDecl == null) { return(false); } var type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl); if (!type.IsResolved) { type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl.GetPsiModule()); } string recommendedName = null; if (!type.IsResolved) { var presentableName = type.GetPresentableName(CSharpLanguage.Instance); var indexOfGeneric = presentableName.IndexOf('<'); if (indexOfGeneric != -1) { var interfaceName = presentableName.Substring(1, indexOfGeneric - 1); var genericArgument = presentableName.Substring(indexOfGeneric).Trim('<', '>'); recommendedName = type.GetPsiServices().Naming.Suggestion.GetDerivedName( genericArgument + interfaceName, NamedElementKinds.Parameters, ScopeKind.Common, CSharpLanguage.Instance, new SuggestionOptions(), ctorDecl.GetSourceFile()); } var interfaceDecl = factory.CreateTypeMemberDeclaration("public interface IFoo {}"); interfaceDecl.SetName(presentableName); languageService.CodeFormatter.Format(interfaceDecl, CodeFormatProfile.GENERATOR); var containingType = ctor.GetContainingType(); if (containingType == null) { return(false); } var containingTypeDecl = containingType.GetDeclarations().First(); ModificationUtil.AddChildBefore(containingTypeDecl, interfaceDecl); } type = CSharpTypeFactory.CreateType(_parameterType, ctorDecl); if (recommendedName == null) { var suggestionOptions = new SuggestionOptions(); recommendedName = type.GetPsiServices().Naming.Suggestion.GetDerivedName( type.GetPresentableName(CSharpLanguage.Instance), NamedElementKinds.Parameters, ScopeKind.Common, CSharpLanguage.Instance, suggestionOptions, ctorDecl.GetSourceFile()); } var parametersOwner = ctorDecl as ICSharpParametersOwnerDeclaration; var references = FindReferences(parametersOwner, progressIndicator); if (parametersOwner == null) { return(false); } parametersOwner.AddParameterDeclarationAfter( ParameterKind.VALUE, type, recommendedName, parametersOwner.ParameterDeclarations.LastOrDefault()); foreach (var reference in references) { ChangeReference(reference, recommendedName, type); } return(true); }