简体   繁体   中英

Roslyn - Can I subscribe to diagnostics being added to my compilation?

I am using the Roslyn SDK with StackExchange.Precompilation to create build-time auto-refactorings (precompiler macros) for C#.

During the process of syntax rewriting, it is very useful to add a Diagnostic to the compilation when an error occurs or when a macro is used inappropriately in source code. Unlike throwing an exception, this displays errors in the VS Error List window and does not abort the thread like an exception might, so all build errors can be accumulated and listed for the user.

However, for debugging the rewriter, it would be very handy to be able to subscribe to a DiagnosticAdded event (or observable), so that a single breakpoint can be set to catch all diagnostics/errors.

Is there publisher in the Roslyn SDK (or StackExchange.Precompilation) like this?

There's nothing public. Roslyn is open source, so you could build your own for testing and then set breakpoints in the diagnostic functions you're interested in.

I supect this question is related to StackExchange.Precompilation - How can I unit test precompilation diagnostics?

StackExchange.Precompilation doesn't have any events/publishers for this, but for testing purposes you could craft a After / BeforeCompileContext with an IList<Diagnostics> that allows observation, eg ObservableCollection :

CSharpCompilation compilation = ...;
ICompileModule testModule = ...
var diagnostics = new ObservableCollection<Diagnostics>();
var context = new BeforeCompileContext
{
    Compilation = compilation,
    Diagnostics = diagnostics,
};
diagnostics.CollectionChanged += (s, e) => { /* do something */ };
testModule.BeforeCompile(context);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM