ExpressionSyntax GenerateTarget(SemanticModel model, BinaryExpressionSyntax node) { var symbols = model.LookupSymbols(node.SpanStart).OfType<IMethodSymbol>(); if (!symbols.Any() || HasDifferentEqualsMethod(symbols)) return SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseExpression("object"), SyntaxFactory.IdentifierName("Equals")); else return SyntaxFactory.IdentifierName("Equals"); }
public static string ReduceQualifiedTypeName( this ITypeSymbol type,SemanticModel semantic,int classDeclarationPosition) { // one problem is that the type could be from a different semantic model // (one that was created before) so we search the type in the // new model and if we find it use the new one instead var typeInSemanticModel = semantic.LookupSymbols(0, name: type.Name) .OfType<ITypeSymbol>() .FirstOrDefault(); if (typeInSemanticModel != null) type = typeInSemanticModel; return type.ToMinimalDisplayString(semantic, classDeclarationPosition); }
private static string GetProgramElementNameThatMatchStringLiteral(LiteralExpressionSyntax stringLiteral, SemanticModel semanticModel) { var programElementName = GetParameterNameThatMatchStringLiteral(stringLiteral); if (!Found(programElementName)) { var literalValueText = stringLiteral.Token.ValueText; var symbol = semanticModel.LookupSymbols(stringLiteral.Token.SpanStart, null, literalValueText).FirstOrDefault(); programElementName = symbol?.ToDisplayParts().LastOrDefault(IncludeOnlyPartsThatAreName).ToString(); } return programElementName; }
protected virtual IEnumerable<CompletionData> CreateCompletionData (CompletionEngine engine, SemanticModel semanticModel, int position, INamedTypeSymbol enclosingType, SyntaxToken token, bool afterPartialKeyword, CancellationToken cancellationToken) { var symbols = semanticModel.LookupSymbols(position, container: enclosingType) .OfType<IMethodSymbol>() .Where(m => IsPartial(m) && m.PartialImplementationPart == null); var list = new List<CompletionData> (); var declarationBegin = afterPartialKeyword ? token.Parent.SpanStart : position - 1; foreach (var m in symbols) { var data = engine.Factory.CreatePartialCompletionData ( this, declarationBegin, enclosingType, m, afterPartialKeyword ); list.Add (data); } return list; }
private static string GetProgramElementNameThatMatchStringLiteral(LiteralExpressionSyntax stringLiteral, SemanticModel semanticModel) { var programElementName = GetParameterNameThatMatchStringLiteral(stringLiteral); if (!Found(programElementName)) { var literalValueText = stringLiteral.Token.ValueText; var symbol = semanticModel.LookupSymbols(stringLiteral.Token.SpanStart, null, literalValueText).FirstOrDefault(); if (symbol?.Kind == SymbolKind.Local) { var symbolSpan = symbol.Locations.Min(i => i.SourceSpan); if (symbolSpan.CompareTo(stringLiteral.Token.Span) > 0) return string.Empty; } programElementName = symbol?.ToDisplayParts().LastOrDefault(AnalyzerExtensions.IsName).ToString(); } return programElementName; }
private static string DetectSynchronousUsages(IMethodSymbol methodCallSymbol, SemanticModel semanticModel) { var list = semanticModel.LookupSymbols(0, container: methodCallSymbol.ContainingType, includeReducedExtensionMethods: true); var name = methodCallSymbol.Name; if (methodCallSymbol.ContainingType == null) { return "None"; } if (methodCallSymbol.ContainingType.Name == "Thread" && name == "Sleep") { return "Task.Delay"; } // Parameter Sifir olmasi lazim!!!!! else if (methodCallSymbol.ContainingType.Name == "Task" && name == "Wait") { return "await"; } else if (methodCallSymbol.ContainingType.Name == "Task" && name == "WaitAll") { return "Task.WhenAll"; } else if (methodCallSymbol.ContainingType.Name == "Task" && name == "WaitAny") { return "Task.WhenAny"; } foreach (var tmp in list) { if (tmp.Name.Equals(name + "Async")) { return tmp.Name; } } return "None"; }
static bool FindIssuesInAccessor(SemanticModel semanticModel, AccessorDeclarationSyntax accessor) { var body = accessor.Body; if (!IsEligible(body)) return false; if (body.Statements.Any()) { var foundValueSymbol = semanticModel.LookupSymbols(body.Statements.First().SpanStart, null, "value").FirstOrDefault(); if (foundValueSymbol == null) return false; foreach (var valueRef in body.DescendantNodes().OfType<IdentifierNameSyntax>().Where(ins => ins.Identifier.ValueText == "value")) { var valueRefSymbol = semanticModel.GetSymbolInfo(valueRef).Symbol; if (foundValueSymbol.Equals(valueRefSymbol)) return false; } } return true; }
private static string GetProgramElementNameThatMatchStringLiteral(LiteralExpressionSyntax stringLiteral, SemanticModel semanticModel, out bool externalSymbol) { externalSymbol = false; var programElementName = GetParameterNameThatMatchStringLiteral(stringLiteral); if (!Found(programElementName)) { var literalValueText = stringLiteral.Token.ValueText; var symbol = semanticModel.LookupSymbols(stringLiteral.Token.SpanStart, null, literalValueText).FirstOrDefault(); if (symbol == null) return null; externalSymbol = !symbol.Locations.Any(l => l.IsInSource); if (symbol.Kind == SymbolKind.Local) { var symbolSpan = symbol.Locations.Min(i => i.SourceSpan); if (symbolSpan.CompareTo(stringLiteral.Token.Span) > 0) return null; } programElementName = symbol.ToDisplayParts(NameOfSymbolDisplayFormat).LastOrDefault(AnalyzerExtensions.IsName).ToString(); } return programElementName; }
private bool TryGetIndexers(int position, SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken, out IEnumerable<IPropertySymbol> indexers, out ITypeSymbol expressionType) { expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType == null) { indexers = null; return false; } if (expressionType is IErrorTypeSymbol) { expressionType = (expressionType as IErrorTypeSymbol).CandidateSymbols.FirstOrDefault().GetSymbolType(); } indexers = semanticModel.LookupSymbols(position, expressionType, WellKnownMemberNames.Indexer).OfType<IPropertySymbol>(); return true; }
private Task<IEnumerable<CompletionData>> GetCompletionsOffOfExplicitInterfaceAsync( CompletionEngine engine, Document document, SemanticModel semanticModel, int position, NameSyntax name, CancellationToken cancellationToken) { // Bind the interface name which is to the left of the dot var syntaxTree = semanticModel.SyntaxTree; var nameBinding = semanticModel.GetSymbolInfo(name, cancellationToken); // var context = CSharpSyntaxContext.CreateContext(document.Project.Solution.Workspace, semanticModel, position, cancellationToken); var symbol = nameBinding.Symbol as ITypeSymbol; if (symbol == null || symbol.TypeKind != TypeKind.Interface) { return Task.FromResult (Enumerable.Empty<CompletionData> ()); } var members = semanticModel.LookupSymbols ( position: name.SpanStart, container: symbol) .Where (s => !s.IsStatic); // .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation); // We're going to create a entry for each one, including the signature var completions = new List<CompletionData>(); // var signatureDisplayFormat = // new SymbolDisplayFormat( // genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, // memberOptions: // SymbolDisplayMemberOptions.IncludeParameters, // parameterOptions: // SymbolDisplayParameterOptions.IncludeName | // SymbolDisplayParameterOptions.IncludeType | // SymbolDisplayParameterOptions.IncludeParamsRefOut, // miscellaneousOptions: // SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | // SymbolDisplayMiscellaneousOptions.UseSpecialTypes); var namePosition = name.SpanStart; // var text = await context.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); // var textChangeSpan = GetTextChangeSpan(text, context.Position); foreach (var member in members) { // var displayString = member.ToMinimalDisplayString(semanticModel, namePosition, signatureDisplayFormat); // var memberCopied = member; // var insertionText = displayString; completions.Add(engine.Factory.CreateSymbolCompletionData (this, member) /*new SymbolCompletionItem( this, displayString, insertionText: insertionText, filterSpan: textChangeSpan, position: position, symbols: new List<ISymbol> { member }, context: context) */); } return Task.FromResult ((IEnumerable<CompletionData>)completions); }
static string GetName(SemanticModel model, TextSpan span, string[] variableNames) { var symbols = model.LookupSymbols(span.Start).ToList(); for (int i = 0; i < 1000; i++) { foreach (var vn in variableNames) { string id = i > 0 ? vn + i : vn; if (symbols.All(s => s.Name != id)) return id; } } return null; }
private bool TryGetIndexers(int position, SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken, out IEnumerable<IPropertySymbol> indexers, out ITypeSymbol expressionType) { expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType == null) { indexers = null; return false; } if (expressionType is IErrorTypeSymbol) { // If `expression` is a QualifiedNameSyntax then GetTypeInfo().Type won't have any CandidateSymbols, so // we should then fall back to getting the actual symbol for the expression. expressionType = (expressionType as IErrorTypeSymbol).CandidateSymbols.FirstOrDefault().GetSymbolType() ?? semanticModel.GetSymbolInfo(expression).GetAnySymbol().GetSymbolType(); } indexers = semanticModel.LookupSymbols(position, expressionType, WellKnownMemberNames.Indexer).OfType<IPropertySymbol>(); return true; }
public IEnumerable<Location> ComputePossibleImplicitUsageConflicts( ISymbol renamedSymbol, SemanticModel semanticModel, Location originalDeclarationLocation, int newDeclarationLocationStartingPosition, CancellationToken cancellationToken) { // TODO: support other implicitly used methods like dispose if ((renamedSymbol.Name == "MoveNext" || renamedSymbol.Name == "GetEnumerator" || renamedSymbol.Name == "Current") && renamedSymbol.GetAllTypeArguments().Length == 0) { // TODO: partial methods currently only show the location where the rename happens as a conflict. // Consider showing both locations as a conflict. var baseType = renamedSymbol.ContainingType.GetBaseTypes().FirstOrDefault(); if (baseType != null) { var implicitSymbols = semanticModel.LookupSymbols( newDeclarationLocationStartingPosition, baseType, renamedSymbol.Name) .Where(sym => !sym.Equals(renamedSymbol)); foreach (var symbol in implicitSymbols) { if (symbol.GetAllTypeArguments().Length != 0) { continue; } if (symbol.Kind == SymbolKind.Method) { var method = (IMethodSymbol)symbol; if (symbol.Name == "MoveNext") { if (!method.ReturnsVoid && !method.Parameters.Any() && method.ReturnType.SpecialType == SpecialType.System_Boolean) { return SpecializedCollections.SingletonEnumerable(originalDeclarationLocation); } } else if (symbol.Name == "GetEnumerator") { // we are a bit pessimistic here. // To be sure we would need to check if the returned type is having a MoveNext and Current as required by foreach if (!method.ReturnsVoid && !method.Parameters.Any()) { return SpecializedCollections.SingletonEnumerable(originalDeclarationLocation); } } } else if (symbol.Kind == SymbolKind.Property && symbol.Name == "Current") { var property = (IPropertySymbol)symbol; if (!property.Parameters.Any() && !property.IsWriteOnly) { return SpecializedCollections.SingletonEnumerable(originalDeclarationLocation); } } } } } return SpecializedCollections.EmptyEnumerable<Location>(); }
CodeAction GetAction(Document document, SemanticModel model, SyntaxNode root, SyntaxNode node, MethodDeclarationSyntax method) { return CodeActionFactory.Create(node.Span, DiagnosticSeverity.Info, GettextCatalog.GetString("Extract anonymous method"), t2 => { var identifier = SyntaxFactory.IdentifierName(NameGenerator.EnsureUniqueness("Method", model.LookupSymbols(node.SpanStart).Select(s => s.Name))); var surroundingMemberDeclaration = node.GetAncestor<MemberDeclarationSyntax>(); var rootWithTrackedMember = root.TrackNodes(node, surroundingMemberDeclaration); var newRoot = rootWithTrackedMember.ReplaceNode(rootWithTrackedMember.GetCurrentNode(node), identifier); newRoot = newRoot .InsertNodesBefore(newRoot.GetCurrentNode(surroundingMemberDeclaration), new[] { method.WithTrailingTrivia(surroundingMemberDeclaration.GetTrailingTrivia()) }); return Task.FromResult(document.WithSyntaxRoot(newRoot)); }); }
ParameterHintingResult HandleTypeParameterCase(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { var result = new ParameterHintingResult(node.SpanStart); string typeName; var gns = node as GenericNameSyntax; if (gns != null) { typeName = gns.Identifier.ToString (); } else { typeName = node.ToString (); } foreach (var cand in semanticModel.LookupSymbols (node.SpanStart).OfType<INamedTypeSymbol> ()) { if (cand.TypeParameters.Length == 0) continue; if (cand.Name == typeName || cand.GetFullName () == typeName) result.AddData(factory.CreateTypeParameterDataProvider(cand)); } if (result.Count == 0) { foreach (var cand in semanticModel.LookupSymbols (node.SpanStart).OfType<IMethodSymbol> ()) { if (cand.TypeParameters.Length == 0) continue; if (cand.Name == typeName) result.AddData (factory.CreateTypeParameterDataProvider (cand)); } } return result; }
private static string FindAvailableStringBuilderVariableName(AssignmentExpressionSyntax assignmentExpression, SemanticModel semanticModel) { const string builderNameBase = "builder"; var builderName = builderNameBase; var builderNameIncrementer = 0; while (semanticModel.LookupSymbols(assignmentExpression.GetLocation().SourceSpan.Start, name: builderName).Any()) builderName = builderNameBase + ++builderNameIncrementer; return builderName; }
public static string DetectSynchronousUsages(this IMethodSymbol methodCallSymbol, SemanticModel semanticModel) { var list = semanticModel.LookupSymbols(0, container: methodCallSymbol.ContainingType, includeReducedExtensionMethods: true); var name = methodCallSymbol.Name; if (name.Equals("Sleep")) { return "Task.Delay"; } foreach (var tmp in list) { //if (tmp.Name.Equals("Begin" + name)) //{ // return tmp.Name; //} if (tmp.Name.Equals(name + "Async")) { if(!name.Equals("Invoke")) return tmp.Name; } } return "None"; }
public static ITypeSymbol InferAwaitableReturnType(this ISymbol symbol, SemanticModel semanticModel, int position) { var methodSymbol = symbol as IMethodSymbol; if (methodSymbol == null) { return null; } var returnType = methodSymbol.ReturnType; if (returnType == null) { return null; } var potentialGetAwaiters = semanticModel.LookupSymbols(position, container: returnType, name: WellKnownMemberNames.GetAwaiter, includeReducedExtensionMethods: true); var getAwaiters = potentialGetAwaiters.OfType<IMethodSymbol>().Where(x => !x.Parameters.Any()); if (!getAwaiters.Any()) { return null; } var getResults = getAwaiters.SelectMany(g => semanticModel.LookupSymbols(position, container: g.ReturnType, name: WellKnownMemberNames.GetResult)); var getResult = getResults.OfType<IMethodSymbol>().FirstOrDefault(g => !g.IsStatic); if (getResult == null) { return null; } return getResult.ReturnType; }
/// <summary> /// If the <paramref name="symbol"/> is a method symbol, returns True if the method's return type is "awaitable". /// If the <paramref name="symbol"/> is a type symbol, returns True if that type is "awaitable". /// An "awaitable" is any type that exposes a GetAwaiter method which returns a valid "awaiter". This GetAwaiter method may be an instance method or an extension method. /// </summary> public static bool IsAwaitable(this ISymbol symbol, SemanticModel semanticModel, int position) { IMethodSymbol methodSymbol = symbol as IMethodSymbol; ITypeSymbol typeSymbol = null; if (methodSymbol == null) { typeSymbol = symbol as ITypeSymbol; if (typeSymbol == null) { return false; } } else { if (methodSymbol.ReturnType == null) { return false; } // dynamic if (methodSymbol.ReturnType.TypeKind == TypeKind.Dynamic && methodSymbol.MethodKind != MethodKind.BuiltinOperator) { return true; } } // otherwise: needs valid GetAwaiter var potentialGetAwaiters = semanticModel.LookupSymbols(position, container: typeSymbol ?? methodSymbol.ReturnType.OriginalDefinition, name: WellKnownMemberNames.GetAwaiter, includeReducedExtensionMethods: true); var getAwaiters = potentialGetAwaiters.OfType<IMethodSymbol>().Where(x => !x.Parameters.Any()); return getAwaiters.Any(VerifyGetAwaiter); }
private static string GetIdentifierName(ObjectCreationExpressionSyntax objectCreation, SemanticModel semanticModel) { var identifierName = "disposableObject"; var type = objectCreation.Type; if (type.IsKind(SyntaxKind.QualifiedName)) { var name = (QualifiedNameSyntax)type; identifierName = LowerCaseFirstLetter(name.Right.Identifier.ValueText); } else if (type is SimpleNameSyntax) { var name = (SimpleNameSyntax)type; identifierName = LowerCaseFirstLetter(name.Identifier.ValueText); } var confilctingNames = from symbol in semanticModel.LookupSymbols(objectCreation.SpanStart) let symbolIdentifierName = symbol?.ToDisplayParts().LastOrDefault(AnalyzerExtensions.IsName).ToString() where symbolIdentifierName != null && symbolIdentifierName.StartsWith(identifierName) select symbolIdentifierName; var identifierPostFix = 0; while (confilctingNames.Any(p => p == identifierName + ++identifierPostFix)) { } return identifierName + (identifierPostFix == 0 ? "" : identifierPostFix.ToString()); }
static MethodDeclarationSyntax GetMethod(SemanticModel context, TextSpan span, IMethodSymbol lambdaSymbol, BlockSyntax body) { TypeSyntax returnType = null; if (lambdaSymbol.ReturnsVoid) { returnType = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)); } else { var type = lambdaSymbol.ReturnType; returnType = type.TypeKind == TypeKind.Unknown ? SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)) : SyntaxFactory.ParseTypeName(type.Name).WithAdditionalAnnotations(Simplifier.Annotation); } var methodParameters = SyntaxFactory.ParameterList( SyntaxFactory.SeparatedList(lambdaSymbol.Parameters.Select(p => SyntaxFactory.Parameter( SyntaxFactory.List<AttributeListSyntax>(), SyntaxFactory.TokenList(), SyntaxFactory.ParseTypeName(p.Type.Name), SyntaxFactory.Identifier(p.Name), null )) )); var method = SyntaxFactory.MethodDeclaration(returnType, NameGenerator.EnsureUniqueness("Method", context.LookupSymbols(span.Start).Select(s => s.Name))) .WithParameterList(methodParameters) .WithBody(body); if (lambdaSymbol.IsAsync) method = method.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))); return method.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation); }