internal GenerateTypeDialogViewModel(
            Document document,
            INotificationService notificationService,
            IProjectManagementService projectManagementService,
            ISyntaxFactsService syntaxFactsService,
            GenerateTypeDialogOptions generateTypeDialogOptions,
            string typeName,
            string fileExtension,
            bool isNewFile,
            string accessSelectString,
            string typeKindSelectString)
        {
            _generateTypeDialogOptions = generateTypeDialogOptions;

            InitialSetup(document.Project.Language);
            var dependencyGraph = document.Project.Solution.GetProjectDependencyGraph();

            // Initialize the dependencies
            var projectListing = new List <ProjectSelectItem>();

            // Populate the project list
            // Add the current project
            projectListing.Add(new ProjectSelectItem(document.Project));

            // Add the rest of the projects
            // Adding dependency graph to avoid cyclic dependency
            projectListing.AddRange(document.Project.Solution.Projects
                                    .Where(p => p != document.Project && !dependencyGraph.GetProjectsThatThisProjectTransitivelyDependsOn(p.Id).Contains(document.Project.Id))
                                    .Select(p => new ProjectSelectItem(p)));

            this.ProjectList = projectListing;

            const string attributeSuffix = "Attribute";

            _typeName     = generateTypeDialogOptions.IsAttribute && !typeName.EndsWith(attributeSuffix, StringComparison.Ordinal) ? typeName + attributeSuffix : typeName;
            this.FileName = typeName + fileExtension;

            _document             = document;
            this.SelectedProject  = document.Project;
            this.SelectedDocument = document;
            _notificationService  = notificationService;

            this.AccessList = document.Project.Language == LanguageNames.CSharp
                ? _csharpAccessList
                : _visualBasicAccessList;
            this.AccessSelectIndex = this.AccessList.Contains(accessSelectString)
                ? this.AccessList.IndexOf(accessSelectString) : 0;
            this.IsAccessListEnabled = true;

            this.KindList = document.Project.Language == LanguageNames.CSharp
                ? _csharpTypeKindList
                : _visualBasicTypeKindList;
            this.KindSelectIndex = this.KindList.Contains(typeKindSelectString)
                ? this.KindList.IndexOf(typeKindSelectString) : 0;

            this.ProjectSelectIndex  = 0;
            this.DocumentSelectIndex = 0;

            _isNewFile = isNewFile;

            _syntaxFactsService = syntaxFactsService;

            _projectManagementService = projectManagementService;
            if (projectManagementService != null)
            {
                this.ProjectFolders = _projectManagementService.GetFolders(this.SelectedProject.Id, this.SelectedProject.Solution.Workspace);
            }
            else
            {
                this.ProjectFolders = SpecializedCollections.EmptyList <string>();
            }
        }
 private static IList <SyntaxNode> GetStatements(CodeGenerationMethodInfo info)
 {
     return(info == null
         ? SpecializedCollections.EmptyList <SyntaxNode>()
         : info._statements);
 }
 private static IList <SyntaxNode> GetHandlesExpressions(CodeGenerationMethodInfo info)
 {
     return(info == null
         ? SpecializedCollections.EmptyList <SyntaxNode>()
         : info._handlesExpressions);
 }
Exemple #4
0
 private static SyntaxNode CreateNotImplementedException(SyntaxGenerator codeDefinitionFactory, Compilation compilation)
 => codeDefinitionFactory.ObjectCreationExpression(
     codeDefinitionFactory.TypeExpression(compilation.NotImplementedExceptionType(), addImport: false),
     SpecializedCollections.EmptyList <SyntaxNode>());
 protected IList <TaggedText> GetAwaitableUsage(IMethodSymbol method, SemanticModel semanticModel, int position)
 {
     return(SpecializedCollections.EmptyList <TaggedText>());
 }
Exemple #6
0
        private IList <ParameterViewModel> GetSelectedGroup()
        {
            var index = SelectedIndex;

            index = _thisParameter == null ? index : index - 1;
            return(index < _parameterGroup1.Count ? _parameterGroup1 : index < _parameterGroup1.Count + _parameterGroup2.Count ? _parameterGroup2 : SpecializedCollections.EmptyList <ParameterViewModel>());
        }
Exemple #7
0
            private (string[] containers, string usingOrImport) GetNamespaceContainersAndAddUsingsOrImport(
                bool isDialog,
                IList <string> folders,
                bool areFoldersValidIdentifiers,
                Project targetProject,
                Project triggeringProject)
            {
                string includeUsingsOrImports = null;

                if (!areFoldersValidIdentifiers)
                {
                    folders = SpecializedCollections.EmptyList <string>();
                }

                // Now actually create the symbol that we want to add to the root namespace.  The
                // symbol may either be a named type (if we're not generating into a namespace) or
                // it may be a namespace symbol.
                string[] containers = null;
                if (!isDialog)
                {
                    // Not generated from the Dialog
                    containers = GetNamespaceToGenerateInto().Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                }
                else if (!_service.IsSimpleName(_state.NameOrMemberAccessExpression))
                {
                    // If the usage was with a namespace
                    containers = GetNamespaceToGenerateIntoForUsageWithNamespace(targetProject, triggeringProject).Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                }
                else
                {
                    // Generated from the Dialog
                    var containerList = new List <string>();

                    var rootNamespaceOfTheProjectGeneratedInto =
                        _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange
                            ? _service.GetRootNamespace(_generateTypeOptionsResult.Project.CompilationOptions).Trim()
                            : _targetLanguageService.GetRootNamespace(_generateTypeOptionsResult.Project.CompilationOptions).Trim();

                    var projectManagementService = _document.Project.Solution.Workspace.Services.GetService <IProjectManagementService>();
                    var defaultNamespace         = _generateTypeOptionsResult.DefaultNamespace;

                    // Case 1 : If the type is generated into the same C# project or
                    // Case 2 : If the type is generated from a C# project to a C# Project
                    // Case 3 : If the Type is generated from a VB Project to a C# Project
                    // Using and Namespace will be the DefaultNamespace + Folder Structure
                    if ((_document.Project == _generateTypeOptionsResult.Project && _document.Project.Language == LanguageNames.CSharp) ||
                        (_targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.CSharp) ||
                        _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.VisualBasicToCSharp)
                    {
                        if (!string.IsNullOrWhiteSpace(defaultNamespace))
                        {
                            containerList.Add(defaultNamespace);
                        }

                        // Populate the ContainerList
                        AddFoldersToNamespaceContainers(containerList, folders);

                        containers             = containerList.ToArray();
                        includeUsingsOrImports = string.Join(".", containerList.ToArray());
                    }

                    // Case 4 : If the type is generated into the same VB project or
                    // Case 5 : If Type is generated from a VB Project to VB Project
                    // Case 6 : If Type is generated from a C# Project to VB Project
                    // Namespace will be Folder Structure and Import will have the RootNamespace of the project generated into as part of the Imports
                    if ((_document.Project == _generateTypeOptionsResult.Project && _document.Project.Language == LanguageNames.VisualBasic) ||
                        (_document.Project != _generateTypeOptionsResult.Project && _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.NoChange && _generateTypeOptionsResult.Project.Language == LanguageNames.VisualBasic) ||
                        _targetProjectChangeInLanguage == TargetProjectChangeInLanguage.CSharpToVisualBasic)
                    {
                        // Populate the ContainerList
                        AddFoldersToNamespaceContainers(containerList, folders);
                        containers             = containerList.ToArray();
                        includeUsingsOrImports = string.Join(".", containerList.ToArray());
                        if (!string.IsNullOrWhiteSpace(rootNamespaceOfTheProjectGeneratedInto))
                        {
                            includeUsingsOrImports = string.IsNullOrEmpty(includeUsingsOrImports) ?
                                                     rootNamespaceOfTheProjectGeneratedInto :
                                                     rootNamespaceOfTheProjectGeneratedInto + "." + includeUsingsOrImports;
                        }
                    }

                    Contract.Assert(includeUsingsOrImports != null);
                }

                return(containers, includeUsingsOrImports);
            }
Exemple #8
0
 public SolutionPreviewResult(IList <SolutionPreviewItem> previews, SolutionChangeSummary changeSummary = null)
 {
     _previews          = previews ?? SpecializedCollections.EmptyList <SolutionPreviewItem>();
     this.ChangeSummary = changeSummary;
 }
        public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document          = context.Document;
            var span              = context.Span;
            var diagnostics       = context.Diagnostics;
            var cancellationToken = context.CancellationToken;

            var project    = document.Project;
            var diagnostic = diagnostics.First();
            var root       = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var ancestors = root.FindToken(span.Start, findInsideTrivia: true).GetAncestors <SyntaxNode>();

            if (!ancestors.Any())
            {
                return;
            }

            var node = ancestors.FirstOrDefault(n => n.Span.Contains(span) && n != root);

            if (node == null)
            {
                return;
            }

            var placeSystemNamespaceFirst = document.Project.Solution.Workspace.Options.GetOption(Microsoft.CodeAnalysis.Shared.Options.OrganizerOptions.PlaceSystemNamespaceFirst, document.Project.Language);

            using (Logger.LogBlock(FunctionId.Refactoring_AddImport, cancellationToken))
            {
                if (!cancellationToken.IsCancellationRequested)
                {
                    if (this.CanAddImport(node, cancellationToken))
                    {
                        var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                        var containingType           = semanticModel.GetEnclosingNamedType(node.SpanStart, cancellationToken);
                        var containingTypeOrAssembly = containingType ?? (ISymbol)semanticModel.Compilation.Assembly;
                        var namespacesInScope        = this.GetNamespacesInScope(semanticModel, node, cancellationToken);
                        var syntaxFacts = document.Project.LanguageServices.GetService <ISyntaxFactsService>();

                        var matchingTypesNamespaces = await this.GetNamespacesForMatchingTypesAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);

                        var matchingTypes = await this.GetMatchingTypesAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);

                        var matchingNamespaces = await this.GetNamespacesForMatchingNamespacesAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);

                        var matchingExtensionMethodsNamespaces = await this.GetNamespacesForMatchingExtensionMethodsAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);

                        var matchingFieldsAndPropertiesAsync = await this.GetNamespacesForMatchingFieldsAndPropertiesAsync(project, diagnostic, node, semanticModel, namespacesInScope, syntaxFacts, cancellationToken).ConfigureAwait(false);

                        var queryPatternsNamespaces = await this.GetNamespacesForQueryPatternsAsync(project, diagnostic, node, semanticModel, namespacesInScope, cancellationToken).ConfigureAwait(false);

                        if (matchingTypesNamespaces != null || matchingNamespaces != null || matchingExtensionMethodsNamespaces != null || matchingFieldsAndPropertiesAsync != null || queryPatternsNamespaces != null || matchingTypes != null)
                        {
                            matchingTypesNamespaces            = matchingTypesNamespaces ?? SpecializedCollections.EmptyList <INamespaceSymbol>();
                            matchingNamespaces                 = matchingNamespaces ?? SpecializedCollections.EmptyList <INamespaceSymbol>();
                            matchingExtensionMethodsNamespaces = matchingExtensionMethodsNamespaces ?? SpecializedCollections.EmptyList <INamespaceSymbol>();
                            matchingFieldsAndPropertiesAsync   = matchingFieldsAndPropertiesAsync ?? SpecializedCollections.EmptyList <INamespaceSymbol>();
                            queryPatternsNamespaces            = queryPatternsNamespaces ?? SpecializedCollections.EmptyList <INamespaceSymbol>();
                            matchingTypes = matchingTypes ?? SpecializedCollections.EmptyList <ITypeSymbol>();

                            var proposedImports =
                                matchingTypesNamespaces.Cast <INamespaceOrTypeSymbol>()
                                .Concat(matchingNamespaces.Cast <INamespaceOrTypeSymbol>())
                                .Concat(matchingExtensionMethodsNamespaces.Cast <INamespaceOrTypeSymbol>())
                                .Concat(matchingFieldsAndPropertiesAsync.Cast <INamespaceOrTypeSymbol>())
                                .Concat(queryPatternsNamespaces.Cast <INamespaceOrTypeSymbol>())
                                .Concat(matchingTypes.Cast <INamespaceOrTypeSymbol>())
                                .Distinct()
                                .Where(NotNull)
                                .Where(NotGlobalNamespace)
                                .OrderBy(INamespaceOrTypeSymbolExtensions.CompareNamespaceOrTypeSymbols)
                                .Take(8)
                                .ToList();

                            if (proposedImports.Count > 0)
                            {
                                cancellationToken.ThrowIfCancellationRequested();

                                foreach (var import in proposedImports)
                                {
                                    var action = new MyCodeAction(this.GetDescription(import, semanticModel, node), (c) =>
                                                                  this.AddImportAsync(node, import, document, placeSystemNamespaceFirst, cancellationToken));

                                    context.RegisterCodeFix(action, diagnostic);
                                }
                            }
                        }
                    }
                }
            }
        }
        protected IPropertySymbol GenerateProperty(string propertyName, string fieldName, Accessibility accessibility, IFieldSymbol field, INamedTypeSymbol containingSymbol, SyntaxAnnotation annotation, Document document, CancellationToken cancellationToken)
        {
            var factory = document.GetLanguageService <SyntaxGenerator>();

            var propertySymbol = annotation.AddAnnotationToSymbol(CodeGenerationSymbolFactory.CreatePropertySymbol(containingType: containingSymbol,
                                                                                                                   attributes: SpecializedCollections.EmptyList <AttributeData>(),
                                                                                                                   accessibility: ComputeAccessibility(accessibility, field.Type),
                                                                                                                   modifiers: new DeclarationModifiers(isStatic: field.IsStatic, isReadOnly: field.IsReadOnly, isUnsafe: field.IsUnsafe()),
                                                                                                                   type: field.Type,
                                                                                                                   explicitInterfaceSymbol: null,
                                                                                                                   name: propertyName,
                                                                                                                   parameters: SpecializedCollections.EmptyList <IParameterSymbol>(),
                                                                                                                   getMethod: CreateGet(fieldName, field, factory),
                                                                                                                   setMethod: field.IsReadOnly || field.IsConst ? null : CreateSet(fieldName, field, factory)));

            return(Simplifier.Annotation.AddAnnotationToSymbol(
                       Formatter.Annotation.AddAnnotationToSymbol(propertySymbol)));
        }
Exemple #11
0
        protected SignatureHelpItem CreateItem(
            ISymbol orderSymbol,
            SemanticModel semanticModel,
            int position,
            ISymbolDisplayService symbolDisplayService,
            IAnonymousTypeDisplayService anonymousTypeDisplayService,
            bool isVariadic,
            Func <CancellationToken, IEnumerable <TaggedText> > documentationFactory,
            IList <SymbolDisplayPart> prefixParts,
            IList <SymbolDisplayPart> separatorParts,
            IList <SymbolDisplayPart> suffixParts,
            IList <SignatureHelpSymbolParameter> parameters,
            IList <SymbolDisplayPart> descriptionParts = null)
        {
            prefixParts      = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(prefixParts, semanticModel, position, symbolDisplayService);
            separatorParts   = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(separatorParts, semanticModel, position, symbolDisplayService);
            suffixParts      = anonymousTypeDisplayService.InlineDelegateAnonymousTypes(suffixParts, semanticModel, position, symbolDisplayService);
            parameters       = parameters.Select(p => InlineDelegateAnonymousTypes(p, semanticModel, position, symbolDisplayService, anonymousTypeDisplayService)).ToList();
            descriptionParts = descriptionParts == null
                ? SpecializedCollections.EmptyList <SymbolDisplayPart>()
                : descriptionParts;

            var allParts = prefixParts.Concat(separatorParts)
                           .Concat(suffixParts)
                           .Concat(parameters.SelectMany(p => p.GetAllParts()))
                           .Concat(descriptionParts);

            var directAnonymousTypeReferences =
                from part in allParts
                where part.Symbol.IsNormalAnonymousType()
                select(INamedTypeSymbol) part.Symbol;

            var info = anonymousTypeDisplayService.GetNormalAnonymousTypeDisplayInfo(
                orderSymbol, directAnonymousTypeReferences, semanticModel, position, symbolDisplayService);

            if (info.AnonymousTypesParts.Count > 0)
            {
                var anonymousTypeParts = new List <SymbolDisplayPart>
                {
                    new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, "\r\n\r\n")
                };

                anonymousTypeParts.AddRange(info.AnonymousTypesParts);

                return(new SymbolKeySignatureHelpItem(
                           orderSymbol,
                           isVariadic,
                           documentationFactory,
                           info.ReplaceAnonymousTypes(prefixParts).ToTaggedText(),
                           info.ReplaceAnonymousTypes(separatorParts).ToTaggedText(),
                           info.ReplaceAnonymousTypes(suffixParts).ToTaggedText(),
                           parameters.Select(p => ReplaceAnonymousTypes(p, info)).Select(p => (SignatureHelpParameter)p),
                           anonymousTypeParts.ToTaggedText()));
            }

            return(new SymbolKeySignatureHelpItem(
                       orderSymbol,
                       isVariadic,
                       documentationFactory,
                       prefixParts.ToTaggedText(),
                       separatorParts.ToTaggedText(),
                       suffixParts.ToTaggedText(),
                       parameters.Select(p => (SignatureHelpParameter)p),
                       descriptionParts.ToTaggedText()));
        }
Exemple #12
0
        protected IList <TaggedText> GetAwaitableUsage(IMethodSymbol method, SemanticModel semanticModel, int position)
#pragma warning restore CA1822 // Mark members as static
        => SpecializedCollections.EmptyList <TaggedText>();
 public CodeGenerationNamespaceSymbol(string name, IList <INamespaceOrTypeSymbol> members)
     : base(null, null, Accessibility.NotApplicable, default(DeclarationModifiers), name)
 {
     _members = members ?? SpecializedCollections.EmptyList <INamespaceOrTypeSymbol>();
 }
Exemple #14
0
 public SolutionPreviewResult(IThreadingContext threadingContext, IList <SolutionPreviewItem> previews, SolutionChangeSummary changeSummary = null)
     : base(threadingContext)
 {
     _previews          = previews ?? SpecializedCollections.EmptyList <SolutionPreviewItem>();
     this.ChangeSummary = changeSummary;
 }
Exemple #15
0
        private IList <T> GetInOrderIntervals(int start, int length, TestInterval testInterval, IIntervalIntrospector <T> introspector)
        {
            List <T> result = null;

            if (root != null && GetEnd(root.MaxEndNode.Value, introspector) >= start)
            {
                int end        = start + length;
                var candidates = new Stack <Node>();

                var currentNode = root;
                while (true)
                {
                    if (currentNode != null)
                    {
                        candidates.Push(currentNode);

                        // only if left's maxVal overlaps with interval's start,
                        // we should consider left subtree
                        var left = currentNode.Left;
                        if (left != null && GetEnd(left.MaxEndNode.Value, introspector) >= start)
                        {
                            currentNode = left;
                            continue;
                        }

                        // current node has no meaning now, set it to null
                        currentNode = null;
                    }

                    if (candidates.Count == 0)
                    {
                        break;
                    }

                    currentNode = candidates.Pop();
                    if (testInterval(currentNode.Value, start, length, introspector))
                    {
                        result = result ?? new List <T>();
                        result.Add(currentNode.Value);
                    }

                    // right children's starts will never be to the left of the parent's start
                    // so we should consider right subtree
                    // only if root's start overlaps with interval's End,
                    if (introspector.GetStart(currentNode.Value) <= end)
                    {
                        var right = currentNode.Right;
                        if (right != null && GetEnd(right.MaxEndNode.Value, introspector) >= start)
                        {
                            currentNode = right;
                            continue;
                        }
                    }

                    // set to null to get new one from stack
                    currentNode = null;
                }
            }

            return(result ?? SpecializedCollections.EmptyList <T>());
        }
Exemple #16
0
 private static IList <ISymbol> GetImports(CodeGenerationNamespaceInfo info)
 {
     return(info == null
         ? SpecializedCollections.EmptyList <ISymbol>()
         : info._imports);
 }