public SourceDefinitionTreeItem(Document document, TextSpan sourceSpan, ISymbol symbol, ushort glyphIndex) : base(document, sourceSpan, glyphIndex) { _symbolDisplay = symbol.ToDisplayString(definitionDisplayFormat); this.DisplayText = $"[{document.Project.Name}] {_symbolDisplay}"; }
public bool ContainedIn(ISymbol symbol) { bool result = false; var attributes = symbol.GetAttributes(); foreach (var attribute in attributes) { INamedTypeSymbol attributeClass = attribute.AttributeClass; if (Uid != VisitorHelper.GetId(attributeClass)) { continue; } // arguments need to be a total match of the config IEnumerable<string> arguments = attribute.ConstructorArguments.Select(arg => GetLiteralString(arg)); if (!ConstructorArguments.SequenceEqual(arguments)) { continue; } // namedarguments need to be a superset of the config Dictionary<string, string> namedArguments = attribute.NamedArguments.ToDictionary(pair => pair.Key, pair => GetLiteralString(pair.Value)); if (!ConstructorNamedArguments.Except(namedArguments).Any()) { result = true; break; } } return result; }
private IEnumerable<SignatureHelpItem> GetDelegateInvokeItems( InvocationExpressionSyntax invocationExpression, SemanticModel semanticModel, ISymbolDisplayService symbolDisplayService, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService, ISymbol within, INamedTypeSymbol delegateType, CancellationToken cancellationToken) { var invokeMethod = delegateType.DelegateInvokeMethod; if (invokeMethod == null) { return null; } // Events can only be invoked directly from the class they were declared in. var expressionSymbol = semanticModel.GetSymbolInfo(invocationExpression.Expression, cancellationToken).GetAnySymbol(); if (expressionSymbol.IsKind(SymbolKind.Event) && !expressionSymbol.ContainingType.OriginalDefinition.Equals(within.OriginalDefinition)) { return null; } var position = invocationExpression.SpanStart; var item = CreateItem( invokeMethod, semanticModel, position, symbolDisplayService, anonymousTypeDisplayService, isVariadic: invokeMethod.IsParams(), documentation: SpecializedCollections.EmptyEnumerable<SymbolDisplayPart>(), prefixParts: GetDelegateInvokePreambleParts(invokeMethod, semanticModel, position), separatorParts: GetSeparatorParts(), suffixParts: GetDelegateInvokePostambleParts(), parameters: GetDelegateInvokeParameters(invokeMethod, semanticModel, position, documentationCommentFormattingService, cancellationToken)); return SpecializedCollections.SingletonEnumerable(item); }
public SDLanguageItemCollection<SDDocumentation> ParseDocumentation(ISymbol symbol) { var documentationXml = symbol.GetDocumentationCommentXml(); var docDic = new SDLanguageItemCollection<SDDocumentation>(); if (!string.IsNullOrEmpty(documentationXml)) { var xml = XDocument.Parse($"<doc>{documentationXml}</doc>"); foreach (var child in xml.Descendants()) { var isoCode = child.Name.LocalName.ToLower(); if (CultureInfo.GetCultures(CultureTypes.NeutralCultures).Any(c => c.TwoLetterISOLanguageName == isoCode) || isoCode == "default") { // TODO //_sdRepository.AddDocumentationLanguage(child.Name.ToLower()); var languageDoc = ParseDocumentation(child.Descendants(), true); if(!docDic.ContainsKey(isoCode)) docDic.Add(isoCode, languageDoc); } } //Es wurde keine Sprachunterstützung in der Doku genutzt. //Deswegen wird die Doku einfach als "default" geladen. if (docDic.Count == 0) { var defaultDoc = ParseDocumentation(xml.Descendants()); docDic.Add("default", defaultDoc); } } return docDic; }
public void AnalyzeCodeBlock(SyntaxNode codeBlock, ISymbol ownerSymbol, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken) { if (IsEmptyFinalizer(codeBlock, semanticModel)) { addDiagnostic(ownerSymbol.CreateDiagnostic(Rule)); } }
public async Task<ICallHierarchyMemberItem> CreateItem(ISymbol symbol, Project project, IEnumerable<Location> callsites, CancellationToken cancellationToken) { if (symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Property || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Field) { symbol = GetTargetSymbol(symbol); var finders = await CreateFinders(symbol, project, cancellationToken).ConfigureAwait(false); ICallHierarchyMemberItem item = new CallHierarchyItem(symbol, project.Id, finders, () => symbol.GetGlyph().GetImageSource(GlyphService), this, callsites, project.Solution.Workspace); return item; } return null; }
private static bool ShouldOmitThisDiagnostic(ISymbol symbol, Compilation compilation) { // This diagnostic is only relevant in constructors. // TODO: should this apply to instance field initializers for VB? var m = symbol as IMethodSymbol; if (m == null || m.MethodKind != MethodKind.Constructor) { return true; } var containingType = m.ContainingType; if (containingType == null) { return true; } // special case ASP.NET and WinForms constructors INamedTypeSymbol webUiControlType = compilation.GetTypeByMetadataName("System.Web.UI.Control"); if (containingType.Inherits(webUiControlType)) { return true; } INamedTypeSymbol windowsFormsControlType = compilation.GetTypeByMetadataName("System.Windows.Forms.Control"); if (containingType.Inherits(windowsFormsControlType)) { return true; } return false; }
internal override void GenerateReferenceInternal(ISymbol symbol, ReferenceItem reference, SymbolVisitorAdapter adapter) { foreach (var generator in _generators) { generator.GenerateReferenceInternal(symbol, reference, adapter); } }
internal override void GenerateSyntax(MemberType type, ISymbol symbol, SyntaxDetail syntax, SymbolVisitorAdapter adapter) { foreach (var generator in _generators) { generator.GenerateSyntax(type, symbol, syntax, adapter); } }
public async Task<Document> AddSourceToAsync(Document document, ISymbol symbol, CancellationToken cancellationToken) { if (document == null) { throw new ArgumentNullException(nameof(document)); } var newSemanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var rootNamespace = newSemanticModel.GetEnclosingNamespace(0, cancellationToken); // Add the interface of the symbol to the top of the root namespace document = await CodeGenerator.AddNamespaceOrTypeDeclarationAsync( document.Project.Solution, rootNamespace, CreateCodeGenerationSymbol(document, symbol), CreateCodeGenerationOptions(newSemanticModel.SyntaxTree.GetLocation(new TextSpan()), symbol), cancellationToken).ConfigureAwait(false); var docCommentFormattingService = document.GetLanguageService<IDocumentationCommentFormattingService>(); var docWithDocComments = await ConvertDocCommentsToRegularComments(document, docCommentFormattingService, cancellationToken).ConfigureAwait(false); var docWithAssemblyInfo = await AddAssemblyInfoRegionAsync(docWithDocComments, symbol.GetOriginalUnreducedDefinition(), cancellationToken).ConfigureAwait(false); var node = await docWithAssemblyInfo.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var formattedDoc = await Formatter.FormatAsync( docWithAssemblyInfo, SpecializedCollections.SingletonEnumerable(node.FullSpan), options: null, rules: GetFormattingRules(docWithAssemblyInfo), cancellationToken: cancellationToken).ConfigureAwait(false); var reducers = this.GetReducers(); return await Simplifier.ReduceAsync(formattedDoc, reducers, null, cancellationToken).ConfigureAwait(false); }
public override void DefaultVisit(ISymbol symbol, MetadataItem item, SymbolVisitorAdapter adapter) { foreach (var generator in _generators) { generator.DefaultVisit(symbol, item, adapter); } }
public bool HasAnnotationForSymbol(ISymbol symbol, bool appliesToItem) { Guard.NotNull(symbol, "symbol"); return HasAnnotationInGlobalCache(symbol, appliesToItem) || HasAnnotationInSideBySideFile(symbol, appliesToItem); }
public static void RunRename(ISymbol symbol, string newName = null) { if ((symbol is IMember) && ((symbol.SymbolKind == SymbolKind.Constructor) || (symbol.SymbolKind == SymbolKind.Destructor))) { // Don't rename constructors/destructors, rename their declaring type instead symbol = ((IMember) symbol).DeclaringType.GetDefinition(); } if (symbol != null) { var project = GetProjectFromSymbol(symbol); if (project != null) { var languageBinding = project.LanguageBinding; if (newName == null) { RenameSymbolDialog renameDialog = new RenameSymbolDialog(name => CheckName(name, languageBinding)) { Owner = SD.Workbench.MainWindow, OldSymbolName = symbol.Name, NewSymbolName = symbol.Name }; if (renameDialog.ShowDialog() == true) { newName = renameDialog.NewSymbolName; } else { return; } } AsynchronousWaitDialog.ShowWaitDialogForAsyncOperation( "${res:SharpDevelop.Refactoring.Rename}", progressMonitor => FindReferenceService.RenameSymbol(symbol, newName, progressMonitor) .ObserveOnUIThread() .Subscribe(error => SD.MessageService.ShowError(error.Message), ex => SD.MessageService.ShowException(ex), () => {})); } } }
private bool IsDiagnosticSuppressed(string id, ISymbol symbol) { Debug.Assert(id != null); Debug.Assert(symbol != null); if (symbol.Kind == SymbolKind.Namespace) { // Suppressions associated with namespace symbols only apply to namespace declarations themselves // and any syntax nodes immediately contained therein, not to nodes attached to any other symbols. // Diagnostics those nodes will be filtered by location, not by associated symbol. return false; } if (symbol.Kind == SymbolKind.Method) { var associated = ((IMethodSymbol)symbol).AssociatedSymbol; if (associated != null && (IsDiagnosticLocallySuppressed(id, associated) || IsDiagnosticGloballySuppressed(id, associated))) { return true; } } if (IsDiagnosticLocallySuppressed(id, symbol) || IsDiagnosticGloballySuppressed(id, symbol)) { return true; } // Check for suppression on parent symbol var parent = symbol.ContainingSymbol; return parent != null ? IsDiagnosticSuppressed(id, parent) : false; }
public static CompletionItem Create( string displayText, TextSpan span, ISymbol symbol, int contextPosition = -1, int descriptionPosition = -1, string sortText = null, string insertionText = null, Glyph? glyph = null, string filterText = null, bool preselect = false, SupportedPlatformData supportedPlatforms = null, bool isArgumentName = false, ImmutableDictionary<string, string> properties = null, CompletionItemRules rules = null) { return Create( displayText: displayText, span: span, symbols: ImmutableArray.Create(symbol), contextPosition: contextPosition, descriptionPosition: descriptionPosition, sortText: sortText, insertionText: insertionText, glyph: glyph, filterText: filterText, preselect: preselect, supportedPlatforms: supportedPlatforms, isArgumentName: isArgumentName, properties: properties, rules: rules); }
public bool HaveSameSignature(ISymbol symbol1, ISymbol symbol2, bool caseSensitive) { // NOTE - we're deliberately using reference equality here for speed. if (symbol1 == symbol2) { return true; } if (symbol1 == null || symbol2 == null) { return false; } if (symbol1.Kind != symbol2.Kind) { return false; } switch (symbol1.Kind) { case SymbolKind.Method: return HaveSameSignature((IMethodSymbol)symbol1, (IMethodSymbol)symbol2, caseSensitive); case SymbolKind.Property: return HaveSameSignature((IPropertySymbol)symbol1, (IPropertySymbol)symbol2, caseSensitive); case SymbolKind.Event: return HaveSameSignature((IEventSymbol)symbol1, (IEventSymbol)symbol2, caseSensitive); } return true; }
public CreatePartialCompletionData (ICompletionDataKeyHandler keyHandler, RoslynCodeCompletionFactory factory, int declarationBegin, ITypeSymbol currentType, ISymbol member, bool afterKeyword) : base (keyHandler, factory, member) { this.afterKeyword = afterKeyword; this.currentType = currentType; this.declarationBegin = declarationBegin; this.GenerateBody = true; }
public ICodeBlockEndedAnalyzer OnCodeBlockStarted(SyntaxNode codeBlock, ISymbol ownerSymbol, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken) { var methodSymbol = ownerSymbol as IMethodSymbol; if (methodSymbol == null || methodSymbol.ReturnsVoid || methodSymbol.ReturnType.Kind == SymbolKind.ArrayType || methodSymbol.Parameters.Length > 0 || !(methodSymbol.DeclaredAccessibility == Accessibility.Public || methodSymbol.DeclaredAccessibility == Accessibility.Protected) || methodSymbol.IsAccessorMethod() || !IsPropertyLikeName(methodSymbol.Name)) { return null; } // Fxcop has a few additional checks to reduce the noise for this diagnostic: // Ensure that the method is non-generic, non-virtual/override, has no overloads and doesn't have special names: 'GetHashCode' or 'GetEnumerator'. // Also avoid generating this diagnostic if the method body has any invocation expressions. if (methodSymbol.IsGenericMethod || methodSymbol.IsVirtual || methodSymbol.IsOverride || methodSymbol.ContainingType.GetMembers(methodSymbol.Name).Length > 1 || methodSymbol.Name == GetHashCodeName || methodSymbol.Name == GetEnumeratorName) { return null; } return GetCodeBlockEndedAnalyzer(); }
public SymbolLocationNavigableItem( Solution solution, ISymbol symbol, Location location) { _solution = solution; _symbol = symbol; _location = location; _lazyDisplayName = new Lazy<string>(() => { var symbolDisplayService = this.Document.Project.LanguageServices.GetService<ISymbolDisplayService>(); switch (symbol.Kind) { case SymbolKind.NamedType: return symbolDisplayService.ToDisplayString(_symbol, s_shortFormatWithModifiers); case SymbolKind.Method: return _symbol.IsStaticConstructor() ? symbolDisplayService.ToDisplayString(_symbol, s_shortFormatWithModifiers) : symbolDisplayService.ToDisplayString(_symbol, s_shortFormat); default: return symbolDisplayService.ToDisplayString(_symbol, s_shortFormat); } }); }
/// <summary> /// Constructs a new break command /// </summary> /// <param name="breakSymbol">Symbol to break at</param> public SetBreakpointNameCmd(ISymbol breakSymbol, SetBreakpointRH.SetBreakpointDelegate rhCb, GDBSubProcess gdbProc) : base(gdbProc) { _breakSymbol = breakSymbol; _rh = new SetBreakpointRH(rhCb, _gdbProc); }
/// <summary> /// The graphics device and clip rectangle are in the parent coordinates. /// </summary> /// <param name="g"></param> /// <param name="clipRectangle"></param> /// <param name="symbol">The symbol to use for drawing.</param> public void Draw(Graphics g, Rectangle clipRectangle, ISymbol symbol) { Color topLeft; Color bottomRight; if (_isSelected) { topLeft = _selectionColor.Darker(.3F); bottomRight = _selectionColor.Lighter(.3F); } else { topLeft = _backColor.Lighter(.3F); bottomRight = _backColor.Darker(.3F); } LinearGradientBrush b = new LinearGradientBrush(_bounds, topLeft, bottomRight, LinearGradientMode.ForwardDiagonal); GraphicsPath gp = new GraphicsPath(); gp.AddRoundedRectangle(Bounds, _roundingRadius); g.FillPath(b, gp); gp.Dispose(); b.Dispose(); Matrix old = g.Transform; Matrix shift = g.Transform; shift.Translate(_bounds.Left + _bounds.Width / 2, _bounds.Top + _bounds.Height / 2); g.Transform = shift; if (symbol != null) { OnDrawSymbol(g, symbol); } g.Transform = old; }
ICSharpCode.SharpDevelop.Project.IProject GetProjectFromSymbol(ISymbol symbol) { switch (symbol.SymbolKind) { case SymbolKind.None: return null; case SymbolKind.TypeDefinition: case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Indexer: case SymbolKind.Event: case SymbolKind.Method: case SymbolKind.Operator: case SymbolKind.Constructor: case SymbolKind.Destructor: case SymbolKind.Accessor: return ((IEntity)symbol).ParentAssembly.GetProject(); case SymbolKind.Namespace: return null; // TODO : extend rename on namespaces case SymbolKind.Variable: return SD.ProjectService.FindProjectContainingFile(new FileName(((IVariable)symbol).Region.FileName)); case SymbolKind.Parameter: if (((IParameter) symbol).Owner != null) { return ((IParameter)symbol).Owner.ParentAssembly.GetProject(); } else { return SD.ProjectService.FindProjectContainingFile(new FileName(((IParameter)symbol).Region.FileName)); } case SymbolKind.TypeParameter: return null; // TODO : extend rename on type parameters default: throw new ArgumentOutOfRangeException(); } }
public static async Task<Solution> RenameSymbolAsync(Solution solution, ISymbol symbol, string newName, OptionSet optionSet, CancellationToken cancellationToken = default(CancellationToken)) { if (solution == null) { throw new ArgumentNullException(nameof(solution)); } if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (string.IsNullOrEmpty(newName)) { throw new ArgumentException("newName"); } cancellationToken.ThrowIfCancellationRequested(); optionSet = optionSet ?? solution.Workspace.Options; var renameLocationSet = await RenameLocationSet.FindAsync(symbol, solution, optionSet, cancellationToken).ConfigureAwait(false); var conflictResolution = await ConflictEngine.ConflictResolver.ResolveConflictsAsync(renameLocationSet, symbol.Name, newName, optionSet, cancellationToken).ConfigureAwait(false); return conflictResolution.NewSolution; }
/// <summary> /// Finds all references to a symbol throughout a solution /// </summary> /// <param name="symbol">The symbol to find references to.</param> /// <param name="solution">The solution to find references within.</param> /// <param name="cancellationToken">A cancellation token.</param> public static Task<IEnumerable<ReferencedSymbol>> FindReferencesAsync( ISymbol symbol, Solution solution, CancellationToken cancellationToken = default(CancellationToken)) { return FindReferencesAsync(symbol, solution, progress: null, documents: null, cancellationToken: cancellationToken); }
private int GetSymbolDepth(ISymbol symbol) { ISymbol current = symbol.ContainingSymbol; int depth = 0; while (current != null) { var namespaceSymbol = current as INamespaceSymbol; if (namespaceSymbol != null) { // if we've reached the global namespace, we're already at the top; bail if (namespaceSymbol.IsGlobalNamespace) { break; } } else { // we don't want namespaces to add to our "depth" because they won't be displayed in the tree depth++; } current = current.ContainingSymbol; } return depth; }
private IEnumerable<AutoCompleteResponse> MakeSnippetedResponses(AutoCompleteRequest request, ISymbol symbol) { var completions = new List<AutoCompleteResponse>(); var methodSymbol = symbol as IMethodSymbol; if (methodSymbol != null) { if (methodSymbol.Parameters.Any(p => p.IsOptional)) { completions.Add(MakeAutoCompleteResponse(request, symbol, false)); } completions.Add(MakeAutoCompleteResponse(request, symbol)); return completions; } var typeSymbol = symbol as INamedTypeSymbol; if (typeSymbol != null) { completions.Add(MakeAutoCompleteResponse(request, symbol)); if (typeSymbol.TypeKind != TypeKind.Enum) { foreach (var ctor in typeSymbol.InstanceConstructors) { completions.Add(MakeAutoCompleteResponse(request, ctor)); } } return completions; } return new[] { MakeAutoCompleteResponse(request, symbol) }; }
internal RenameLocations(ISet<RenameLocation> locations, ISymbol symbol, Solution solution, IEnumerable<ISymbol> referencedSymbols, IEnumerable<ReferenceLocation> implicitLocations, OptionSet options) { _symbol = symbol; _solution = solution; _mergedResult = new SearchResult(locations, implicitLocations, referencedSymbols); Options = options; }
public HtmlElementInfo GenerateHyperlinkToReferences(ISymbol symbol, bool isLargeFile = false) { string symbolId = SymbolIdService.GetId(symbol); string referencesFilePath = Path.Combine(ProjectDestinationFolder, Constants.ReferencesFileName, symbolId + ".html"); string href = Paths.MakeRelativeToFile(referencesFilePath, documentDestinationFilePath); href = href.Replace('\\', '/'); var result = new HtmlElementInfo { Name = "a", Attributes = { { "id", symbolId }, { "href", href }, { "target", "n" }, }, DeclaredSymbol = symbol, DeclaredSymbolId = symbolId }; if (!isLargeFile) { var dataGlyph = string.Format("{0},{1}", SymbolIdService.GetGlyphNumber(symbol), GetSymbolDepth(symbol)); result.Attributes.Add("data-glyph", dataGlyph); } return result; }
public MetadataNamedArgument(ISymbol entity, Cci.ITypeReference type, Cci.IMetadataExpression value) { // entity must be one of INamedEntity or IFieldDefinition or IPropertyDefinition this.entity = entity; this.type = type; this.value = value; }
private QuickFix ConvertSymbol(ISymbol symbol, Location location) { var lineSpan = location.GetLineSpan(); var path = lineSpan.Path; var documents = _workspace.GetDocuments(path); var format = SymbolDisplayFormat.MinimallyQualifiedFormat; format = format.WithMemberOptions(format.MemberOptions ^ SymbolDisplayMemberOptions.IncludeContainingType ^ SymbolDisplayMemberOptions.IncludeType); format = format.WithKindOptions(SymbolDisplayKindOptions.None); return new SymbolLocation { Text = symbol.ToDisplayString(format), Kind = symbol.GetKind(), FileName = path, Line = lineSpan.StartLinePosition.Line + 1, Column = lineSpan.StartLinePosition.Character + 1, EndLine = lineSpan.EndLinePosition.Line + 1, EndColumn = lineSpan.EndLinePosition.Character + 1, Projects = documents.Select(document => document.Project.Name).ToArray() }; }
public static async Task ComputeRefactoringsAsync(RefactoringContext context, YieldStatementSyntax yieldStatement) { if (context.IsAnyRefactoringEnabled( RefactoringIdentifiers.ChangeMemberTypeAccordingToYieldReturnExpression, RefactoringIdentifiers.AddCastExpression, RefactoringIdentifiers.CallToMethod) && yieldStatement.IsYieldReturn() && yieldStatement.Expression != null) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); ISymbol memberSymbol = ReturnExpressionRefactoring.GetContainingMethodOrPropertySymbol(yieldStatement.Expression, semanticModel, context.CancellationToken); if (memberSymbol != null) { SyntaxNode node = await memberSymbol .DeclaringSyntaxReferences[0] .GetSyntaxAsync(context.CancellationToken) .ConfigureAwait(false); TypeSyntax type = ReturnExpressionRefactoring.GetTypeOrReturnType(node); if (type != null) { ITypeSymbol memberTypeSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken); if (memberTypeSymbol?.SpecialType != SpecialType.System_Collections_IEnumerable) { ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(yieldStatement.Expression, context.CancellationToken); if (context.IsRefactoringEnabled(RefactoringIdentifiers.ChangeMemberTypeAccordingToYieldReturnExpression) && typeSymbol?.IsErrorType() == false && !typeSymbol.IsVoid() && !memberSymbol.IsOverride && (memberTypeSymbol == null || memberTypeSymbol.IsErrorType() || !memberTypeSymbol.IsConstructedFromIEnumerableOfT() || !((INamedTypeSymbol)memberTypeSymbol).TypeArguments[0].Equals(typeSymbol))) { INamedTypeSymbol newTypeSymbol = semanticModel .Compilation .GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T) .Construct(typeSymbol); TypeSyntax newType = newTypeSymbol.ToMinimalTypeSyntax(semanticModel, type.SpanStart); context.RegisterRefactoring( $"Change {ReturnExpressionRefactoring.GetText(node)} type to '{SymbolDisplay.GetMinimalString(newTypeSymbol, semanticModel, type.SpanStart)}'", cancellationToken => { return(ChangeTypeRefactoring.ChangeTypeAsync( context.Document, type, newType, cancellationToken)); }); } if (context.IsAnyRefactoringEnabled(RefactoringIdentifiers.AddCastExpression, RefactoringIdentifiers.CallToMethod) && yieldStatement.Expression.Span.Contains(context.Span) && memberTypeSymbol?.IsNamedType() == true) { var namedTypeSymbol = (INamedTypeSymbol)memberTypeSymbol; if (namedTypeSymbol.IsConstructedFromIEnumerableOfT()) { ITypeSymbol argumentSymbol = namedTypeSymbol.TypeArguments[0]; if (argumentSymbol != typeSymbol) { ModifyExpressionRefactoring.ComputeRefactoring( context, yieldStatement.Expression, argumentSymbol, semanticModel); } } } } } } } if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceStatementWithIfStatement) && context.Span.IsBetweenSpans(yieldStatement)) { var refactoring = new ReplaceYieldStatementWithIfStatementRefactoring(); await refactoring.ComputeRefactoringAsync(context, yieldStatement).ConfigureAwait(false); } if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseListInsteadOfYield)) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); UseListInsteadOfYieldRefactoring.ComputeRefactoring(context, yieldStatement, semanticModel); } }
private static string GetQualifiedName(ISymbol symbol) { return(symbol.ToDisplayString(new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters))); }
protected abstract SyntaxNode AddGlobalSuppressMessageAttribute(SyntaxNode newRoot, ISymbol targetSymbol, Diagnostic diagnostic);
protected string GetTargetString(ISymbol targetSymbol) { return "~" + DocumentationCommentId.CreateDeclarationId(targetSymbol); }
public static bool TryGoToDefinition( ISymbol symbol, Project project, IEnumerable <Lazy <IStreamingFindUsagesPresenter> > streamingPresenters, CancellationToken cancellationToken, bool thirdPartyNavigationAllowed = true, bool throwOnHiddenDefinition = false) { var alias = symbol as IAliasSymbol; if (alias != null) { var ns = alias.Target as INamespaceSymbol; if (ns != null && ns.IsGlobalNamespace) { return(false); } } // VB global import aliases have a synthesized SyntaxTree. // We can't go to the definition of the alias, so use the target type. var solution = project.Solution; if (alias != null) { var sourceLocations = NavigableItemFactory.GetPreferredSourceLocations( solution, symbol, cancellationToken); if (sourceLocations.All(l => project.Solution.GetDocument(l.SourceTree) == null)) { symbol = alias.Target; } } var definition = SymbolFinder.FindSourceDefinitionAsync(symbol, solution, cancellationToken).WaitAndGetResult(cancellationToken); cancellationToken.ThrowIfCancellationRequested(); symbol = definition ?? symbol; // If it is a partial method declaration with no body, choose to go to the implementation // that has a method body. if (symbol is IMethodSymbol method) { symbol = method.PartialImplementationPart ?? symbol; } var definitions = ArrayBuilder <DefinitionItem> .GetInstance(); // Going to a symbol may end up actually showing the symbol in the Find-Usages window. // This happens when there is more than one location for the symbol (i.e. for partial // symbols) and we don't know the best place to take you to. // // The FindUsages window supports showing the classified text for an item. It does this // in two ways. Either the item can pass along its classified text (and the window will // defer to that), or the item will have no classified text, and the window will compute // it in the BG. // // Passing along the classified information is valuable for OOP scenarios where we want // all that expensive computation done on the OOP side and not in the VS side. // // However, Go To Definition is all in-process, and is also synchronous. So we do not // want to fetch the classifications here. It slows down the command and leads to a // measurable delay in our perf tests. // // So, if we only have a single location to go to, this does no unnecessary work. And, // if we do have multiple locations to show, it will just be done in the BG, unblocking // this command thread so it can return the user faster. var definitionItem = symbol.ToNonClassifiedDefinitionItem(solution, includeHiddenLocations: true); if (thirdPartyNavigationAllowed) { var factory = solution.Workspace.Services.GetService <IDefinitionsAndReferencesFactory>(); var thirdPartyItem = factory?.GetThirdPartyDefinitionItem(solution, definitionItem, cancellationToken); definitions.AddIfNotNull(thirdPartyItem); } definitions.Add(definitionItem); var presenter = streamingPresenters.FirstOrDefault()?.Value; var title = string.Format(EditorFeaturesResources._0_declarations, FindUsagesHelpers.GetDisplayName(symbol)); return(presenter.TryNavigateToOrPresentItemsAsync( project.Solution.Workspace, title, definitions.ToImmutableAndFree()).WaitAndGetResult(cancellationToken)); }
public bool TryGetDocument(ISymbol symbol, out IDocument document) { return(_symbolToDocument.TryGetValue(symbol, out document)); }
private SymbolDocumentValue DocumentFor(ISymbol symbol) { return(new SymbolDocumentValue(symbol, this)); }
private string GetSyntax(ISymbol symbol) { return(SyntaxHelper.GetSyntax(symbol)); }
public static bool IsObsolete(this ISymbol symbol) => symbol.HasAttribute(KnownType.System_ObsoleteAttribute);
// Helpers below... // This was helpful: http://stackoverflow.com/a/30445814/807064 private IEnumerable <ISymbol> GetAccessibleMembersInThisAndBaseTypes(ITypeSymbol containingType, ISymbol within) { List <ISymbol> members = ((IEnumerable <ISymbol>)_getAccessibleMembersInThisAndBaseTypes.Invoke(null, new object[] { containingType, within })).ToList(); // Remove overridden symbols ImmutableHashSet <ISymbol> remove = members .Select(x => (ISymbol)(x as IMethodSymbol)?.OverriddenMethod ?? (x as IPropertySymbol)?.OverriddenProperty) .Where(x => x != null) .ToImmutableHashSet(); members.RemoveAll(x => remove.Contains(x)); return(members); }
internal static bool HasAttribute(this ISymbol symbol, KnownType attributeType) => symbol?.GetAttributes().Any(a => a.AttributeClass.Is(attributeType)) ?? false;
public ISymbol FindImplementationForInterfaceMember(ISymbol interfaceMember) => null;
public static bool CanSymbolBeInterfaceMemberOrOverride(ISymbol symbol) { return(symbol is IMethodSymbol || symbol is IPropertySymbol || symbol is IEventSymbol); }
internal static bool HasAnyAttribute(this ISymbol symbol, ISet <KnownType> attributeTypes) => symbol?.GetAttributes().Any(a => a.AttributeClass.IsAny(attributeTypes)) ?? false;
private static bool FilterMembersToFlatten(ISymbol m) => m.OriginalDefinition.DeclaredAccessibility == Accessibility.Public && !m.OriginalDefinition.IsStatic && !m.IsAbstract;
public static bool IsConstructor(this ISymbol symbol) { return(symbol.Kind == SymbolKind.Method && symbol.Name == ".ctor"); }
public static IEnumerable <NameAndLocation> ItemsToIgnoreFromAttributes(ISymbol symbol, IEnumerable <Type> attributes) {
private static async Task <Document> GetUpdatedDocumentForParameterRenameAsync(Document document, ISymbol parameter, string newName, CancellationToken cancellationToken) { Solution newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution, parameter, newName, null, cancellationToken).ConfigureAwait(false); return(newSolution.GetDocument(document.Id)); }
private static bool AutoGenerated(ISymbol symbol) { return(SyntaxRootContainsAutoGeneratedComment(symbol.DeclaringSyntaxReferences[0].SyntaxTree.GetRoot())); }
private static bool InfoBoundSuccessfully(ISymbol operation) { operation = operation.GetOriginalUnreducedDefinition(); return(operation != null); }
public static bool SkipSymbolAnalysis(ISymbol symbol, SettingsHandler settingsHandler, IEnumerable <Type> suppressionAttributes) { return(HasIgnoreRuleAttribute(symbol, suppressionAttributes) || SkipSymbolAnalysisIgnoringAttributes(symbol, settingsHandler)); }
private static bool HasIgnoreRuleAttribute(ISymbol symbol, IEnumerable <Type> attributes) { return(symbol.GetAttributes() .Any(s => attributes.TryFirst(t => MatchAttributeName(t, s.AttributeClass?.Name)).HasValue)); }
private static bool AllMatches <TSymbolMatcher>(ImmutableArray <TSymbolMatcher> matchers, ISymbol symbol) where TSymbolMatcher : ISymbolMatcher { foreach (var matcher in matchers) { if (!matcher.MatchesSymbol(symbol)) { return(false); } } return(true); }
public static bool SkipSymbolAnalysisIgnoringAttributes(ISymbol symbol, SettingsHandler settingsHandler) { var settings = settingsHandler.GetArnolyzerSettingsForProject(GetFilePathForSymbol(symbol)); return(AutoGenerated(symbol) || IgnoredFile(symbol, settings)); }
public void visit(Var var) { string varName = var.name; ISymbol s = scope.find(varName); }
public Hypothesis(ISymbol premise, ISymbol conclusion) { this.premise = premise; this.conclusion = conclusion; }
public async Task Rename(ISymbol symbol) { var ws = IdeApp.Workbench.ActiveDocument.RoslynWorkspace; var currentSolution = ws.CurrentSolution; var cts = new CancellationTokenSource(); var newSolution = await MessageService.ExecuteTaskAndShowWaitDialog(Task.Run(() => Renamer.RenameSymbolAsync(currentSolution, symbol, "_" + symbol.Name + "_", ws.Options, cts.Token)), GettextCatalog.GetString("Looking for all references"), cts); var projectChanges = currentSolution.GetChanges(newSolution).GetProjectChanges().ToList(); var changedDocuments = new HashSet <string> (); foreach (var change in projectChanges) { foreach (var changedDoc in change.GetChangedDocuments()) { changedDocuments.Add(ws.CurrentSolution.GetDocument(changedDoc).FilePath); } } if (changedDocuments.Count > 1) { using (var dlg = new RenameItemDialog(symbol, this)) MessageService.ShowCustomDialog(dlg); return; } var projectChange = projectChanges [0]; var changes = projectChange.GetChangedDocuments().ToList(); if (changes.Count != 1 || symbol.Kind == SymbolKind.NamedType) { using (var dlg = new RenameItemDialog(symbol, this)) MessageService.ShowCustomDialog(dlg); return; } var doc = IdeApp.Workbench.ActiveDocument; var editor = doc.Editor; var oldVersion = editor.Version; var links = new List <TextLink> (); var link = new TextLink("name"); var documents = ImmutableHashSet.Create(doc.AnalysisDocument); foreach (var loc in symbol.Locations) { if (loc.IsInSource && FilePath.PathComparer.Equals(loc.SourceTree.FilePath, doc.FileName)) { link.AddLink(new TextSegment(loc.SourceSpan.Start, loc.SourceSpan.Length)); } } foreach (var mref in await SymbolFinder.FindReferencesAsync(symbol, doc.AnalysisDocument.Project.Solution, documents, default(CancellationToken))) { foreach (var loc in mref.Locations) { TextSpan span = loc.Location.SourceSpan; var root = loc.Location.SourceTree.GetRoot(); var node = root.FindNode(loc.Location.SourceSpan); var trivia = root.FindTrivia(loc.Location.SourceSpan.Start); if (!trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia)) { span = node.Span; } if (span.Start != loc.Location.SourceSpan.Start) { span = loc.Location.SourceSpan; } var segment = new TextSegment(span.Start, span.Length); if (segment.Offset <= editor.CaretOffset && editor.CaretOffset <= segment.EndOffset) { link.Links.Insert(0, segment); } else { link.AddLink(segment); } } } links.Add(link); editor.StartTextLinkMode(new TextLinkModeOptions(links, (arg) => { //If user cancel renaming revert changes if (!arg.Success) { var textChanges = editor.Version.GetChangesTo(oldVersion).ToList(); for (int i = textChanges.Count - 1; i >= 0; i--) { var change = textChanges [i]; var rollbackChanges = new List <Microsoft.CodeAnalysis.Text.TextChange> (); for (int j = 0; j < change.TextChanges.Count; j++) { var textChange = change.TextChanges [j]; rollbackChanges.Add(new Microsoft.CodeAnalysis.Text.TextChange(new TextSpan(textChange.Offset, textChange.InsertionLength), textChange.RemovedText.Text)); } editor.ApplyTextChanges(rollbackChanges); } } }) { TextLinkPurpose = TextLinkPurpose.Rename }); }
public bool AppliesTo(ISymbol symbol) => AnyMatches(this.ApplicableSymbolKindList, symbol) && AllMatches(this.RequiredModifierList, symbol) && AnyMatches(this.ApplicableAccessibilityList, symbol);