public bool TryGetSerializationPrefixAndVersion(Solution solution, string assemblyFilePath, out string prefix, out VersionStamp version)
        {
            prefix = string.Empty;
            version = VersionStamp.Default;

            return false;
        }
Beispiel #2
0
        public static bool CanReusePersistedTextVersion(this Document document, VersionStamp textVersion, VersionStamp persistedVersion)
        {
            var canReuse = VersionStamp.CanReusePersistedVersion(textVersion, persistedVersion);

            PersistedVersionStampLogger.LogPersistedTextVersionUsage(canReuse);
            return canReuse;
        }
Beispiel #3
0
        private Solution(
            BranchId branchId,
            int workspaceVersion,
            SolutionServices solutionServices,
            SolutionId id,
            string filePath,
            ImmutableList<ProjectId> projectIds,
            ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap,
            ImmutableDictionary<ProjectId, CompilationTracker> projectIdToTrackerMap,
            ProjectDependencyGraph dependencyGraph,
            VersionStamp version,
            Lazy<VersionStamp> lazyLatestProjectVersion)
        {
            this.branchId = branchId;
            this.workspaceVersion = workspaceVersion;
            this.id = id;
            this.filePath = filePath;
            this.solutionServices = solutionServices;
            this.projectIds = projectIds;
            this.projectIdToProjectStateMap = idToProjectStateMap;
            this.projectIdToTrackerMap = projectIdToTrackerMap;
            this.dependencyGraph = dependencyGraph;
            this.projectIdToProjectMap = ImmutableHashMap<ProjectId, Project>.Empty;
            this.version = version;
            this.lazyLatestProjectVersion = lazyLatestProjectVersion;

            CheckInvariants();
        }
        public bool TryGetSerializationPrefixAndVersion(Solution solution, string assemblyFilePath, out string prefix, out VersionStamp version)
        {
            prefix = FilePathUtilities.GetRelativePath(solution.FilePath, assemblyFilePath);
            version = VersionStamp.Create(File.GetLastWriteTimeUtc(assemblyFilePath));

            return true;
        }
Beispiel #5
0
        public static bool CanReusePersistedDependentProjectVersion(this Project project, VersionStamp dependentProjectVersion, VersionStamp persistedVersion)
        {
            var canReuse = VersionStamp.CanReusePersistedVersion(dependentProjectVersion, persistedVersion);

            PersistedVersionStampLogger.LogPersistedDependentProjectVersionUsage(canReuse);
            return canReuse;
        }
 private SyntaxTreeContextInfo(VersionStamp version, int predefinedTypes, int predefinedOperators, ContainingNodes containingNodes) :
     base(version)
 {
     _predefinedTypes = predefinedTypes;
     _predefinedOperators = predefinedOperators;
     _containingNodes = containingNodes;
 }
        internal static bool TryGetReference(
            Solution solution, ProjectReference projectReference, Compilation finalOrDeclarationCompilation, VersionStamp version, out MetadataReference reference)
        {
            // if we have one from snapshot cache, use it. it will make sure same compilation will get same metadata reference always.
            MetadataOnlyReferenceSet referenceSet;
            if (s_snapshotCache.TryGetValue(finalOrDeclarationCompilation, out referenceSet))
            {
                reference = referenceSet.GetMetadataReference(finalOrDeclarationCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes);
                return true;
            }

            // okay, now use version based cache that can live multiple compilation as long as there is no semantic changes.

            // get one for the branch
            if (TryGetReferenceFromBranch(solution.BranchId, projectReference, finalOrDeclarationCompilation, version, out reference))
            {
                return true;
            }

            // see whether we can use primary branch one
            var primaryBranchId = solution.Workspace.PrimaryBranchId;
            if (solution.BranchId != primaryBranchId &&
                TryGetReferenceFromBranch(primaryBranchId, projectReference, finalOrDeclarationCompilation, version, out reference))
            {
                return true;
            }

            // noop, we don't have any
            reference = null;
            return false;
        }
Beispiel #8
0
        private SolutionState(
            BranchId branchId,
            int workspaceVersion,
            SolutionServices solutionServices,
            SolutionId id,
            string filePath,
            IEnumerable<ProjectId> projectIds,
            ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap,
            ImmutableDictionary<ProjectId, CompilationTracker> projectIdToTrackerMap,
            ImmutableDictionary<string, ImmutableArray<DocumentId>> linkedFilesMap,
            ProjectDependencyGraph dependencyGraph,
            VersionStamp version,
            Lazy<VersionStamp> lazyLatestProjectVersion)
        {
            _branchId = branchId;
            _workspaceVersion = workspaceVersion;
            _id = id;
            _filePath = filePath;
            _solutionServices = solutionServices;
            _projectIds = projectIds.ToImmutableReadOnlyListOrEmpty();
            _projectIdToProjectStateMap = idToProjectStateMap;
            _projectIdToTrackerMap = projectIdToTrackerMap;
            _linkedFilesMap = linkedFilesMap;
            _dependencyGraph = dependencyGraph;
            _version = version;
            _lazyLatestProjectVersion = lazyLatestProjectVersion;

            CheckInvariants();
        }
Beispiel #9
0
        public static bool CanReusePersistedSyntaxTreeVersion(this Document document, VersionStamp syntaxVersion, VersionStamp persistedVersion)
        {
            var canReuse = VersionStamp.CanReusePersistedVersion(syntaxVersion, persistedVersion);

            PersistedVersionStampLogger.LogPersistedSyntaxTreeVersionUsage(canReuse);
            return canReuse;
        }
        private static bool ShouldCreateFromScratch(
            Solution solution,
            IAssemblySymbol assembly,
            string filePath,
            out string prefix,
            out VersionStamp version,
            CancellationToken cancellationToken)
        {
            prefix = null;
            version = default(VersionStamp);

            var service = solution.Workspace.Services.GetService<IAssemblySerializationInfoService>();
            if (service == null)
            {
                return true;
            }

            // check whether the assembly that belong to a solution is something we can serialize
            if (!service.Serializable(solution, filePath))
            {
                return true;
            }

            if (!service.TryGetSerializationPrefixAndVersion(solution, filePath, out prefix, out version))
            {
                return true;
            }

            return false;
        }
Beispiel #11
0
        public NavigationBarModel(IList<NavigationBarItem> types, VersionStamp semanticVersionStamp, INavigationBarItemService itemService)
        {
            Contract.ThrowIfNull(types);

            this.Types = types;
            this.SemanticVersionStamp = semanticVersionStamp;
            this.ItemService = itemService;
        }
Beispiel #12
0
 private SymbolTreeInfo(VersionStamp version, IReadOnlyList<Node> orderedNodes, SpellChecker spellChecker)
     : this(version, orderedNodes, new Lazy<SpellChecker>(() => spellChecker))
 {
     // Make the lazy 'Created'.  This is a no-op since we already have the underlying spell
     // checker.  This way if we end up wanting to serialize this tree info, we'll also
     // serialize the spell checker.
     var unused = _lazySpellChecker.Value;
 }
Beispiel #13
0
 /// <summary>
 /// Create a new instance of a SolutionInfo.
 /// </summary>
 public static SolutionInfo Create(
     SolutionId id,
     VersionStamp version,
     string filePath = null,
     IEnumerable<ProjectInfo> projects = null)
 {
     return new SolutionInfo(new SolutionAttributes(id, version, filePath), projects);
 }
            public ProjectAnalysisData(ProjectId projectId, VersionStamp version, ImmutableDictionary<DiagnosticAnalyzer, AnalysisResult> result)
            {
                ProjectId = projectId;
                Version = version;
                Result = result;

                OldResult = null;
            }
Beispiel #15
0
        /// <summary>
        /// Create a new TextAndVersion instance.
        /// </summary>
        /// <param name="text">The text</param>
        /// <param name="version">The version</param>
        /// <param name="filePath">An optional file path that identifies the original of the source text.</param>
        /// <returns></returns>
        public static TextAndVersion Create(SourceText text, VersionStamp version, string filePath = null)
        {
            if (text == null)
            {
                throw new ArgumentNullException("text");
            }

            return new TextAndVersion(text, version, filePath);
        }
Beispiel #16
0
        /// <summary>
        /// Creates a TextLoader from a SourceTextContainer and version. 
        /// 
        /// The text obtained from the loader will be the current text of the container at the time
        /// the loader is accessed.
        /// </summary>
        public static TextLoader From(SourceTextContainer container, VersionStamp version, string filePath = null)
        {
            if (container == null)
            {
                throw new ArgumentNullException("container");
            }

            return new TextContainerLoader(container, version, filePath);
        }
Beispiel #17
0
        public static TreeAndVersion Create(SyntaxTree tree, VersionStamp version)
        {
            if (tree == null)
            {
                throw new ArgumentNullException("tree");
            }

            return new TreeAndVersion(tree, version);
        }
Beispiel #18
0
        public static bool CanReusePersistedDependentSemanticVersion(
            this Project project, VersionStamp dependentProjectVersion, VersionStamp dependentSemanticVersion, VersionStamp persistedVersion)
        {
            var canReuse = CanReusePersistedSemanticVersionInternal(
                project, dependentProjectVersion, dependentSemanticVersion, persistedVersion, (s, p, v) => s.GetInitialDependentProjectVersionFromDependentSemanticVersion(p, v));

            PersistedVersionStampLogger.LogPersistedDependentSemanticVersionUsage(canReuse);
            return canReuse;
        }
        internal static MetadataReference GetOrBuildReference(
            Solution solution,
            ProjectReference projectReference,
            Compilation finalCompilation,
            VersionStamp version,
            CancellationToken cancellationToken)
        {
            MetadataReference reference;
            if (TryGetReference(solution, projectReference, finalCompilation, version, out reference))
            {
                return reference;
            }

            // okay, we don't have one. so create one now.

            // first, prepare image
            // * NOTE * image is cancellable, do not create it inside of conditional weak table.
            var service = solution.Workspace.Services.GetService<ITemporaryStorageService>();
            var image = MetadataOnlyImage.Create(service, finalCompilation, cancellationToken);
            if (image.IsEmpty)
            {
                // unfortunately, we couldn't create one. do best effort
                if (TryGetReference(solution, projectReference, finalCompilation, VersionStamp.Default, out reference))
                {
                    // we have one from previous compilation!!, it might be out-of-date big time, but better than nothing.
                    // re-use it
                    return reference;
                }
            }

            // okay, proceed with whatever image we have

            // now, remove existing set
            var mapFromBranch = s_cache.GetValue(solution.BranchId, s_createReferenceSetMap);
            mapFromBranch.Remove(projectReference.ProjectId);

            // create new one
            var newReferenceSet = new MetadataOnlyReferenceSet(version, image);
            var referenceSet = s_snapshotCache.GetValue(finalCompilation, _ => newReferenceSet);
            if (newReferenceSet != referenceSet)
            {
                // someone else has beaten us. 
                // let image go eagerly. otherwise, finalizer in temporary storage will take care of it
                image.Cleanup();

                // return new reference
                return referenceSet.GetMetadataReference(finalCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes);
            }

            // record it to version based cache as well. snapshot cache always has a higher priority. we don't need to check returned set here
            // since snapshot based cache will take care of same compilation for us.
            mapFromBranch.GetValue(projectReference.ProjectId, _ => referenceSet);

            // return new reference
            return referenceSet.GetMetadataReference(finalCompilation, projectReference.Aliases, projectReference.EmbedInteropTypes);
        }
Beispiel #20
0
        public void Touch(DiagnosticAnalyzer analyzer, Document document, VersionStamp version)
        {
            // only touch and updateMemberRange methods are allowed to update the dictionaries
            var data = _map.GetOrAdd(document.Id, s_createMap);

            lock (data)
            {
                Touch_NoLock(data, analyzer, document, version);
            }
        }
 public SyntaxTreeIdentifierInfo(
     VersionStamp version,
     BloomFilter identifierFilter,
     BloomFilter escapedIdentifierFilter) :
     base(version)
 {
     _version = version;
     _identifierFilter = identifierFilter ?? throw new ArgumentNullException(nameof(identifierFilter));
     _escapedIdentifierFilter = escapedIdentifierFilter ?? throw new ArgumentNullException(nameof(escapedIdentifierFilter));
 }
Beispiel #22
0
        public void Touch(ProviderId providerId, Document document, VersionStamp version)
        {
            // only touch and updateMemberRange methods are allowed to update the dictionaries
            var data = _map.GetOrAdd(document.Id, s_createMap);

            lock (data)
            {
                Touch_NoLock(data, providerId, document, version);
            }
        }
 public ProjectChecksumObjectInfo(ProjectId id, VersionStamp version, string name, string assemblyName, string language, string filePath, string outputFilePath)
 {
     Id = id;
     Version = version;
     Name = name;
     AssemblyName = assemblyName;
     Language = language;
     FilePath = filePath;
     OutputFilePath = outputFilePath;
 }
        private ProjectInfo(
            ProjectId id,
            VersionStamp version,
            string name,
            string assemblyName,
            string language,
            string filePath,
            string outputFilePath,
//            CompilationOptions compilationOptions,
//            ParseOptions parseOptions,
//            IEnumerable<DocumentInfo> documents,
            IEnumerable<ProjectReference> projectReferences,
//            IEnumerable<MetadataReference> metadataReferences,
//            IEnumerable<AnalyzerReference> analyzerReferences,
//            IEnumerable<DocumentInfo> additionalDocuments,
            bool isSubmission,
            Type hostObjectType)
        {
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }

            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            if (assemblyName == null)
            {
                throw new ArgumentNullException("assemblyName");
            }

            if (language == null)
            {
                throw new ArgumentNullException("language");
            }

            this.Id = id;
            this.Version = version;
            this.Name = name;
            this.AssemblyName = assemblyName;
            this.Language = language;
            this.FilePath = filePath;
            this.OutputFilePath = outputFilePath;
            //            this.CompilationOptions = compilationOptions;
            //            this.ParseOptions = parseOptions;
            //            this.Documents = documents.ToImmutableReadOnlyListOrEmpty();
            this.ProjectReferences = (projectReferences != null) ? projectReferences.ToList() : new List<ProjectReference>();
            //            this.MetadataReferences = metadataReferences.ToImmutableReadOnlyListOrEmpty();
            //            this.AnalyzerReferences = analyzerReferences.ToImmutableReadOnlyListOrEmpty();
            //            this.AdditionalDocuments = additionalDocuments.ToImmutableReadOnlyListOrEmpty();
            this.IsSubmission = isSubmission;
            this.HostObjectType = hostObjectType;
        }
            public Builder(Project project, VersionStamp version)
            {
                _project = project;
                _version = version;

                _lazySet = null;
                _lazySyntaxLocals = null;
                _lazySemanticLocals = null;
                _lazyNonLocals = null;
                _lazyOthers = null;
            }
        private static bool TryReadVersion(ObjectReader reader, string formatVersion, out VersionStamp version)
        {
            version = VersionStamp.Default;
            if (reader.ReadString() != formatVersion)
            {
                return false;
            }

            version = VersionStamp.ReadFrom(reader);
            return true;
        }
Beispiel #27
0
        public TestHostSolution(params TestHostProject[] projects)
        {
            this.Id = SolutionId.CreateNewId();
            this.Version = VersionStamp.Create();
            this.Projects = projects;

            foreach (var project in projects)
            {
                project.SetSolution(this);
            }
        }
Beispiel #28
0
 private SymbolTreeInfo(
     VersionStamp version,
     string concatenatedNames,
     Node[] sortedNodes,
     Task<SpellChecker> spellCheckerTask,
     OrderPreservingMultiDictionary<string, string> inheritanceMap)
     : this(version, concatenatedNames, sortedNodes, spellCheckerTask)
 {
     var indexBasedInheritanceMap = CreateIndexBasedInheritanceMap(inheritanceMap);
     _inheritanceMap = indexBasedInheritanceMap;
 }
Beispiel #29
0
 private SyntaxTreeIndex(
     VersionStamp version,
     IdentifierInfo identifierInfo,
     ContextInfo contextInfo,
     DeclarationInfo declarationInfo)
 {
     Version = version;
     _identifierInfo = identifierInfo;
     _contextInfo = contextInfo;
     _declarationInfo = declarationInfo;
 }
Beispiel #30
0
 private SolutionInfo(
     SolutionId id,
     VersionStamp version,
     string filePath,
     IEnumerable<ProjectInfo> projects)
 {
     this.Id = id;
     this.Version = version;
     this.FilePath = filePath;
     this.Projects = projects.ToImmutableReadOnlyListOrEmpty();
 }
Beispiel #31
0
 private SymbolTreeInfo(VersionStamp version, IReadOnlyList <Node> orderedNodes)
 {
     _version = version;
     _nodes   = orderedNodes;
 }
Beispiel #32
0
        private void UpdateProject(ProjectFileInfo projectFileInfo)
        {
            var project = _workspace.CurrentSolution.GetProject(projectFileInfo.WorkspaceId);

            var unusedDocuments = project.Documents.ToDictionary(d => d.FilePath, d => d.Id);

            foreach (var file in projectFileInfo.SourceFiles)
            {
                if (unusedDocuments.Remove(file))
                {
                    continue;
                }

                using (var stream = File.OpenRead(file))
                {
                    var sourceText = SourceText.From(stream, encoding: Encoding.UTF8);
                    var id         = DocumentId.CreateNewId(projectFileInfo.WorkspaceId);
                    var version    = VersionStamp.Create();

                    var loader = TextLoader.From(TextAndVersion.Create(sourceText, version));

                    _workspace.AddDocument(DocumentInfo.Create(id, file, filePath: file, loader: loader));
                }
            }

            if (projectFileInfo.SpecifiedLanguageVersion.HasValue)
            {
                var parseOptions = new CSharpParseOptions(projectFileInfo.SpecifiedLanguageVersion.Value);
                _workspace.SetParseOptions(project.Id, parseOptions);
            }

            foreach (var unused in unusedDocuments)
            {
                _workspace.RemoveDocument(unused.Value);
            }

            var unusedProjectReferences = new HashSet <ProjectReference>(project.ProjectReferences);

            foreach (var projectReferencePath in projectFileInfo.ProjectReferences)
            {
                ProjectFileInfo projectReferenceInfo;
                if (_context.Projects.TryGetValue(projectReferencePath, out projectReferenceInfo))
                {
                    var reference = new ProjectReference(projectReferenceInfo.WorkspaceId);

                    if (unusedProjectReferences.Remove(reference))
                    {
                        // This reference already exists
                        continue;
                    }

                    _workspace.AddProjectReference(project.Id, reference);
                }
                else
                {
                    _logger.WriteWarning($"Unable to resolve project reference '{projectReferencePath}' for '{projectFileInfo}'.");
                }
            }

            foreach (var unused in unusedProjectReferences)
            {
                _workspace.RemoveProjectReference(project.Id, unused);
            }

            var unusedAnalyzers = new Dictionary <string, AnalyzerReference>(project.AnalyzerReferences.ToDictionary(a => a.FullPath));

            foreach (var analyzerPath in projectFileInfo.Analyzers)
            {
                if (!File.Exists(analyzerPath))
                {
                    _logger.WriteWarning($"Unable to resolve assembly '{analyzerPath}'");
                }
                else
                {
                    if (unusedAnalyzers.Remove(analyzerPath))
                    {
                        continue;
                    }
#if ASPNET50
                    var analyzerReference = new AnalyzerFileReference(analyzerPath);
                    project.AddAnalyzerReference(analyzerReference);
#endif
                }
            }

            foreach (var analyzerReference in unusedAnalyzers.Values)
            {
                project.RemoveAnalyzerReference(analyzerReference);
            }

            var unusedReferences = new HashSet <MetadataReference>(project.MetadataReferences);

            foreach (var referencePath in projectFileInfo.References)
            {
                if (!File.Exists(referencePath))
                {
                    _logger.WriteWarning($"Unable to resolve assembly '{referencePath}'");
                }
                else
                {
                    var metadataReference = _metadataReferenceCache.GetMetadataReference(referencePath);

                    if (unusedReferences.Remove(metadataReference))
                    {
                        continue;
                    }

                    _logger.WriteVerbose($"Adding reference '{referencePath}' to '{projectFileInfo.ProjectFilePath}'.");
                    _workspace.AddMetadataReference(project.Id, metadataReference);
                }
            }

            foreach (var reference in unusedReferences)
            {
                _workspace.RemoveMetadataReference(project.Id, reference);
            }
        }
        private async Task <ProjectId> LoadProjectAsync(string projectFilePath, IProjectFileLoader loader, bool preferMetadata, LoadState loadedProjects, CancellationToken cancellationToken)
        {
            Debug.Assert(projectFilePath != null);
            Debug.Assert(loader != null);

            var projectId = loadedProjects.GetOrCreateProjectId(projectFilePath);

            var projectName = Path.GetFileNameWithoutExtension(projectFilePath);

            var projectFile = await loader.LoadProjectFileAsync(projectFilePath, _properties, cancellationToken).ConfigureAwait(false);

            var projectFileInfo = await projectFile.GetProjectFileInfoAsync(cancellationToken).ConfigureAwait(false);

            var projectDirectory = Path.GetDirectoryName(projectFilePath);
            var outputFilePath   = projectFileInfo.OutputFilePath;
            var outputDirectory  = Path.GetDirectoryName(outputFilePath);

            VersionStamp version;

            if (!string.IsNullOrEmpty(projectFilePath) && File.Exists(projectFilePath))
            {
                version = VersionStamp.Create(File.GetLastWriteTimeUtc(projectFilePath));
            }
            else
            {
                version = VersionStamp.Create();
            }

            // translate information from command line args
            var commandLineParser = _workspace.Services.GetLanguageServices(loader.Language).GetService <ICommandLineParserService>();
            var metadataService   = _workspace.Services.GetService <IMetadataService>();
            var analyzerService   = _workspace.Services.GetService <IAnalyzerService>();

            var commandLineArgs = commandLineParser.Parse(
                arguments: projectFileInfo.CommandLineArgs,
                baseDirectory: projectDirectory,
                isInteractive: false,
                sdkDirectory: RuntimeEnvironment.GetRuntimeDirectory());

            var resolver           = new RelativePathReferenceResolver(commandLineArgs.ReferencePaths, commandLineArgs.BaseDirectory);
            var metadataReferences = commandLineArgs.ResolveMetadataReferences(new AssemblyReferenceResolver(resolver, metadataService.GetProvider()));

            var analyzerLoader = analyzerService.GetLoader();

            foreach (var path in commandLineArgs.AnalyzerReferences.Select(r => r.FilePath))
            {
                analyzerLoader.AddDependencyLocation(path);
            }

            var analyzerReferences = commandLineArgs.ResolveAnalyzerReferences(analyzerLoader);

            var defaultEncoding = commandLineArgs.Encoding;

            // docs & additional docs
            var docFileInfos           = projectFileInfo.Documents.ToImmutableArrayOrEmpty();
            var additionalDocFileInfos = projectFileInfo.AdditionalDocuments.ToImmutableArrayOrEmpty();

            // check for duplicate documents
            var allDocFileInfos = docFileInfos.AddRange(additionalDocFileInfos);

            CheckDocuments(allDocFileInfos, projectFilePath, projectId);

            var docs = new List <DocumentInfo>();

            foreach (var docFileInfo in docFileInfos)
            {
                string name;
                ImmutableArray <string> folders;
                GetDocumentNameAndFolders(docFileInfo.LogicalPath, out name, out folders);

                docs.Add(DocumentInfo.Create(
                             DocumentId.CreateNewId(projectId, debugName: docFileInfo.FilePath),
                             name,
                             folders,
                             projectFile.GetSourceCodeKind(docFileInfo.FilePath),
                             new FileTextLoader(docFileInfo.FilePath, defaultEncoding),
                             docFileInfo.FilePath,
                             docFileInfo.IsGenerated));
            }

            var additionalDocs = new List <DocumentInfo>();

            foreach (var docFileInfo in additionalDocFileInfos)
            {
                string name;
                ImmutableArray <string> folders;
                GetDocumentNameAndFolders(docFileInfo.LogicalPath, out name, out folders);

                additionalDocs.Add(DocumentInfo.Create(
                                       DocumentId.CreateNewId(projectId, debugName: docFileInfo.FilePath),
                                       name,
                                       folders,
                                       SourceCodeKind.Regular,
                                       new FileTextLoader(docFileInfo.FilePath, defaultEncoding),
                                       docFileInfo.FilePath,
                                       docFileInfo.IsGenerated));
            }

            // project references
            var resolvedReferences = await this.ResolveProjectReferencesAsync(
                projectId, projectFilePath, projectFileInfo.ProjectReferences, preferMetadata, loadedProjects, cancellationToken).ConfigureAwait(false);

            // add metadata references for project refs converted to metadata refs
            metadataReferences = metadataReferences.Concat(resolvedReferences.MetadataReferences);

            // if the project file loader couldn't figure out an assembly name, make one using the project's file path.
            var assemblyName = commandLineArgs.CompilationName;

            if (string.IsNullOrWhiteSpace(assemblyName))
            {
                assemblyName = Path.GetFileNameWithoutExtension(projectFilePath);

                // if this is still unreasonable, use a fixed name.
                if (string.IsNullOrWhiteSpace(assemblyName))
                {
                    assemblyName = "assembly";
                }
            }

            // make sure that doc-comments at least get parsed.
            var parseOptions = commandLineArgs.ParseOptions;

            if (parseOptions.DocumentationMode == DocumentationMode.None)
            {
                parseOptions = parseOptions.WithDocumentationMode(DocumentationMode.Parse);
            }

            // add all the extra options that are really behavior overrides
            var compOptions = commandLineArgs.CompilationOptions
                              .WithXmlReferenceResolver(new XmlFileResolver(projectDirectory))
                              .WithSourceReferenceResolver(new SourceFileResolver(ImmutableArray <string> .Empty, projectDirectory))
                              .WithMetadataReferenceResolver(
                new AssemblyReferenceResolver(
                    new RelativePathReferenceResolver(ImmutableArray <string> .Empty, projectDirectory),
                    MetadataFileReferenceProvider.Default))
                              .WithStrongNameProvider(new DesktopStrongNameProvider(ImmutableArray.Create(projectDirectory, outputFilePath)))
                              .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);

            loadedProjects.Add(
                ProjectInfo.Create(
                    projectId,
                    version,
                    projectName,
                    assemblyName,
                    loader.Language,
                    projectFilePath,
                    outputFilePath,
                    compilationOptions: compOptions,
                    parseOptions: parseOptions,
                    documents: docs,
                    projectReferences: resolvedReferences.ProjectReferences,
                    metadataReferences: metadataReferences,
                    analyzerReferences: analyzerReferences,
                    additionalDocuments: additionalDocs,
                    isSubmission: false,
                    hostObjectType: null));

            return(projectId);
        }
Beispiel #34
0
 public Data(VersionStamp textVersion, VersionStamp syntaxVersion, ImmutableArray <TodoItem> items)
 {
     this.TextVersion   = textVersion;
     this.SyntaxVersion = syntaxVersion;
     this.Items         = items;
 }
 public VersionArgument(VersionStamp textVersion, VersionStamp dataVersion) :
     this(textVersion, dataVersion, VersionStamp.Default)
 {
 }
 public VersionArgument(VersionStamp textVersion, VersionStamp dataVersion, VersionStamp projectVersion)
 {
     this.TextVersion    = textVersion;
     this.DataVersion    = dataVersion;
     this.ProjectVersion = projectVersion;
 }
Beispiel #37
0
 public SyntaxModel(Workspace workspace, Document document, SemanticModel semanticModel, CompilationUnitSyntax compilation, VersionStamp version)
 {
     Workspace     = workspace;
     Document      = document;
     SemanticModel = semanticModel;
     Compilation   = compilation;
     Version       = version;
 }
Beispiel #38
0
        public static DiagnosticAnalysisResultMap <DiagnosticAnalyzer, DiagnosticAnalysisResult> ReadDiagnosticAnalysisResults(
            ObjectReader reader, IDictionary <string, DiagnosticAnalyzer> analyzerMap, Project project, VersionStamp version, CancellationToken cancellationToken)
        {
            var diagnosticDataSerializer = new DiagnosticDataSerializer(VersionStamp.Default, VersionStamp.Default);

            var analysisMap = ImmutableDictionary.CreateBuilder <DiagnosticAnalyzer, DiagnosticAnalysisResult>();

            var analysisCount = reader.ReadInt32();

            for (var i = 0; i < analysisCount; i++)
            {
                var analyzer = analyzerMap[reader.ReadString()];

                var syntaxLocalMap   = ReadDiagnosticDataMap(reader, diagnosticDataSerializer, project, cancellationToken);
                var semanticLocalMap = ReadDiagnosticDataMap(reader, diagnosticDataSerializer, project, cancellationToken);
                var nonLocalMap      = ReadDiagnosticDataMap(reader, diagnosticDataSerializer, project, cancellationToken);

                var others = diagnosticDataSerializer.ReadDiagnosticData(reader, project, document: null, cancellationToken);

                var analysisResult = DiagnosticAnalysisResult.Create(
                    project,
                    version,
                    syntaxLocalMap,
                    semanticLocalMap,
                    nonLocalMap,
                    others.NullToEmpty(),
                    documentIds: null);

                analysisMap.Add(analyzer, analysisResult);
            }

            var telemetryMap = ImmutableDictionary.CreateBuilder <DiagnosticAnalyzer, AnalyzerTelemetryInfo>();

            var telemetryCount = reader.ReadInt32();

            for (var i = 0; i < telemetryCount; i++)
            {
                var analyzer      = analyzerMap[reader.ReadString()];
                var telemetryInfo = ReadTelemetry(reader, cancellationToken);

                telemetryMap.Add(analyzer, telemetryInfo);
            }

            return(DiagnosticAnalysisResultMap.Create(analysisMap.ToImmutable(), telemetryMap.ToImmutable()));
        }
Beispiel #39
0
        private static AnalysisResult GetResultOrEmpty(ImmutableDictionary <DiagnosticAnalyzer, AnalysisResult> map, DiagnosticAnalyzer analyzer, ProjectId projectId, VersionStamp version)
        {
            AnalysisResult result;

            if (map.TryGetValue(analyzer, out result))
            {
                return(result);
            }

            return(new AnalysisResult(projectId, version));
        }
Beispiel #40
0
 internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken)
 {
     return(TextAndVersion.Create(_text, VersionStamp.Create()));
 }
        internal static Solution CreateFullSolution(Workspace workspace)
        {
            var solution        = workspace.CurrentSolution;
            var languages       = ImmutableHashSet.Create(LanguageNames.CSharp, LanguageNames.VisualBasic);
            var solutionOptions = solution.Workspace.Services.GetRequiredService <IOptionService>().GetSerializableOptionsSnapshot(languages);

            solution = solution.WithOptions(solutionOptions);

            var csCode    = "class A { }";
            var project1  = solution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
            var document1 = project1.AddDocument("Document1", SourceText.From(csCode));

            var vbCode    = "Class B\r\nEnd Class";
            var project2  = document1.Project.Solution.AddProject("Project2", "Project2.dll", LanguageNames.VisualBasic);
            var document2 = project2.AddDocument("Document2", SourceText.From(vbCode));

            solution = document2.Project.Solution.GetRequiredProject(project1.Id)
                       .AddProjectReference(new ProjectReference(project2.Id, ImmutableArray.Create("test")))
                       .AddMetadataReference(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
                       .AddAnalyzerReference(new AnalyzerFileReference(Path.Combine(TempRoot.Root, "path1"), new TestAnalyzerAssemblyLoader()))
                       .AddAdditionalDocument("Additional", SourceText.From("hello"), ImmutableArray.Create("test"), @".\Add").Project.Solution;

            return(solution
                   .WithAnalyzerReferences(new[] { new AnalyzerFileReference(Path.Combine(TempRoot.Root, "path2"), new TestAnalyzerAssemblyLoader()) })
                   .AddAnalyzerConfigDocuments(
                       ImmutableArray.Create(
                           DocumentInfo.Create(
                               DocumentId.CreateNewId(project1.Id),
                               ".editorconfig",
                               loader: TextLoader.From(TextAndVersion.Create(SourceText.From("root = true"), VersionStamp.Create()))))));
        }
 public WorkspaceSnapshot(VersionStamp version, ImmutableDictionary <string, DocumentSnapshot> documents)
 {
     Version   = version;
     Documents = documents;
 }
        public static DiagnosticAnalysisResultMap <DiagnosticAnalyzer, DiagnosticAnalysisResult> Deserialize(
            ObjectReader reader, IDictionary <string, DiagnosticAnalyzer> analyzerMap, Project project, VersionStamp version, CancellationToken cancellationToken)
        {
            var diagnosticDataSerializer = new DiagnosticDataSerializer(VersionStamp.Default, VersionStamp.Default);

            var analysisMap = ImmutableDictionary.CreateBuilder <DiagnosticAnalyzer, DiagnosticAnalysisResult>();

            var analysisCount = reader.ReadInt32();

            for (var i = 0; i < analysisCount; i++)
            {
                var analyzer = analyzerMap[reader.ReadString()];

                var syntaxLocalMap   = Deserialize(reader, diagnosticDataSerializer, project, cancellationToken);
                var semanticLocalMap = Deserialize(reader, diagnosticDataSerializer, project, cancellationToken);
                var nonLocalMap      = Deserialize(reader, diagnosticDataSerializer, project, cancellationToken);

                var others = diagnosticDataSerializer.ReadFrom(reader, project, cancellationToken);

                var analysisResult = DiagnosticAnalysisResult.CreateFromSerialization(
                    project,
                    version,
                    syntaxLocalMap,
                    semanticLocalMap,
                    nonLocalMap,
                    GetOrDefault(others));

                analysisMap.Add(analyzer, analysisResult);
            }

            var telemetryMap = ImmutableDictionary.CreateBuilder <DiagnosticAnalyzer, AnalyzerTelemetryInfo>();

            var telemetryCount = reader.ReadInt32();

            for (var i = 0; i < telemetryCount; i++)
            {
                var analyzer      = analyzerMap[reader.ReadString()];
                var telemetryInfo = Deserialize(reader, cancellationToken);

                telemetryMap.Add(analyzer, telemetryInfo);
            }

            var exceptionMap = ImmutableDictionary.CreateBuilder <DiagnosticAnalyzer, ImmutableArray <DiagnosticData> >();

            var exceptionCount = reader.ReadInt32();

            for (var i = 0; i < exceptionCount; i++)
            {
                var analyzer   = analyzerMap[reader.ReadString()];
                var exceptions = diagnosticDataSerializer.ReadFrom(reader, project, cancellationToken);

                exceptionMap.Add(analyzer, GetOrDefault(exceptions));
            }

            return(DiagnosticAnalysisResultMap.Create(analysisMap.ToImmutable(), telemetryMap.ToImmutable(), exceptionMap.ToImmutable()));
        }
 public AnalysisData(VersionStamp textVersion, VersionStamp dataVersion, ImmutableArray <DiagnosticData> oldItems, ImmutableArray <DiagnosticData> newItems) :
     this(textVersion, dataVersion, newItems)
 {
     this.OldItems = oldItems;
 }
Beispiel #45
0
 public override bool TryGetTextVersion(out VersionStamp result)
 {
     return(State.TryGetTextVersion(out result));
 }
Beispiel #46
0
        async Task InitializeAsync(ITextBuffer buffer, string code, MetadataReference[] refs, string languageName, ISynchronousTagger <IClassificationTag> tagger, CompilationOptions compilationOptions, ParseOptions parseOptions)
        {
            using (var workspace = new AdhocWorkspace(RoslynMefHostServices.DefaultServices)) {
                var documents = new List <DocumentInfo>();
                var projectId = ProjectId.CreateNewId();
                documents.Add(DocumentInfo.Create(DocumentId.CreateNewId(projectId), "main.cs", null, SourceCodeKind.Regular, TextLoader.From(buffer.AsTextContainer(), VersionStamp.Create())));

                var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), "compilecodeproj", Guid.NewGuid().ToString(), languageName,
                                                     compilationOptions: compilationOptions
                                                     .WithOptimizationLevel(OptimizationLevel.Release)
                                                     .WithPlatform(Platform.AnyCpu)
                                                     .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default),
                                                     parseOptions: parseOptions,
                                                     documents: documents,
                                                     metadataReferences: refs,
                                                     isSubmission: false, hostObjectType: null);
                workspace.AddProject(projectInfo);
                foreach (var doc in documents)
                {
                    workspace.OpenDocument(doc.Id);
                }

                buffer.Replace(new Span(0, buffer.CurrentSnapshot.Length), code);

                {
                    // Initialize classification code paths
                    var spans = new NormalizedSnapshotSpanCollection(new SnapshotSpan(buffer.CurrentSnapshot, 0, buffer.CurrentSnapshot.Length));
                    foreach (var tagSpan in tagger.GetTags(spans, CancellationToken.None))
                    {
                    }
                }

                {
                    // Initialize completion code paths
                    var info = CompletionInfo.Create(buffer.CurrentSnapshot);
                    Debug.Assert(info != null);
                    if (info != null)
                    {
                        var completionTrigger = CompletionTrigger.Default;
                        var completionList    = await info.Value.CompletionService.GetCompletionsAsync(info.Value.Document, 0, completionTrigger);
                    }
                }

                {
                    // Initialize signature help code paths
                    var info = SignatureHelpInfo.Create(buffer.CurrentSnapshot);
                    Debug.Assert(info != null);
                    if (info != null)
                    {
                        int sigHelpIndex = code.IndexOf("sighelp");
                        Debug.Assert(sigHelpIndex >= 0);
                        var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand);
                        var items       = await info.Value.SignatureHelpService.GetItemsAsync(info.Value.Document, sigHelpIndex, triggerInfo);
                    }
                }

                {
                    // Initialize quick info code paths
                    var info = QuickInfoState.Create(buffer.CurrentSnapshot);
                    Debug.Assert(info != null);
                    if (info != null)
                    {
                        int quickInfoIndex = code.IndexOf("Equals");
                        Debug.Assert(quickInfoIndex >= 0);
                        var item = await info.Value.QuickInfoService.GetItemAsync(info.Value.Document, quickInfoIndex);
                    }
                }
            }
        }
 public AnalysisData(VersionStamp textVersion, VersionStamp dataVersion, ImmutableArray <DiagnosticData> items)
 {
     this.TextVersion = textVersion;
     this.DataVersion = dataVersion;
     this.Items       = items;
 }
Beispiel #48
0
 private static bool CheckVersions(Document document, VersionStamp textVersion, VersionStamp syntaxVersion, Data existingData)
 {
     // first check full version to see whether we can reuse data in same session, if we can't, check timestamp only version to see whether
     // we can use it cross-session.
     return(document.CanReusePersistedTextVersion(textVersion, existingData.TextVersion) &&
            document.CanReusePersistedSyntaxTreeVersion(syntaxVersion, existingData.SyntaxVersion));
 }
        public ProjectBuildChangeTriggerTest()
        {
            SomeProject      = new HostProject("c:\\SomeProject\\SomeProject.csproj", FallbackRazorConfiguration.MVC_1_0, "SomeProject");
            SomeOtherProject = new HostProject("c:\\SomeOtherProject\\SomeOtherProject.csproj", FallbackRazorConfiguration.MVC_2_0, "SomeOtherProject");

            Workspace = TestWorkspace.Create(w => SomeWorkspaceProject = w.AddProject(ProjectInfo.Create(
                                                                                          ProjectId.CreateNewId(),
                                                                                          VersionStamp.Create(),
                                                                                          "SomeProject",
                                                                                          "SomeProject",
                                                                                          LanguageNames.CSharp,
                                                                                          filePath: SomeProject.FilePath)));
        }
Beispiel #50
0
        private async Task <Solution> CreateSolutionAsync(Checksum solutionChecksum, CancellationToken cancellationToken)
        {
            // synchronize whole solution first
            await _assetService.SynchronizeSolutionAssetsAsync(solutionChecksum, cancellationToken).ConfigureAwait(false);

            var solutionChecksumObject = await _assetService.GetAssetAsync <SolutionStateChecksums>(solutionChecksum, cancellationToken).ConfigureAwait(false);

            var workspace = new AdhocWorkspace(RoslynServices.HostServices, workspaceKind: WorkspaceKind_RemoteWorkspace);

            // never cache any tree in memory
            workspace.Options = workspace.Options.WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0);

            var solutionInfo = await _assetService.GetAssetAsync <SolutionInfo.SolutionAttributes>(solutionChecksumObject.Info, cancellationToken).ConfigureAwait(false);

            var projects = new List <ProjectInfo>();

            foreach (var projectChecksum in solutionChecksumObject.Projects)
            {
                var projectSnapshot = await _assetService.GetAssetAsync <ProjectStateChecksums>(projectChecksum, cancellationToken).ConfigureAwait(false);

                var projectInfo = await _assetService.GetAssetAsync <ProjectInfo.ProjectAttributes>(projectSnapshot.Info, cancellationToken).ConfigureAwait(false);

                if (!workspace.Services.IsSupported(projectInfo.Language))
                {
                    // only add project our workspace supports.
                    // workspace doesn't allow creating project with unknown languages
                    continue;
                }

                var documents = new List <DocumentInfo>();
                foreach (var documentChecksum in projectSnapshot.Documents)
                {
                    var documentSnapshot = await _assetService.GetAssetAsync <DocumentStateChecksums>(documentChecksum, cancellationToken).ConfigureAwait(false);

                    var documentInfo = await _assetService.GetAssetAsync <DocumentInfo.DocumentAttributes>(documentSnapshot.Info, cancellationToken).ConfigureAwait(false);

                    var textLoader = TextLoader.From(
                        TextAndVersion.Create(
                            new ChecksumSourceText(
                                documentSnapshot.Text,
                                await _assetService.GetAssetAsync <SourceText>(documentSnapshot.Text, cancellationToken).ConfigureAwait(false)),
                            VersionStamp.Create(),
                            documentInfo.FilePath));

                    // TODO: do we need version?
                    documents.Add(
                        DocumentInfo.Create(
                            documentInfo.Id,
                            documentInfo.Name,
                            documentInfo.Folders,
                            documentInfo.SourceCodeKind,
                            textLoader,
                            documentInfo.FilePath,
                            documentInfo.IsGenerated));
                }

                var p2p = new List <ProjectReference>();
                foreach (var checksum in projectSnapshot.ProjectReferences)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var reference = await _assetService.GetAssetAsync <ProjectReference>(checksum, cancellationToken).ConfigureAwait(false);

                    p2p.Add(reference);
                }

                var metadata = new List <MetadataReference>();
                foreach (var checksum in projectSnapshot.MetadataReferences)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var reference = await _assetService.GetAssetAsync <MetadataReference>(checksum, cancellationToken).ConfigureAwait(false);

                    metadata.Add(reference);
                }

                var analyzers = new List <AnalyzerReference>();
                foreach (var checksum in projectSnapshot.AnalyzerReferences)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var reference = await _assetService.GetAssetAsync <AnalyzerReference>(checksum, cancellationToken).ConfigureAwait(false);

                    analyzers.Add(reference);
                }

                var additionals = new List <DocumentInfo>();
                foreach (var documentChecksum in projectSnapshot.AdditionalDocuments)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    var documentSnapshot = await _assetService.GetAssetAsync <DocumentStateChecksums>(documentChecksum, cancellationToken).ConfigureAwait(false);

                    var documentInfo = await _assetService.GetAssetAsync <DocumentInfo.DocumentAttributes>(documentSnapshot.Info, cancellationToken).ConfigureAwait(false);

                    var textLoader = TextLoader.From(
                        TextAndVersion.Create(
                            new ChecksumSourceText(
                                documentSnapshot.Text,
                                await _assetService.GetAssetAsync <SourceText>(documentSnapshot.Text, cancellationToken).ConfigureAwait(false)),
                            VersionStamp.Create(),
                            documentInfo.FilePath));

                    // TODO: do we need version?
                    additionals.Add(
                        DocumentInfo.Create(
                            documentInfo.Id,
                            documentInfo.Name,
                            documentInfo.Folders,
                            documentInfo.SourceCodeKind,
                            textLoader,
                            documentInfo.FilePath,
                            documentInfo.IsGenerated));
                }

                var compilationOptions = await _assetService.GetAssetAsync <CompilationOptions>(projectSnapshot.CompilationOptions, cancellationToken).ConfigureAwait(false);

                var parseOptions = await _assetService.GetAssetAsync <ParseOptions>(projectSnapshot.ParseOptions, cancellationToken).ConfigureAwait(false);

                projects.Add(
                    ProjectInfo.Create(
                        projectInfo.Id, projectInfo.Version, projectInfo.Name, projectInfo.AssemblyName,
                        projectInfo.Language, projectInfo.FilePath, projectInfo.OutputFilePath,
                        compilationOptions, parseOptions,
                        documents, p2p, metadata, analyzers, additionals, projectInfo.IsSubmission));
            }

            return(workspace.AddSolution(SolutionInfo.Create(solutionInfo.Id, solutionInfo.Version, solutionInfo.FilePath, projects)));
        }
Beispiel #51
0
 protected AbstractSyntaxTreeInfo(VersionStamp version)
     : base(version)
 {
 }
Beispiel #52
0
        private async Task <int> OnExecuteAsync(CommandLineApplication app,
                                                CancellationToken cancellationToken = default)
        {
            var outputDir = Path.IsPathFullyQualified(OutputProjectDir)
                ? OutputProjectDir
                : Path.GetFullPath(OutputProjectDir);

            Directory.CreateDirectory(outputDir);

            var workspace   = new AdhocWorkspace();
            var projectId   = ProjectId.CreateNewId();
            var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), "XP.SDK", "XP.SDK", LanguageNames.CSharp)
                              .WithDefaultNamespace("XP.SDK");
            var project = workspace.AddProject(projectInfo);

            var typeMap = new TypeMap(BuildTypeCallback);

            _enumBuilder = new EnumBuilder(workspace, projectId, outputDir, typeMap)
                           .Map("xpMainWindowStyle_MainWindow", "MainWindowType")
                           .Map("xpProperty_MainWindowType", "MainWindowProperty")
                           .Map("xpMessage_CloseButtonPushed", "MainWindowMessage")
                           .Map("xpSubWindowStyle_SubWindow", "SubWindowType")
                           .Map("xpProperty_SubWindowType", "SubWindowProperty")
                           .Map("xpPushButton", "ButtonType")
                           .Map("xpButtonBehaviorPushButton", "ButtonBehavior")
                           .Map("xpProperty_ButtonType", "ButtonProperty")
                           .Map("xpMsg_PushButtonPressed", "ButtonMessage")
                           .Map("xpTextEntryField", "TextFieldType")
                           .Map("xpProperty_EditFieldSelStart", "TextFieldProperty")
                           .Map("xpMsg_TextFieldChanged", "TextFieldMessage")
                           .Map("xpScrollBarTypeScrollBar", "ScrollBarType")
                           .Map("xpProperty_ScrollBarSliderPosition", "ScrollBarProperty")
                           .Map("xpMsg_ScrollBarSliderPositionChanged", "ScrollBarMessage")
                           .Map("xpProperty_CaptionLit", "CaptionProperty")
                           .Map("xpShip", "GeneralGraphicsType")
                           .Map("xpProperty_GeneralGraphicsType", "GeneralGraphicsProperty")
                           .Map("xpProperty_ProgressPosition", "ProgressBarProperty");
            _handleBuilder   = new HandleBuilder(workspace, projectId, outputDir, typeMap);
            _delegateBuilder = new DelegateBuilder(workspace, projectId, outputDir, typeMap);
            _structBuilder   = new StructBuilder(workspace, projectId, outputDir, typeMap);
            var functionBuilder = new FunctionBuilder(workspace, projectId, outputDir, typeMap);

            var xplmHeadersPath = Path.Combine(SdkRoot, "CHeaders", "XPLM");

            if (!Directory.Exists(xplmHeadersPath))
            {
                throw new DirectoryNotFoundException($"Directory '{xplmHeadersPath}' does not exist.");
            }
            var xmplHeaders = Directory.EnumerateFiles(xplmHeadersPath, "*.h");

            var xpWidgetsHeadersPath = Path.Combine(SdkRoot, "CHeaders", "Widgets");

            if (!Directory.Exists(xpWidgetsHeadersPath))
            {
                throw new DirectoryNotFoundException($"Directory '{xpWidgetsHeadersPath}' does not exist.");
            }
            var xpWidgetsHeaders = Directory.EnumerateFiles(xpWidgetsHeadersPath, "*.h");
            var headers          = xmplHeaders.Concat(xpWidgetsHeaders)
                                   /*.Where(x => Path.GetFileName(x) != "XPStandardWidgets.h")*/;

            var parserOptions = new CppParserOptions
            {
                Defines             = { "IBM", "XPLM303", "XPLM302", "XPLM301", "XPLM300", "XPLM210", "XPLM200" },
                ParseSystemIncludes = false,
                TargetCpu           = CppTargetCpu.X86_64,
                IncludeFolders      = { xplmHeadersPath },
            };


            var compilation = CppParser.ParseFiles(headers.ToList(), parserOptions);

            foreach (var child in compilation.Children().OfType <CppType>())
            {
                await BuildTypeAsync(child);
            }

            var functionsByHeader = compilation
                                    .Functions
                                    .ToLookup(x => x.Span.Start.File);

            foreach (var functionsInHeader in functionsByHeader)
            {
                await functionBuilder.BuildAsync(functionsInHeader);
            }

            foreach (var document in workspace.CurrentSolution.Projects.SelectMany(p => p.Documents))
            {
                var text = await document.GetTextAsync(cancellationToken);

                await using var writer = new StreamWriter(document.FilePath, false);
                text.Write(writer, cancellationToken);
            }

            return(0);

            async Task BuildTypeCallback(dynamic item)
            {
                using (Log.PushIdent())
                {
                    await BuildTypeAsync(item);
                }
            }
        }
        /// <summary>
        /// Loads the <see cref="SolutionInfo"/> for the specified solution file, including all projects referenced by the solution file and
        /// all the projects referenced by the project files.
        /// </summary>
        public async Task <SolutionInfo> LoadSolutionInfoAsync(
            string solutionFilePath,
            IReadOnlyDictionary <string, ProjectId> projectPathToProjectIdMap = null,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (solutionFilePath == null)
            {
                throw new ArgumentNullException(nameof(solutionFilePath));
            }

            var absoluteSolutionPath = this.GetAbsoluteSolutionPath(solutionFilePath, Directory.GetCurrentDirectory());

            using (_dataGuard.DisposableWait(cancellationToken))
            {
                this.SetSolutionProperties(absoluteSolutionPath);
            }

            VersionStamp version = default(VersionStamp);

#if !MSBUILD12
            Microsoft.Build.Construction.SolutionFile solutionFile = Microsoft.Build.Construction.SolutionFile.Parse(absoluteSolutionPath);
            var reportMode = this.SkipUnrecognizedProjects ? ReportMode.Log : ReportMode.Throw;

            // a list to accumulate all the loaded projects
            var loadedProjects = new LoadState(null);

            // load all the projects
            foreach (var project in solutionFile.ProjectsInOrder)
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (project.ProjectType != SolutionProjectType.SolutionFolder)
                {
                    var projectAbsolutePath = TryGetAbsolutePath(project.AbsolutePath, reportMode);
                    if (projectAbsolutePath != null)
                    {
                        IProjectFileLoader loader;
                        if (TryGetLoaderFromProjectPath(projectAbsolutePath, reportMode, out loader))
                        {
                            // projects get added to 'loadedProjects' as side-effect
                            // never prefer metadata when loading solution, all projects get loaded if they can.
                            var tmp = await GetOrLoadProjectAsync(projectAbsolutePath, loader, preferMetadata : false, loadedProjects : loadedProjects, cancellationToken : cancellationToken).ConfigureAwait(false);
                        }
                    }
                }
            }
#else
            SolutionFile solutionFile = null;

            using (var reader = new StreamReader(absoluteSolutionPath))
            {
                version = VersionStamp.Create(File.GetLastWriteTimeUtc(absoluteSolutionPath));
                var text = await reader.ReadToEndAsync().ConfigureAwait(false);

                solutionFile = SolutionFile.Parse(new StringReader(text));
            }

            var solutionFolder = Path.GetDirectoryName(absoluteSolutionPath);

            // a list to accumulate all the loaded projects
            var loadedProjects = new LoadState(null);

            var reportMode = this.SkipUnrecognizedProjects ? ReportMode.Log : ReportMode.Throw;

            // load all the projects
            foreach (var projectBlock in solutionFile.ProjectBlocks)
            {
                cancellationToken.ThrowIfCancellationRequested();

                string absoluteProjectPath;
                if (TryGetAbsoluteProjectPath(projectBlock.ProjectPath, solutionFolder, reportMode, out absoluteProjectPath))
                {
                    IProjectFileLoader loader;
                    if (TryGetLoaderFromProjectPath(absoluteProjectPath, reportMode, out loader))
                    {
                        // projects get added to 'loadedProjects' as side-effect
                        // never prefer metadata when loading solution, all projects get loaded if they can.
                        var tmp = await GetOrLoadProjectAsync(absoluteProjectPath, loader, preferMetadata : false, loadedProjects : loadedProjects, cancellationToken : cancellationToken).ConfigureAwait(false);
                    }
                }
            }
#endif

            // construct workspace from loaded project infos
            return(SolutionInfo.Create(SolutionId.CreateNewId(debugName: absoluteSolutionPath), version, absoluteSolutionPath, loadedProjects.Projects));
        }
        protected static void AnalyzeWithRule <T>(string input, string ruleId, string output = null, int issueToFix = -1, int actionToRun = 0, Action <int, Diagnostic> diagnosticCheck = null) where T : DiagnosticAnalyzer, new()
        {
            var text = new StringBuilder();

            var expectedDiagnosics = new List <TextSpan> ();
            int start = -1;

            for (int i = 0; i < input.Length; i++)
            {
                char ch = input [i];
                if (ch == '$')
                {
                    if (start < 0)
                    {
                        start = text.Length;
                        continue;
                    }
                    expectedDiagnosics.Add(TextSpan.FromBounds(start, text.Length));
                    start = -1;
                }
                else
                {
                    text.Append(ch);
                }
            }

            var syntaxTree = CSharpSyntaxTree.ParseText(text.ToString());

            Compilation compilation = CreateCompilationWithMscorlib(new [] { syntaxTree });

            var diagnostics = new List <Diagnostic>();
            var compilationWithAnalyzers = compilation.WithAnalyzers(System.Collections.Immutable.ImmutableArray <DiagnosticAnalyzer> .Empty.Add(new T()));

            diagnostics.AddRange(compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result);


            if (expectedDiagnosics.Count != diagnostics.Count)
            {
                Console.WriteLine("Diagnostics: " + diagnostics.Count);
                foreach (var diag in diagnostics)
                {
                    Console.WriteLine(diag.Id + "/" + diag.GetMessage());
                }
                Assert.Fail("Diagnostic count mismatch expected: " + expectedDiagnosics.Count + " but was:" + diagnostics.Count);
            }

            for (int i = 0; i < expectedDiagnosics.Count; i++)
            {
                var d         = diagnostics [i];
                var wholeSpan = GetWholeSpan(d);
                if (wholeSpan != expectedDiagnosics [i])
                {
                    Assert.Fail("Diagnostic " + i + " span mismatch expected: " + expectedDiagnosics[i] + " but was " + wholeSpan);
                }
                if (diagnosticCheck != null)
                {
                    diagnosticCheck(i, d);
                }
            }

            if (output == null)
            {
                return;
            }

            var workspace  = new TestWorkspace();
            var projectId  = ProjectId.CreateNewId();
            var documentId = DocumentId.CreateNewId(projectId);

            workspace.Open(ProjectInfo.Create(
                               projectId,
                               VersionStamp.Create(),
                               "", "", LanguageNames.CSharp, null, null, null, null,
                               new [] {
                DocumentInfo.Create(
                    documentId,
                    "a.cs",
                    null,
                    SourceCodeKind.Regular,
                    TextLoader.From(TextAndVersion.Create(SourceText.From(text.ToString()), VersionStamp.Create())))
            }
                               ));
            if (issueToFix < 0)
            {
                diagnostics.Reverse();
                foreach (var v in diagnostics)
                {
                    RunFix(workspace, projectId, documentId, v);
                }
            }
            else
            {
                RunFix(workspace, projectId, documentId, diagnostics.ElementAt(issueToFix), actionToRun);
            }

            var txt = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId).GetTextAsync().Result.ToString();

            if (output != txt)
            {
                Console.WriteLine("expected:");
                Console.WriteLine(output);
                Console.WriteLine("got:");
                Console.WriteLine(txt);
                Assert.Fail();
            }
        }
Beispiel #55
0
        public void Initalize()
        {
            var solutionFilePath = _env.SolutionFilePath;

            if (string.IsNullOrEmpty(solutionFilePath))
            {
                var solutions = Directory.GetFiles(_env.Path, "*.sln");
                var result    = SolutionPicker.ChooseSolution(_env.Path, solutions);

                if (result.Message != null)
                {
                    _logger.WriteInformation(result.Message);
                }

                if (result.Solution == null)
                {
                    return;
                }

                solutionFilePath = result.Solution;
            }

            SolutionFile solutionFile = null;

            _context.SolutionPath = solutionFilePath;

            using (var stream = File.OpenRead(solutionFilePath))
            {
                using (var reader = new StreamReader(stream))
                {
                    solutionFile = SolutionFile.Parse(reader);
                }
            }

            _logger.WriteInformation($"Detecting projects in '{solutionFilePath}'.");

            foreach (var block in solutionFile.ProjectBlocks)
            {
                if (!_supportsProjectTypes.Contains(block.ProjectTypeGuid))
                {
                    if (UnityTypeGuid(block.ProjectName) != block.ProjectTypeGuid)
                    {
                        _logger.WriteWarning("Skipped unsupported project type '{0}'", block.ProjectPath);
                        continue;
                    }
                }

                if (_context.ProjectGuidToWorkspaceMapping.ContainsKey(block.ProjectGuid))
                {
                    continue;
                }

                var projectFilePath = Path.GetFullPath(Path.GetFullPath(Path.Combine(_env.Path, block.ProjectPath.Replace('\\', Path.DirectorySeparatorChar))));

                _logger.WriteInformation($"Loading project from '{projectFilePath}'.");

                var projectFileInfo = CreateProject(projectFilePath);

                if (projectFileInfo == null)
                {
                    continue;
                }

                var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(projectFileInfo.Name),
                                                     VersionStamp.Create(),
                                                     projectFileInfo.Name,
                                                     projectFileInfo.AssemblyName,
                                                     LanguageNames.CSharp,
                                                     projectFileInfo.ProjectFilePath);

                _workspace.AddProject(projectInfo);

                projectFileInfo.WorkspaceId = projectInfo.Id;

                _context.Projects[projectFileInfo.ProjectFilePath]        = projectFileInfo;
                _context.ProjectGuidToWorkspaceMapping[block.ProjectGuid] = projectInfo.Id;

                _watcher.Watch(projectFilePath, OnProjectChanged);
            }

            foreach (var projectFileInfo in _context.Projects.Values)
            {
                UpdateProject(projectFileInfo);
            }
        }
        public void Initalize()
        {
            _logger.LogInformation($"Detecting CSX files in '{_env.Path}'.");

            var allCsxFiles = Directory.GetFiles(_env.Path, "*.csx", SearchOption.TopDirectoryOnly);

            if (allCsxFiles.Length == 0)
            {
                _logger.LogInformation("Could not find any CSX files");
                return;
            }

            _scriptCsContext.Path = _env.Path;
            _logger.LogInformation($"Found {allCsxFiles.Length} CSX files.");

            //script name is added here as a fake one (dir path not even a real file); this is OK though -> it forces MEF initialization
            var scriptServicesBuilder = new ScriptServicesBuilder(new ScriptConsole(), LogManager.GetCurrentClassLogger()).
                                        LogLevel(LogLevel.Info).Cache(false).Repl(false).ScriptName(_env.Path).ScriptEngine <NullScriptEngine>();

            _scriptServices = scriptServicesBuilder.Build();

            var mscorlib          = MetadataReference.CreateFromAssembly(typeof(object).GetTypeInfo().Assembly);
            var systemCore        = MetadataReference.CreateFromAssembly(typeof(Enumerable).GetTypeInfo().Assembly);
            var scriptcsContracts = MetadataReference.CreateFromAssembly(typeof(IScriptHost).Assembly);

            var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Script);

            var scriptPacks   = _scriptServices.ScriptPackResolver.GetPacks().ToList();
            var assemblyPaths = _scriptServices.AssemblyResolver.GetAssemblyPaths(_env.Path);

            foreach (var csxPath in allCsxFiles)
            {
                try
                {
                    _scriptCsContext.CsxFiles.Add(csxPath);
                    var processResult = _scriptServices.FilePreProcessor.ProcessFile(csxPath);

                    var references = new List <MetadataReference> {
                        mscorlib, systemCore, scriptcsContracts
                    };
                    var usings = new List <string>(ScriptExecutor.DefaultNamespaces);

                    //default references
                    ImportReferences(references, ScriptExecutor.DefaultReferences);

                    //file usings
                    usings.AddRange(processResult.Namespaces);

                    //#r references
                    ImportReferences(references, processResult.References);

                    //nuget references
                    ImportReferences(references, assemblyPaths);

                    //script packs
                    if (scriptPacks != null && scriptPacks.Any())
                    {
                        var scriptPackSession = new ScriptPackSession(scriptPacks, new string[0]);
                        scriptPackSession.InitializePacks();

                        //script pack references
                        ImportReferences(references, scriptPackSession.References);

                        //script pack usings
                        usings.AddRange(scriptPackSession.Namespaces);

                        _scriptCsContext.ScriptPacks.UnionWith(scriptPackSession.Contexts.Select(pack => pack.GetType().ToString()));
                    }

                    _scriptCsContext.References.UnionWith(references.Select(x => x.Display));
                    _scriptCsContext.Usings.UnionWith(usings);

                    var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usings.Distinct());

                    var fileName = Path.GetFileName(csxPath);

                    var projectId = ProjectId.CreateNewId(Guid.NewGuid().ToString());
                    var project   = ProjectInfo.Create(projectId, VersionStamp.Create(), fileName, $"{fileName}.dll", LanguageNames.CSharp, null, null,
                                                       compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost));

                    _workspace.AddProject(project);
                    AddFile(csxPath, projectId);

                    foreach (var filePath in processResult.LoadedScripts.Distinct().Except(new[] { csxPath }))
                    {
                        _scriptCsContext.CsxFiles.Add(filePath);
                        var loadedFileName = Path.GetFileName(filePath);

                        var loadedFileProjectId         = ProjectId.CreateNewId(Guid.NewGuid().ToString());
                        var loadedFileSubmissionProject = ProjectInfo.Create(loadedFileProjectId, VersionStamp.Create(),
                                                                             $"{loadedFileName}-LoadedFrom-{fileName}", $"{loadedFileName}-LoadedFrom-{fileName}.dll", LanguageNames.CSharp, null, null,
                                                                             compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost));

                        _workspace.AddProject(loadedFileSubmissionProject);
                        AddFile(filePath, loadedFileProjectId);
                        _workspace.AddProjectReference(projectId, new ProjectReference(loadedFileProjectId));
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"{csxPath} will be ignored due to the following error:", ex);
                }
            }
        }
Beispiel #57
0
        static TSymbol FindSymbol <TSymbol>(string code)
            where TSymbol : ISymbol
        {
            var position = code.IndexOf('$');

            var cleanedCode = code.Remove(position, 1);

            var workspace  = new DiagnosticTestBase.TestWorkspace();
            var projectId  = ProjectId.CreateNewId();
            var documentId = DocumentId.CreateNewId(projectId);

            var docInfo = DocumentInfo.Create(documentId, "Document1.cs", loader: TextLoader.From(TextAndVersion.Create(SourceText.From(cleanedCode), VersionStamp.Create())));

            var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);

            var projectInfo = ProjectInfo.Create(
                projectId,
                VersionStamp.Create(),
                "Project",
                "Project",
                LanguageNames.CSharp,
                metadataReferences: new[] { mscorlib },
                documents: new[] { docInfo }
                );


            workspace.Open(projectInfo);

            var document = workspace.CurrentSolution.GetDocument(documentId);

            var semanticModel = document.GetSemanticModelAsync().Result;

            var diag = semanticModel.GetDiagnostics();

            Assert.That(diag, Is.Empty, "No errors reported");

            var symbol = SymbolFinder.FindSymbolAtPosition(semanticModel, position, workspace);

            Assert.That(symbol, Is.Not.Null, "Symbol should be found");
            Assert.That(symbol, Is.InstanceOf <TSymbol>());

            return((TSymbol)symbol);
        }
        private void AddFile(string filePath, ProjectId projectId)
        {
            using (var stream = File.OpenRead(filePath))
                using (var reader = new StreamReader(stream))
                {
                    var fileName = Path.GetFileName(filePath);
                    var csxFile  = reader.ReadToEnd();

                    var documentId   = DocumentId.CreateNewId(projectId, fileName);
                    var documentInfo = DocumentInfo.Create(documentId, fileName, null, SourceCodeKind.Script, null, filePath)
                                       .WithSourceCodeKind(SourceCodeKind.Script)
                                       .WithTextLoader(TextLoader.From(TextAndVersion.Create(SourceText.From(csxFile), VersionStamp.Create())));
                    _workspace.AddDocument(documentInfo);
                }
        }
 public static TestDocumentSnapshot Create(string filePath, VersionStamp version) => Create(filePath, string.Empty, version);
        private async Task <(DiagnosticAnalysisResult loadDiagnostics, ImmutableHashSet <Document>?failedDocuments)> GetDocumentLoadFailuresAsync(Project project, VersionStamp version, CancellationToken cancellationToken)
        {
            ImmutableHashSet <Document> .Builder?failedDocuments = null;
            ImmutableDictionary <DocumentId, ImmutableArray <DiagnosticData> > .Builder?lazyLoadDiagnostics = null;

            foreach (var document in project.Documents)
            {
                var loadDiagnostic = await document.State.GetLoadDiagnosticAsync(cancellationToken).ConfigureAwait(false);

                if (loadDiagnostic != null)
                {
                    lazyLoadDiagnostics ??= ImmutableDictionary.CreateBuilder <DocumentId, ImmutableArray <DiagnosticData> >();
                    lazyLoadDiagnostics.Add(document.Id, ImmutableArray.Create(DiagnosticData.Create(loadDiagnostic, document)));

                    failedDocuments ??= ImmutableHashSet.CreateBuilder <Document>();
                    failedDocuments.Add(document);
                }
            }

            var result = DiagnosticAnalysisResult.Create(
                project,
                version,
                syntaxLocalMap: lazyLoadDiagnostics?.ToImmutable() ?? ImmutableDictionary <DocumentId, ImmutableArray <DiagnosticData> > .Empty,
                semanticLocalMap: ImmutableDictionary <DocumentId, ImmutableArray <DiagnosticData> > .Empty,
                nonLocalMap: ImmutableDictionary <DocumentId, ImmutableArray <DiagnosticData> > .Empty,
                others: ImmutableArray <DiagnosticData> .Empty,
                documentIds: null);

            return(result, failedDocuments?.ToImmutable());
        }