本文整理汇总了C#中Microsoft.CodeAnalysis.Project.GetCompilationAsync方法的典型用法代码示例。如果您正苦于以下问题:C# Project.GetCompilationAsync方法的具体用法?C# Project.GetCompilationAsync怎么用?C# Project.GetCompilationAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Microsoft.CodeAnalysis.Project
的用法示例。
在下文中一共展示了Project.GetCompilationAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetDiagnostics
internal static async Task<ImmutableArray<Diagnostic>> GetDiagnostics (Project project, List<DiagnosticAnalyzer> providers, CancellationToken token)
{
var analyzers = ImmutableArray<DiagnosticAnalyzer>.Empty.AddRange (providers);
try {
var compilation = await project.GetCompilationAsync (token).ConfigureAwait (false);
CompilationWithAnalyzers compilationWithAnalyzer;
var options = new CompilationWithAnalyzersOptions (
null,
delegate (Exception exception, DiagnosticAnalyzer analyzer, Diagnostic diag) {
LoggingService.LogError ("Exception in diagnostic analyzer " + diag.Id + ":" + diag.GetMessage (), exception);
},
true,
false
);
compilationWithAnalyzer = compilation.WithAnalyzers (analyzers, options);
if (token.IsCancellationRequested)
return ImmutableArray<Diagnostic>.Empty;
return await compilationWithAnalyzer.GetAnalyzerDiagnosticsAsync ().ConfigureAwait (false);
} catch (Exception) {
return ImmutableArray<Diagnostic>.Empty;
} finally {
CompilationWithAnalyzers.ClearAnalyzerState (analyzers);
}
}
示例2: Execute
public override bool Execute()
{
if (Language != CSharp)
{
Log.LogError("Unsupported language {0}.", Language);
return false;
}
Project = this.GetOrAddProject(ProjectFullPath);
if (cancellation.IsCancellationRequested)
{
Log.LogWarning("Cancellation was requested. Aborting task.");
return false;
}
Compilation = Project.GetCompilationAsync(cancellation.Token).Result;
var logWarnings = false;
if (!string.IsNullOrEmpty(LogWarnings) && bool.TryParse(LogWarnings, out logWarnings) && logWarnings)
{
var diagnostics = Compilation.GetDiagnostics(cancellation.Token);
if (diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error))
Log.LogWarning("Code generation may not be complete, since there are compilation errors: " +
string.Join(Environment.NewLine, diagnostics.Select(d => d.GetMessage())));
}
return true;
}
示例3: GetThrownExceptionTypeNames
private static async Task<IEnumerable<string>> GetThrownExceptionTypeNames(Project project)
{
var compilation = await project.GetCompilationAsync();
return compilation.SyntaxTrees
.SelectMany(tree => GetThrownExceptionTypeNames(compilation, tree))
.Distinct();
}
示例4: Calculate
public async Task<IProjectMetric> Calculate(Project project, Solution solution)
{
if (project == null)
{
return null;
}
var compilation = project.GetCompilationAsync();
return await InnerCalculate(project, compilation, solution).ConfigureAwait(false);
}
示例5: GenerateDll
private static void GenerateDll(Project p)
{
var c = p.GetCompilationAsync().Result;
var fileName = Path.Combine(OutputPath, p.Name, p.AssemblyName + ".dll");
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
var result = c.Emit(fileName);
if (!result.Success)
{
foreach (var diagnostic in result.Diagnostics)
Debug.WriteLine(diagnostic.Location.GetMappedLineSpan().StartLinePosition.Line + " " +
diagnostic.GetMessage());
}
}
示例6: Verify
public static void Verify(Project project, DiagnosticAnalyzer diagnosticAnalyzer)
{
var compilation = project.GetCompilationAsync().Result;
var compilationWithAnalyzer = GetDiagnostics(compilation, diagnosticAnalyzer);
var expected = new List<int>(ExpectedIssues(compilation.SyntaxTrees.First()));
foreach (var diagnostic in compilationWithAnalyzer
.Where(diag => diag.Id == diagnosticAnalyzer.SupportedDiagnostics.Single().Id))
{
var line = diagnostic.GetLineNumberToReport();
expected.Should().Contain(line);
expected.Remove(line);
}
expected.Should().BeEquivalentTo(Enumerable.Empty<int>());
}
示例7: Create
/// <summary>
/// Create a new P# static analysis context from the given program unit.
/// </summary>
/// <param name="project">Project</param>
public static void Create(Project project)
{
AnalysisContext.Compilation = project.GetCompilationAsync().Result;
AnalysisContext.Machines = new List<ClassDeclarationSyntax>();
AnalysisContext.MachineInheritance = new Dictionary<ClassDeclarationSyntax, ClassDeclarationSyntax>();
AnalysisContext.MachineActions = new Dictionary<ClassDeclarationSyntax, List<string>>();
AnalysisContext.Summaries = new Dictionary<BaseMethodDeclarationSyntax, MethodSummary>();
AnalysisContext.StateTransitionGraphs = new Dictionary<ClassDeclarationSyntax, StateTransitionGraphNode>();
// Finds all the machines in the project.
AnalysisContext.FindAllMachines();
// Finds machine inheritance information.
AnalysisContext.FindMachineInheritanceInformation();
// Find all machine actions in the project.
AnalysisContext.FindAllMachineActions();
}
示例8: CreateCompilationFromSolution
private static bool CreateCompilationFromSolution(Options options, MSBuildWorkspace workspace, out Task<Compilation> compilationAsync, out Project project)
{
var solution = workspace.OpenSolutionAsync(options.Solution).Result;
var projects = solution.Projects.Where(proj => proj.FilePath.Equals(options.Project));
if (projects.Any())
{
project = projects.First();
}
else
{
Output.WriteError("Unable to find the specified project in solution. Project {0}", options.Project);
project = null;
compilationAsync = null;
return false;
}
compilationAsync = project.GetCompilationAsync();
return true;
}
示例9: MakeRetro
public static async Task<Project> MakeRetro(Project prj)
{
var compilation = await prj.GetCompilationAsync();
var changedDocuments = MakeChanges(compilation);
Project nPrj = prj;
foreach (var newDoc in changedDocuments)
{
var docId = nPrj.GetDocumentId(newDoc.Item1);
var doc = nPrj.GetDocument(docId);
nPrj = nPrj.RemoveDocument(docId);
var nd = nPrj.AddDocument(doc.Name, newDoc.Item2, doc.Folders, doc.FilePath);
nPrj = nd.Project;
}
return nPrj;
}
示例10: NavigateOnForegroundThread
private void NavigateOnForegroundThread(SourceLocation sourceLocation, SymbolKey symbolId, Project project, Document document)
{
AssertIsForeground();
// Notify of navigation so third parties can intercept the navigation
if (symbolId != null)
{
var symbolNavigationService = _workspace.Services.GetService<ISymbolNavigationService>();
var symbol = symbolId.Resolve(project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None)).Symbol;
// Do not allow third party navigation to types or constructors
if (symbol != null &&
!(symbol is ITypeSymbol) &&
!symbol.IsConstructor() &&
symbolNavigationService.TrySymbolNavigationNotify(symbol, project.Solution))
{
return;
}
}
if (sourceLocation.IsValid)
{
// We must find the right document in this project. This may not be the
// ContextDocumentId if you have a partial member that is shown under one
// document, but only exists in the other
if (document != null)
{
var editorWorkspace = document.Project.Solution.Workspace;
var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
navigationService.TryNavigateToLineAndOffset(
editorWorkspace,
document.Id,
sourceLocation.StartPosition.Line,
sourceLocation.StartPosition.Character);
}
}
}
示例11: CompileProject
/// <summary>
/// Compiles the given P# project.
/// </summary>
/// <param name="project">Project</param>
private void CompileProject(Project project)
{
var compilation = project.GetCompilationAsync().Result;
try
{
if (this.CompilationContext.ActiveCompilationTarget == CompilationTarget.Testing ||
this.CompilationContext.ActiveCompilationTarget == CompilationTarget.Distribution)
{
this.ToFile(compilation, OutputKind.DynamicallyLinkedLibrary,
project.OutputFilePath);
}
else
{
this.ToFile(compilation, project.CompilationOptions.OutputKind,
project.OutputFilePath);
}
}
catch (ApplicationException ex)
{
ErrorReporter.ReportAndExit(ex.Message);
}
}
示例12: FindMethodSymbolInProject
private static IMethodSymbol FindMethodSymbolInProject(MethodDescriptor methodDescriptor, Project project)
{
var compilation = project.GetCompilationAsync().Result;
return FindMethodInCompilation(methodDescriptor, compilation);
}
示例13: TryNavigateToSymbol
public bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet options, CancellationToken cancellationToken)
{
if (project == null || symbol == null)
{
return false;
}
options = options ?? project.Solution.Workspace.Options;
symbol = symbol.OriginalDefinition;
// Prefer visible source locations if possible.
var sourceLocations = symbol.Locations.Where(loc => loc.IsInSource);
var visibleSourceLocations = sourceLocations.Where(loc => loc.IsVisibleSourceLocation());
var sourceLocation = visibleSourceLocations.FirstOrDefault() ?? sourceLocations.FirstOrDefault();
if (sourceLocation != null)
{
var targetDocument = project.Solution.GetDocument(sourceLocation.SourceTree);
if (targetDocument != null)
{
var editorWorkspace = targetDocument.Project.Solution.Workspace;
var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
return navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, options);
}
}
// We don't have a source document, so show the Metadata as Source view in a preview tab.
var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault();
if (metadataLocation == null || !_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
{
return false;
}
// Should we prefer navigating to the Object Browser over metadata-as-source?
if (options.GetOption(VisualStudioNavigationOptions.NavigateToObjectBrowser, project.Language))
{
var libraryService = project.LanguageServices.GetService<ILibraryService>();
if (libraryService == null)
{
return false;
}
var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, project, compilation);
if (navInfo == null)
{
navInfo = libraryService.NavInfoFactory.CreateForProject(project);
}
if (navInfo != null)
{
var navigationTool = _serviceProvider.GetService<SVsObjBrowser, IVsNavigationTool>();
return navigationTool.NavigateToNavInfo(navInfo) == VSConstants.S_OK;
}
// Note: we'll fallback to Metadata-As-Source if we fail to get IVsNavInfo, but that should never happen.
}
// Generate new source or retrieve existing source for the symbol in question
var result = _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, cancellationToken).WaitAndGetResult(cancellationToken);
var vsRunningDocumentTable4 = _serviceProvider.GetService<SVsRunningDocumentTable, IVsRunningDocumentTable4>();
var fileAlreadyOpen = vsRunningDocumentTable4.IsMonikerValid(result.FilePath);
var openDocumentService = _serviceProvider.GetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>();
IVsUIHierarchy hierarchy;
uint itemId;
IOleServiceProvider localServiceProvider;
IVsWindowFrame windowFrame;
openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out localServiceProvider, out hierarchy, out itemId, out windowFrame);
var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath);
var vsTextBuffer = (IVsTextBuffer)vsRunningDocumentTable4.GetDocumentData(documentCookie);
var textBuffer = _editorAdaptersFactory.GetDataBuffer(vsTextBuffer);
if (!fileAlreadyOpen)
{
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true));
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle));
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip));
}
windowFrame.Show();
var openedDocument = textBuffer.AsTextContainer().GetRelatedDocuments().FirstOrDefault();
if (openedDocument != null)
{
var editorWorkspace = openedDocument.Project.Solution.Workspace;
var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
return navigationService.TryNavigateToSpan(
workspace: editorWorkspace,
documentId: openedDocument.Id,
textSpan: result.IdentifierLocation.SourceSpan,
options: options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true));
}
//.........这里部分代码省略.........
示例14: ProcessProject
static void ProcessProject(Project project)
{
//TODO: ignore unit test projects....
var compilation = project.GetCompilationAsync().Result;
if (compilation.Language != "C#")
return;
foreach (var document in project.Documents)
ProcessDocument(document);
}
示例15: ProjectCompile
//static public IEnumerable<Project> GetProjects(String solutionPath) {
// return GetSolution(solutionPath).Projects;
//}
public static Compilation ProjectCompile(Project project)
{
//string solutionPath = @"C:\Users\Vitaliy\Documents\Visual Studio 2013\Projects\Metr2\Metr2.sln";
//var workspace = MSBuildWorkspace.Create();
//_solution = workspace.OpenSolutionAsync(solutionPath).Result;
//var projects = _solution.Projects;
//var project = projects.Where(p => p.Name.ToString() == projectToPick).First();
return project.GetCompilationAsync().Result;
// var temp = _compilation.GetCompilationNamespace(_compilation.GlobalNamespace);
}