Exemplo n.º 1
0
        public async Task TestSessionClosed()
        {
            // enable local remote host service
            var service = CreateRemoteHostClientService();

            service.Enable();

            var client = (InProcRemoteHostClient)(await service.TryGetRemoteHostClientAsync(CancellationToken.None));

            // register local service
            TestService testService = null;

            client.RegisterService("Test", (s, p) =>
            {
                testService = new TestService(s, p);
                return(testService);
            });

            // create session that stay alive until client alive (ex, SymbolSearchUpdateEngine)
            var session = await client.TryCreateKeepAliveSessionAsync("Test", CancellationToken.None);

            // mimic unfortunate call that happens to be in the middle of communication.
            var task = session.TryInvokeAsync("TestMethodAsync", SpecializedCollections.EmptyReadOnlyList <object>(), CancellationToken.None);

            // make client to go away
            service.Disable();

            // let the service to return
            testService.Event.Set();

            // make sure task finished gracefully
            await task;
        }
            private SimpleDiagnostic(
                DiagnosticDescriptor descriptor,
                DiagnosticSeverity severity,
                int warningLevel,
                Location location,
                IEnumerable <Location> additionalLocations,
                object[] messageArgs,
                ImmutableDictionary <string, string> properties)
            {
                if ((warningLevel == 0 && severity != DiagnosticSeverity.Error) ||
                    (warningLevel != 0 && severity == DiagnosticSeverity.Error))
                {
                    throw new ArgumentException(nameof(warningLevel));
                }

                if (descriptor == null)
                {
                    throw new ArgumentNullException(nameof(descriptor));
                }

                _descriptor          = descriptor;
                _severity            = severity;
                _warningLevel        = warningLevel;
                _location            = location ?? Location.None;
                _additionalLocations = additionalLocations?.ToImmutableArray() ?? SpecializedCollections.EmptyReadOnlyList <Location>();
                _messageArgs         = messageArgs ?? SpecializedCollections.EmptyArray <object>();
                _properties          = properties ?? ImmutableDictionary <string, string> .Empty;
            }
Exemplo n.º 3
0
        private void AttachToDocument(uint docCookie, string moniker)
        {
            _foregroundThreadAffinitization.AssertIsForeground();

            var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
            var textBuffer   = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);

            if (_fileTrackingMetadataAsSourceService.TryAddDocumentToWorkspace(moniker, textBuffer))
            {
                // We already added it, so we will keep it excluded from the misc files workspace
                return;
            }

            // This should always succeed since we only got here if we already confirmed the moniker is acceptable
            var languageInformation = TryGetLanguageInformation(moniker);

            Contract.ThrowIfNull(languageInformation);
            var parseOptions = languageInformation.ParseOptions;

            if (Path.GetExtension(moniker) == languageInformation.ScriptExtension)
            {
                parseOptions = parseOptions.WithKind(SourceCodeKind.Script);
            }

            // First, create the project
            var hostProject = new HostProject(this, CurrentSolution.Id, languageInformation.LanguageName, parseOptions, _metadataReferences);

            // Now try to find the document. We accept any text buffer, since we've already verified it's an appropriate file in ShouldIncludeFile.
            var document = _documentProvider.TryGetDocumentForFile(
                hostProject,
                moniker,
                parseOptions.Kind,
                getFolderNames: _ => SpecializedCollections.EmptyReadOnlyList <string>(),
                canUseTextBuffer: _ => true);

            // If the buffer has not yet been initialized, we won't get a document.
            if (document == null)
            {
                return;
            }

            // Since we have a document, we can do the rest of the project setup.
            _hostProjects.Add(hostProject.Id, hostProject);
            OnProjectAdded(hostProject.CreateProjectInfoForCurrentState());

            OnDocumentAdded(document.GetInitialState());
            hostProject.Document = document;

            // Notify the document provider, so it knows the document is now open and a part of
            // the project
            _documentProvider.NotifyDocumentRegisteredToProjectAndStartToRaiseEvents(document);

            Contract.ThrowIfFalse(document.IsOpen);

            var buffer = document.GetOpenTextBuffer();

            OnDocumentOpened(document.Id, document.GetOpenTextContainer());

            _docCookiesToHostProject.Add(docCookie, hostProject);
        }
Exemplo n.º 4
0
 internal CSDiagnosticInfo(ErrorCode code, object[] args, ImmutableArray <Symbol> symbols, ImmutableArray <Location> additionalLocations)
     : base(code, args, symbols)
 {
     // Internal errors are abnormal and should not occur except where there are bugs in the compiler.
     Debug.Assert(code != ErrorCode.ERR_InternalError);
     _additionalLocations = additionalLocations.IsDefaultOrEmpty ? SpecializedCollections.EmptyReadOnlyList <Location>() : additionalLocations;
 }
        public static SourceGeneratedDocumentState Create(
            SourceGeneratedDocumentIdentity documentIdentity,
            SourceText generatedSourceText,
            ParseOptions parseOptions,
            HostLanguageServices languageServices,
            SolutionServices solutionServices)
        {
            var textAndVersion = TextAndVersion.Create(generatedSourceText, VersionStamp.Create());
            var textSource     = new ConstantValueSource <TextAndVersion>(textAndVersion);
            var treeSource     = CreateLazyFullyParsedTree(
                textSource,
                documentIdentity.DocumentId.ProjectId,
                documentIdentity.FilePath,
                parseOptions,
                languageServices);

            return(new SourceGeneratedDocumentState(
                       documentIdentity,
                       languageServices,
                       solutionServices,
                       documentServiceProvider: null,
                       new DocumentInfo.DocumentAttributes(
                           documentIdentity.DocumentId,
                           name: documentIdentity.HintName,
                           folders: SpecializedCollections.EmptyReadOnlyList <string>(),
                           parseOptions.Kind,
                           filePath: documentIdentity.FilePath,
                           isGenerated: true,
                           designTimeOnly: false),
                       parseOptions,
                       textSource,
                       treeSource));
        }
Exemplo n.º 6
0
        protected static void AddMappedDocument(Workspace workspace, string markup)
        {
            var generatedDocumentId = DocumentId.CreateNewId(
                workspace.CurrentSolution.ProjectIds.First()
                );
            var version = VersionStamp.Create();
            var loader  = TextLoader.From(
                TextAndVersion.Create(
                    SourceText.From(markup),
                    version,
                    TestSpanMapper.GeneratedFileName
                    )
                );
            var generatedDocumentInfo = DocumentInfo.Create(
                generatedDocumentId,
                TestSpanMapper.GeneratedFileName,
                SpecializedCollections.EmptyReadOnlyList <string>(),
                SourceCodeKind.Regular,
                loader,
                $"C:\\{TestSpanMapper.GeneratedFileName}",
                isGenerated: true,
                designTimeOnly: false,
                new TestSpanMapperProvider()
                );
            var newSolution = workspace.CurrentSolution.AddDocument(generatedDocumentInfo);

            workspace.TryApplyChanges(newSolution);
        }
            internal SimpleDiagnostic(string id, string category, string message, DiagnosticSeverity severity, bool isEnabledByDefault,
                                      int warningLevel, bool isWarningAsError, Location location,
                                      IEnumerable <Location> additionalLocations, IEnumerable <string> customTags)
            {
                if (isWarningAsError && severity != DiagnosticSeverity.Warning)
                {
                    throw new ArgumentException("isWarningAsError");
                }

                if ((warningLevel == 0 && severity == DiagnosticSeverity.Warning) ||
                    (warningLevel != 0 && severity != DiagnosticSeverity.Warning))
                {
                    throw new ArgumentException("warningLevel");
                }

                this.id                  = id;
                this.category            = category;
                this.message             = message;
                this.severity            = severity;
                this.isEnabledByDefault  = isEnabledByDefault;
                this.warningLevel        = warningLevel;
                this.isWarningAsError    = isWarningAsError;
                this.location            = location;
                this.additionalLocations = additionalLocations == null?SpecializedCollections.EmptyReadOnlyList <Location>() : additionalLocations.ToImmutableArray();

                this.customTags = customTags == null?SpecializedCollections.EmptyReadOnlyList <string>() : customTags.ToImmutableArray();
            }
Exemplo n.º 8
0
            private SimpleDiagnostic(
                DiagnosticDescriptor descriptor,
                DiagnosticSeverity severity,
                int warningLevel,
                Location location,
                IEnumerable <Location> additionalLocations,
                object[] messageArgs,
                ImmutableDictionary <string, string> properties,
                bool isSuppressed)
            {
                if ((warningLevel == 0 && severity != DiagnosticSeverity.Error) ||
                    (warningLevel != 0 && severity == DiagnosticSeverity.Error))
                {
                    throw new ArgumentException($"{nameof(warningLevel)} ({warningLevel}) and {nameof(severity)} ({severity}) are not compatible.", nameof(warningLevel));
                }

                _descriptor          = descriptor ?? throw new ArgumentNullException(nameof(descriptor));
                _severity            = severity;
                _warningLevel        = warningLevel;
                _location            = location ?? Location.None;
                _additionalLocations = additionalLocations?.ToImmutableArray() ?? SpecializedCollections.EmptyReadOnlyList <Location>();
                _messageArgs         = messageArgs ?? Array.Empty <object>();
                _properties          = properties ?? ImmutableDictionary <string, string> .Empty;
                _isSuppressed        = isSuppressed;
            }
            /// <summary>
            /// Creates a <see cref="StandardTextDocument"/>.
            /// <para>Note: getFolderNames maps from a VSITEMID to the folders this document should be contained in.</para>
            /// </summary>
            public StandardTextDocument(
                DocumentProvider documentProvider,
                AbstractProject project,
                DocumentKey documentKey,
                Func <uint, IReadOnlyList <string> > getFolderNames,
                SourceCodeKind sourceCodeKind,
                IVsFileChangeEx fileChangeService,
                ITextBuffer openTextBuffer,
                DocumentId id,
                EventHandler updatedOnDiskHandler,
                EventHandler <bool> openedHandler,
                EventHandler <bool> closingHandler)
            {
                Contract.ThrowIfNull(documentProvider);

                this.Project = project;
                this.Id      = id ?? DocumentId.CreateNewId(project.Id, documentKey.Moniker);
                _itemMoniker = documentKey.Moniker;

                var itemid = this.GetItemId();

                this.Folders = itemid == (uint)VSConstants.VSITEMID.Nil
                    ? SpecializedCollections.EmptyReadOnlyList <string>()
                    : getFolderNames(itemid);

                _documentProvider = documentProvider;

                this.Key            = documentKey;
                this.SourceCodeKind = sourceCodeKind;
                _fileChangeTracker  = new FileChangeTracker(fileChangeService, this.FilePath);
                _fileChangeTracker.UpdatedOnDisk += OnUpdatedOnDisk;

                _openTextBuffer  = openTextBuffer;
                _snapshotTracker = new ReiteratedVersionSnapshotTracker(openTextBuffer);

                // The project system does not tell us the CodePage specified in the proj file, so
                // we use null to auto-detect.
                _doNotAccessDirectlyLoader = new FileTextLoader(documentKey.Moniker, defaultEncoding: null);

                // If we aren't already open in the editor, then we should create a file change notification
                if (openTextBuffer == null)
                {
                    _fileChangeTracker.StartFileChangeListeningAsync();
                }

                if (updatedOnDiskHandler != null)
                {
                    UpdatedOnDisk += updatedOnDiskHandler;
                }

                if (openedHandler != null)
                {
                    Opened += openedHandler;
                }

                if (closingHandler != null)
                {
                    Closing += closingHandler;
                }
            }
Exemplo n.º 10
0
        public static SourceGeneratedDocumentState Create(
            string hintName,
            SourceText generatedSourceText,
            SyntaxTree generatedSyntaxTree,
            DocumentId documentId,
            ISourceGenerator sourceGenerator,
            HostLanguageServices languageServices,
            SolutionServices solutionServices,
            CancellationToken cancellationToken)
        {
            var options  = generatedSyntaxTree.Options;
            var filePath = generatedSyntaxTree.FilePath;

            var textAndVersion = TextAndVersion.Create(generatedSourceText, VersionStamp.Create());
            ValueSource <TextAndVersion> textSource = new ConstantValueSource <TextAndVersion>(textAndVersion);

            var root = generatedSyntaxTree.GetRoot(cancellationToken);

            Contract.ThrowIfNull(languageServices.SyntaxTreeFactory, "We should not have a generated syntax tree for a language that doesn't support trees.");

            if (languageServices.SyntaxTreeFactory.CanCreateRecoverableTree(root))
            {
                // We will only create recoverable text if we can create a recoverable tree; if we created a
                // recoverable text but not a new tree, it would mean tree.GetText() could still potentially return
                // the non-recoverable text, but asking the document directly for it's text would give a recoverable
                // text with a different object identity.
                textSource = CreateRecoverableText(textAndVersion, solutionServices);

                generatedSyntaxTree = languageServices.SyntaxTreeFactory.CreateRecoverableTree(
                    documentId.ProjectId,
                    filePath: generatedSyntaxTree.FilePath,
                    options,
                    textSource,
                    generatedSourceText.Encoding,
                    root);
            }

            var treeAndVersion = TreeAndVersion.Create(generatedSyntaxTree, textAndVersion.Version);

            return(new SourceGeneratedDocumentState(
                       languageServices,
                       solutionServices,
                       documentServiceProvider: null,
                       new DocumentInfo.DocumentAttributes(
                           documentId,
                           name: hintName,
                           folders: SpecializedCollections.EmptyReadOnlyList <string>(),
                           options.Kind,
                           filePath: filePath,
                           isGenerated: true,
                           designTimeOnly: false),
                       options,
                       sourceText: null, // don't strongly hold the text
                       textSource,
                       treeAndVersion,
                       sourceGenerator,
                       hintName));
        }
Exemplo n.º 11
0
        private bool TryCreateXamlDocument(AbstractProject project, string filePath, out IVisualStudioHostDocument vsDocument)
        {
            vsDocument = _vsWorkspace.ProjectTracker.DocumentProvider.TryGetDocumentForFile(
                project, filePath, SourceCodeKind.Regular,
                tb => tb.ContentType.IsOfType(ContentTypeNames.XamlContentType),
                _ => SpecializedCollections.EmptyReadOnlyList <string>());

            return(vsDocument != null);
        }
 public IReadOnlyList <SyntaxNode> GetNodes(SyntaxAnnotation id)
 {
     if (_idToNodeMap.TryGetValue(id, out var nodes))
     {
         return(nodes);
     }
     else
     {
         return(SpecializedCollections.EmptyReadOnlyList <SyntaxNode>());
     }
 }
                internal CSharpCompilerInputs(CSharpProjectFile projectFile)
                {
                    _projectFile            = projectFile;
                    this.Options            = new HostBuildOptions();
                    this.Sources            = SpecializedCollections.EmptyEnumerable <MSB.Framework.ITaskItem>();
                    this.References         = SpecializedCollections.EmptyEnumerable <MSB.Framework.ITaskItem>();
                    this.AnalyzerReferences = SpecializedCollections.EmptyEnumerable <MSB.Framework.ITaskItem>();
                    this.AdditionalFiles    = SpecializedCollections.EmptyEnumerable <MSB.Framework.ITaskItem>();
                    this.LibPaths           = SpecializedCollections.EmptyReadOnlyList <string>();

                    this.Options.ProjectDirectory = Path.GetDirectoryName(projectFile.FilePath);
                    this.Options.OutputDirectory  = projectFile.GetOutputDirectory();
                }
Exemplo n.º 14
0
        private static IReadOnlyList <SyntaxNode> GetCurrentNodeFromTrueRoots(SyntaxNode trueRoot, SyntaxNode node)
        {
            var id = GetId(node);

            if (id != null)
            {
                CurrentNodes tracked = s_rootToCurrentNodesMap.GetValue(trueRoot, r => new CurrentNodes(r));
                return(tracked.GetNodes(id));
            }
            else
            {
                return(SpecializedCollections.EmptyReadOnlyList <SyntaxNode>());
            }
        }
Exemplo n.º 15
0
        public IFormattingResult GetFormattingResult(SyntaxNode node, IEnumerable <TextSpan>?spans, SyntaxFormattingOptions options, IEnumerable <AbstractFormattingRule>?rules, CancellationToken cancellationToken)
        {
            IReadOnlyList <TextSpan> spansToFormat;

            if (spans == null)
            {
                spansToFormat = node.FullSpan.IsEmpty ?
                                SpecializedCollections.EmptyReadOnlyList <TextSpan>() :
                                SpecializedCollections.SingletonReadOnlyList(node.FullSpan);
            }
            else
            {
                spansToFormat = new NormalizedTextSpanCollection(spans.Where(s_notEmpty));
            }

            if (spansToFormat.Count == 0)
            {
                return(CreateAggregatedFormattingResult(node, SpecializedCollections.EmptyList <AbstractFormattingResult>()));
            }

            rules ??= GetDefaultFormattingRules();

            List <AbstractFormattingResult>?results = null;

            foreach (var(startToken, endToken) in node.ConvertToTokenPairs(spansToFormat))
            {
                if (node.IsInvalidTokenRange(startToken, endToken))
                {
                    continue;
                }

                results ??= new List <AbstractFormattingResult>();
                results.Add(Format(node, options, rules, startToken, endToken, cancellationToken));
            }

            // quick simple case check
            if (results == null)
            {
                return(CreateAggregatedFormattingResult(node, SpecializedCollections.EmptyList <AbstractFormattingResult>()));
            }

            if (results.Count == 1)
            {
                return(results[0]);
            }

            // more expensive case
            return(CreateAggregatedFormattingResult(node, results));
        }
Exemplo n.º 16
0
        private static IReadOnlyList <string> GetCustomTags(ObjectReader reader, int count)
        {
            if (count > 0)
            {
                var tags = new List <string>(count);
                for (var i = 0; i < count; i++)
                {
                    tags.Add(reader.ReadString());
                }

                return(new ReadOnlyCollection <string>(tags));
            }

            return(SpecializedCollections.EmptyReadOnlyList <string>());
        }
Exemplo n.º 17
0
        public IReadOnlyList <string> GetFolderNames(uint documentItemID)
        {
            object parentObj;

            if (documentItemID != (uint)VSConstants.VSITEMID.Nil && Hierarchy.GetProperty(documentItemID, (int)VsHierarchyPropID.Parent, out parentObj) == VSConstants.S_OK)
            {
                var parentID = UnboxVSItemId(parentObj);
                if (parentID != (uint)VSConstants.VSITEMID.Nil && parentID != (uint)VSConstants.VSITEMID.Root)
                {
                    return(GetFolderNamesForFolder(parentID));
                }
            }

            return(SpecializedCollections.EmptyReadOnlyList <string>());
        }
Exemplo n.º 18
0
        public void AddAdditionalFile(string additionalFilePath, Func <IVisualStudioHostDocument, bool> getIsInCurrentContext)
        {
            var document = this.DocumentProvider.TryGetDocumentForFile(
                this,
                filePath: additionalFilePath,
                sourceCodeKind: SourceCodeKind.Regular,
                getFolderNames: _ => SpecializedCollections.EmptyReadOnlyList <string>(),
                canUseTextBuffer: _ => true,
                updatedOnDiskHandler: s_additionalDocumentUpdatedOnDiskEventHandler,
                openedHandler: s_additionalDocumentOpenedEventHandler,
                closingHandler: s_additionalDocumentClosingEventHandler);

            if (document == null)
            {
                return;
            }

            AddAdditionalDocument(document, isCurrentContext: getIsInCurrentContext(document));
        }
                internal CSharpCompilerInputs(CSharpProjectFile projectFile)
                {
                    this.projectFile = projectFile;
                    var projectDirectory = Path.GetDirectoryName(projectFile.FilePath);
                    var outputDirectory  = projectFile.GetOutputDirectory();

                    this.ParseOptions       = defaultParseOptions;
                    this.CompilationOptions = new CSharpCompilationOptions(
                        OutputKind.ConsoleApplication,
                        xmlReferenceResolver: new XmlFileResolver(projectDirectory),
                        sourceReferenceResolver: new SourceFileResolver(ImmutableArray <string> .Empty, projectDirectory),
                        metadataReferenceResolver: new MetadataFileReferenceResolver(ImmutableArray <string> .Empty, projectDirectory),
                        metadataReferenceProvider: MetadataFileReferenceProvider.Default,
                        strongNameProvider: new DesktopStrongNameProvider(ImmutableArray.Create(projectDirectory, outputDirectory)),
                        assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default);
                    this.Warnings           = new Dictionary <string, ReportDiagnostic>();
                    this.Sources            = SpecializedCollections.EmptyEnumerable <MSB.Framework.ITaskItem>();
                    this.References         = SpecializedCollections.EmptyEnumerable <MSB.Framework.ITaskItem>();
                    this.AnalyzerReferences = SpecializedCollections.EmptyEnumerable <MSB.Framework.ITaskItem>();
                    this.AdditionalFiles    = SpecializedCollections.EmptyEnumerable <MSB.Framework.ITaskItem>();
                    this.LibPaths           = SpecializedCollections.EmptyReadOnlyList <string>();
                }
Exemplo n.º 20
0
            private SimpleDiagnostic(
                DiagnosticDescriptor descriptor,
                DiagnosticSeverity severity,
                int warningLevel,
                Location location,
                IEnumerable <Location> additionalLocations,
                object[] messageArgs)
            {
                if ((warningLevel == 0 && severity != DiagnosticSeverity.Error) ||
                    (warningLevel != 0 && severity == DiagnosticSeverity.Error))
                {
                    throw new ArgumentException("warningLevel");
                }

                _descriptor          = descriptor;
                _severity            = severity;
                _warningLevel        = warningLevel;
                _location            = location;
                _additionalLocations = additionalLocations == null?SpecializedCollections.EmptyReadOnlyList <Location>() : additionalLocations.ToImmutableArray();

                _messageArgs = messageArgs ?? SpecializedCollections.EmptyArray <object>();
            }
        private async Task <IReadOnlyList <Reference> > FindResultsAsync(
            Document document, SemanticModel semanticModel, Diagnostic diagnostic, SyntaxNode node, CancellationToken cancellationToken)
        {
            // Caches so we don't produce the same data multiple times while searching
            // all over the solution.
            var project                = document.Project;
            var projectToAssembly      = new ConcurrentDictionary <Project, AsyncLazy <IAssemblySymbol> >(concurrencyLevel: 2, capacity: project.Solution.ProjectIds.Count);
            var referenceToCompilation = new ConcurrentDictionary <PortableExecutableReference, Compilation>(concurrencyLevel: 2, capacity: project.Solution.Projects.Sum(p => p.MetadataReferences.Count));

            var finder = new SymbolReferenceFinder(this, document, semanticModel, diagnostic, node, cancellationToken);

            // Look for exact matches first:
            var exactReferences = await FindResultsAsync(projectToAssembly, referenceToCompilation, project, finder, exact : true, cancellationToken : cancellationToken).ConfigureAwait(false);

            if (exactReferences?.Count > 0)
            {
                return(exactReferences);
            }

            // No exact matches found.  Fall back to fuzzy searching.
            // Only bother doing this for host workspaces.  We don't want this for
            // things like the Interactive workspace as this will cause us to
            // create expensive bktrees which we won't even be able to save for
            // future use.
            if (!IsHostOrTestWorkspace(project))
            {
                return(SpecializedCollections.EmptyReadOnlyList <Reference>());
            }

            var fuzzyReferences = await FindResultsAsync(projectToAssembly, referenceToCompilation, project, finder, exact : false, cancellationToken : cancellationToken).ConfigureAwait(false);

            if (fuzzyReferences?.Count > 0)
            {
                return(fuzzyReferences);
            }

            return(null);
        }
Exemplo n.º 22
0
 public IEnumerable <IMethodDefinition> GetMethods(EmitContext context)
 {
     return(_methods ??= SpecializedCollections.EmptyReadOnlyList <IMethodDefinition>());
 }
Exemplo n.º 23
0
        private void AttachToDocument(uint docCookie, string moniker)
        {
            _foregroundThreadAffinitization.AssertIsForeground();

            var vsTextBuffer = (IVsTextBuffer)_runningDocumentTable.GetDocumentData(docCookie);
            var textBuffer   = _editorAdaptersFactoryService.GetDocumentBuffer(vsTextBuffer);

            if (_fileTrackingMetadataAsSourceService.TryAddDocumentToWorkspace(moniker, textBuffer))
            {
                // We already added it, so we will keep it excluded from the misc files workspace
                return;
            }

            // This should always succeed since we only got here if we already confirmed the moniker is acceptable
            var languageInformation = TryGetLanguageInformation(moniker);

            Contract.ThrowIfNull(languageInformation);

            var languageServices      = Services.GetLanguageServices(languageInformation.LanguageName);
            var compilationOptionsOpt = languageServices.GetService <ICompilationFactoryService>()?.GetDefaultCompilationOptions();
            var parseOptionsOpt       = languageServices.GetService <ISyntaxTreeFactoryService>()?.GetDefaultParseOptions();

            if (parseOptionsOpt != null &&
                compilationOptionsOpt != null &&
                PathUtilities.GetExtension(moniker) == languageInformation.ScriptExtension)
            {
                parseOptionsOpt = parseOptionsOpt.WithKind(SourceCodeKind.Script);

                var metadataService = Services.GetService <IMetadataService>();
                var directory       = PathUtilities.GetDirectoryName(moniker);

                // TODO (https://github.com/dotnet/roslyn/issues/5325, https://github.com/dotnet/roslyn/issues/13886):
                // - Need to have a way to specify these somewhere in VS options.
                // - Use RuntimeMetadataReferenceResolver like in InteractiveEvaluator.CreateMetadataReferenceResolver
                // - Add default namespace imports
                // - Add default script globals available in 'csi goo.csx' environment: CommandLineScriptGlobals

                var referenceSearchPaths = ImmutableArray <string> .Empty;
                var sourceSearchPaths    = ImmutableArray <string> .Empty;

                var referenceResolver = new WorkspaceMetadataFileReferenceResolver(
                    metadataService,
                    new RelativePathResolver(referenceSearchPaths, directory));

                compilationOptionsOpt = compilationOptionsOpt.
                                        WithMetadataReferenceResolver(referenceResolver).
                                        WithSourceReferenceResolver(new SourceFileResolver(sourceSearchPaths, directory));
            }

            // First, create the project
            var hostProject = new HostProject(this, CurrentSolution.Id, languageInformation.LanguageName, parseOptionsOpt, compilationOptionsOpt, _metadataReferences);

            // Now try to find the document. We accept any text buffer, since we've already verified it's an appropriate file in ShouldIncludeFile.
            var document = _documentProvider.TryGetDocumentForFile(
                hostProject,
                moniker,
                parseOptionsOpt?.Kind ?? SourceCodeKind.Regular,
                getFolderNames: _ => SpecializedCollections.EmptyReadOnlyList <string>(),
                canUseTextBuffer: _ => true);

            // If the buffer has not yet been initialized, we won't get a document.
            if (document == null)
            {
                return;
            }

            // Since we have a document, we can do the rest of the project setup.
            _hostProjects.Add(hostProject.Id, hostProject);
            OnProjectAdded(hostProject.CreateProjectInfoForCurrentState());

            OnDocumentAdded(document.GetInitialState());
            hostProject.Document = document;

            // Notify the document provider, so it knows the document is now open and a part of
            // the project
            _documentProvider.NotifyDocumentRegisteredToProjectAndStartToRaiseEvents(document);

            Contract.ThrowIfFalse(document.IsOpen);

            var buffer = document.GetOpenTextBuffer();

            OnDocumentOpened(document.Id, document.GetOpenTextContainer());

            _docCookiesToHostProject.Add(docCookie, hostProject);
        }
Exemplo n.º 24
0
 protected Task <TResult> InvokeAsync <TResult>(string targetName, CancellationToken cancellationToken)
 {
     return(InvokeAsync <TResult>(targetName, SpecializedCollections.EmptyReadOnlyList <object>(), cancellationToken));
 }
Exemplo n.º 25
0
 public IReadOnlyList <string> GetFolderNames(uint documentItemID)
 {
     return(SpecializedCollections.EmptyReadOnlyList <string>());
 }
Exemplo n.º 26
0
 public IReadOnlyList <Span> GetAdditionalInformationMatchRuns(string searchValue)
 => SpecializedCollections.EmptyReadOnlyList <Span>();