Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Roslyn as a compilation hook/AOP tool [duplicate]

For example I have

class Foo: INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;
    public int Bar {get;set;}
}

Can I get the Foo class AST and rewrite Bar, in compile time, to

    public string Bar
    {
        get { return this.bar; }

        set 
        {
            if (value != this.bar)
            {
                this.phoneNumberValue = value;
                PropertyChanged(this, new PropertyChangedEventArgs("Bar"));
            }
        }
    }

.

like image 859
dotneter Avatar asked Oct 20 '11 09:10

dotneter


People also ask

What is Roslyn C #compiler?

Today we will look at the Roslyn C# compiler and how to run it directly. We are so used to IDE environments that we rarely step back to think about what happens under the hood. When we compile a C# program in Visual Studio, it calls the C# compiler also known as Roslyn.

Can Roslyn source generators modify existing code?

They cannot, however, modify existing code. Strictly speaking, Roslyn source generators don’t enable any scenario that was impossible before. The novelty with Roslyn source generators is that they are built into the Roslyn compiler, which gives two advantages.

Can I use Roslyn without Visual Studio or another IDE?

In this article, we looked at creating a console application and running it directly using the C# compiler Roslyn without the use of Visual Studio or another IDE. This might not be a normal practice in our everyday work, but it is always good to understand how things work under the hood. Happy coding!

Should we accept AOP in PostSharp?

Unlike AspectJ aspects, PostSharp aspects have always had access to the code model. This approach was also the one of Code Analysis (FxCop) and now of Roslyn analyzers and source generators. Therefore, we don’t have to accept or reject AOP as a whole.


2 Answers

Compile time re-writing isn't directly supported by Roslyn today, but syntactic and semantic transformations definitely are. In fact, take a look at the "ImplementNotifyPropertyChanged" sample included in the CTP to see something of what you want to do. The sample is implemented as a design time transformation in and IDE feature, but you can extract the logic and make it into something like a pre-build task that rewrites files before compilation.

like image 178
Kevin Pilch Avatar answered Nov 13 '22 01:11

Kevin Pilch


I don't think this is possible in the current CTP that has been released as the compiler is there as service but there is no such thing which allows you to plug into the compilation process as you can do in Nemerle.

like image 28
Ankur Avatar answered Nov 12 '22 23:11

Ankur