26
Aspect Oriented Aspect Oriented Programming in .NET Programming in .NET with CodeBricks with CodeBricks Antonio Cisternino Antonio Cisternino Academic Days Academic Days Milan, 2004 Milan, 2004 Università di Pisa Supported by Microsoft Research

Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

Embed Size (px)

DESCRIPTION

Agenda AOP and Code Generation AOP and Code Generation CodeBricks: quick introCodeBricks: quick intro [a]C#: annotated join points[a]C#: annotated join points ARE: a generic program rewriting systemARE: a generic program rewriting system ConclusionsConclusions

Citation preview

Page 1: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

Aspect Oriented Aspect Oriented Programming in .NET Programming in .NET

with CodeBrickswith CodeBricks

Antonio CisterninoAntonio CisterninoAcademic DaysAcademic Days

Milan, 2004Milan, 2004

Università di Pisa

Supported by Microsoft Research grant

Page 2: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

IntroductionIntroduction• Aspect Oriented Programming is a way of Aspect Oriented Programming is a way of

modularize crosscutting concerns in modularize crosscutting concerns in computer programscomputer programs

• AOP tools are responsible for synthesizing AOP tools are responsible for synthesizing the program by combining different aspectsthe program by combining different aspects

• CodeBricks provides support for meta-CodeBricks provides support for meta-programming within CLR: how can we use programming within CLR: how can we use the code generation facilities to support the code generation facilities to support AOP?AOP?

Page 3: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

AgendaAgenda• AOP and Code GenerationAOP and Code Generation• CodeBricks: quick introCodeBricks: quick intro• [a]C#: annotated join points[a]C#: annotated join points• ARE: a generic program rewriting ARE: a generic program rewriting

systemsystem• ConclusionsConclusions

Page 4: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

Aspect Oriented Aspect Oriented ProgrammingProgramming

• Traditional code organization privileges Traditional code organization privileges functional aspect of code: other aspects, like functional aspect of code: other aspects, like logging, security, concurrency, tend to crosscut logging, security, concurrency, tend to crosscut the program.the program.

• Aspect Oriented Programming aims to develop Aspect Oriented Programming aims to develop tools modularizing crosscutting concerns.tools modularizing crosscutting concerns.

• AOP languages (like AspectJ) are based on the AOP languages (like AspectJ) are based on the single notion of single notion of join pointsjoin points: positions in the : positions in the source code where the code of a crosscutting source code where the code of a crosscutting aspect should join the programaspect should join the program

• AOP is a form of generative programming: AOP is a form of generative programming: programs are synthesized from aspects and programs are synthesized from aspects and codecode

Page 5: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

AspectJ: a shallow AspectJ: a shallow approach to AOPapproach to AOP

• AspectJ is one of the most popular systems for AspectJ is one of the most popular systems for AOPAOP

• It extends the Java language with constructs to It extends the Java language with constructs to specify join points and how aspects are weaved specify join points and how aspects are weaved into theminto them

• PointcutsPointcuts are defined by means of pattern are defined by means of pattern matchingmatching

• It is possible to insert code before and after a It is possible to insert code before and after a given pointcutgiven pointcut

• Inter-type declarations allow to interact with Inter-type declarations allow to interact with the static structure of a program (i.e. types)the static structure of a program (i.e. types)

Page 6: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

AspectJ: a shallow AspectJ: a shallow approach to AOPapproach to AOP

public aspect AutoLog{public aspect AutoLog{ pointcut publicMethods() : pointcut publicMethods() : execution(public * org.apache.cactus..*(..)); execution(public * org.apache.cactus..*(..)); pointcut logObjectCalls() : pointcut logObjectCalls() : execution(* Logger.*(..));execution(* Logger.*(..)); pointcut loggableCalls() :pointcut loggableCalls() : publicMethods() && ! logObjectCalls();publicMethods() && ! logObjectCalls(); before() : loggableCalls(){ before() : loggableCalls(){ Logger.entry(thisJoinPoint.getSignature().toString());Logger.entry(thisJoinPoint.getSignature().toString()); }} after() : loggableCalls(){ after() : loggableCalls(){ Logger.exit(thisJoinPoint.getSignature().toString());Logger.exit(thisJoinPoint.getSignature().toString()); }}} }

Page 7: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

Aspectwerkz: runtime Aspectwerkz: runtime bytecode generationbytecode generation

• AspectWerkz provides AOP facilities in the AspectWerkz provides AOP facilities in the form of Java library rather than languageform of Java library rather than language

• The library is capable of manipulating The library is capable of manipulating bytecode inside the class loader for injecting bytecode inside the class loader for injecting aspect code into classesaspect code into classes

• Aspects and join points are connected Aspects and join points are connected through XML filesthrough XML files

• The library supports matching on code The library supports matching on code attributes, the new feature of Java 1.5 attributes, the new feature of Java 1.5 (custom attributes)(custom attributes)

Page 8: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

AgendaAgenda• AOP and Code GenerationAOP and Code Generation• CodeBricks: quick introCodeBricks: quick intro• [a]C#: annotated join points[a]C#: annotated join points• ARE: a generic program rewriting ARE: a generic program rewriting

systemsystem• ConclusionsConclusions

Page 9: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

Code Manipulation Code Manipulation based on methodsbased on methods

Programming language

Intermediate (or machine) language

Real transformation

Perceived transformation

Type T

Type T

Source program

Target program

Page 10: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

Partial application + Partial application + inlininginlining

• CodeBricks library is built around the CodeBricks library is built around the notion of notion of partial applicationpartial application

• Code generation is expressed as Code generation is expressed as partial application assuming that partial application assuming that code is generated relying on an code is generated relying on an inlining strategyinlining strategy

• Code bricks are built around methods Code bricks are built around methods and represent high order valuesand represent high order values

Page 11: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

ExamplesExamplesdelegate int F(int v);delegate int F(int v);delegate int G(int i, int j, int k);delegate int G(int i, int j, int k);public int add(int x, int y) { return x+y; }public int add(int x, int y) { return x+y; }//…//…Code c = new Code(typeof(Add).GetMethod(“add”));Code c = new Code(typeof(Add).GetMethod(“add”));Code inc = c.Bind(1, new Free()); // add(1, _)Code inc = c.Bind(1, new Free()); // add(1, _)Free x = new Free();Free x = new Free();Code twice = c.Bind(x, x); // add(_0, _0)Code twice = c.Bind(x, x); // add(_0, _0)Code threeAdd = c.Bind(c.Bind(new Free(), new Code threeAdd = c.Bind(c.Bind(new Free(), new

Free()), new Free()); // add(add(_, _), _)Free()), new Free()); // add(add(_, _), _)F f = (F)inc.MakeDelegate(typeof(F)); f(2);F f = (F)inc.MakeDelegate(typeof(F)); f(2);G g = (G)threeAdd.MakeDelegate(typeof(G)); g(1, 2, G g = (G)threeAdd.MakeDelegate(typeof(G)); g(1, 2,

3);3);

Page 12: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

High order spliceHigh order splicedelegate void Cmd();delegate void Cmd();void Log(string info, Cmd c) {void Log(string info, Cmd c) { Console.WriteLine(“Enter: {0}”, info);Console.WriteLine(“Enter: {0}”, info); c();c(); Console.WriteLine(“Exit: {0}”, info);Console.WriteLine(“Exit: {0}”, info);}}void SomeWork() { ... }void SomeWork() { ... }//...//...Code log = new Code(typeof(Exmp).GetMethod(“Log”));Code log = new Code(typeof(Exmp).GetMethod(“Log”));Code tgt = new Code tgt = new

Code(typeof(Exmp).GetMethod(“SomeWork”));Code(typeof(Exmp).GetMethod(“SomeWork”));Cmd norm = new Cmd(SomeWork); // Log(“info”, SomeWork)Cmd norm = new Cmd(SomeWork); // Log(“info”, SomeWork)Cmd wlog = (Cmd)log.Bind(“SomeWork”, Cmd wlog = (Cmd)log.Bind(“SomeWork”,

tgt).MakeDelegate(typeof(Cmd));tgt).MakeDelegate(typeof(Cmd));

Page 13: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

AOP with CodeBricksAOP with CodeBricks• Previous example shows how CodeBricks Previous example shows how CodeBricks

can provide before and after code can provide before and after code injectionsinjections

• But you always need to abstract the code But you always need to abstract the code you want to surround into a methodyou want to surround into a method

• The compiler can generate patterns based The compiler can generate patterns based on CodeBricks for aspect waving (this on CodeBricks for aspect waving (this allows for dynamic weaving of aspects)allows for dynamic weaving of aspects)

Page 14: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

AgendaAgenda• AOP and Code GenerationAOP and Code Generation• CodeBricks: quick introCodeBricks: quick intro• [a]C#: annotated join points[a]C#: annotated join points• ARE: a generic program rewriting ARE: a generic program rewriting

systemsystem• ConclusionsConclusions

Page 15: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

Annotations for better Annotations for better join points?join points?

• AspectWerkz shows that code with AspectWerkz shows that code with annotations may help to define annotations may help to define better join pointsbetter join points

• The annotation model of CLR and The annotation model of CLR and JVM is limited to methodsJVM is limited to methods

• Join points are inside methodsJoin points are inside methods• We have extended C# to allow We have extended C# to allow

annotations inside method bodiesannotations inside method bodies

Page 16: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

[a]C#[a]C#public void m() {public void m() {

Console.WriteLine("Parallelizable code sample");Console.WriteLine("Parallelizable code sample"); [Parallel("Begin of a parallelizable block")][Parallel("Begin of a parallelizable block")] { { Console.WriteLine("Code exec by the main thread");Console.WriteLine("Code exec by the main thread"); [Process("First process")][Process("First process")] { { // Computation here// Computation here }} [Process][Process] { { // Computation here// Computation here }} } // Join of processes here} // Join of processes here Console.WriteLine("Here is sequential");Console.WriteLine("Here is sequential");}}

Page 17: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

[a]C# runtime [a]C# runtime operationsoperations

• Operations available at runtime Operations available at runtime are:are:– Annotation tree inspectionAnnotation tree inspection– ExtrusionExtrusion– InjectionInjection– ReplacementReplacement

Page 18: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

[a]C# and AOP[a]C# and AOP• Annotations may help to define pointcutsAnnotations may help to define pointcuts• With code-level annotations With code-level annotations

programmers may declare join points:programmers may declare join points:– AOP systems may get benefit from AOP systems may get benefit from

annotationsannotations– The main source code becomes a little aware The main source code becomes a little aware

of the subsequent code transformationof the subsequent code transformation• [a]C# transformations are performed at [a]C# transformations are performed at

runtime: but what does it means exactly runtime: but what does it means exactly runtime?runtime?

Page 19: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

AgendaAgenda• AOP and Code GenerationAOP and Code Generation• CodeBricks: quick introCodeBricks: quick intro• [a]C#: annotated join points[a]C#: annotated join points• ARE: a generic program ARE: a generic program

rewriting systemrewriting system• ConclusionsConclusions

Page 20: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

Assembly Rewriting Assembly Rewriting EngineEngine

• It is possible to encode information into binaries It is possible to encode information into binaries so that the programmer perceives that the so that the programmer perceives that the information is provided into its own languageinformation is provided into its own language

• A general rewriting system would support A general rewriting system would support several applications in a standard way several applications in a standard way complementing the reflection support already complementing the reflection support already available in STEEsavailable in STEEs

• Because the target program and the Because the target program and the transformation system are expressed in the transformation system are expressed in the same language the program can be specialized same language the program can be specialized by executing its own codeby executing its own code

• AOP systems can rely on this general AOP systems can rely on this general infrastructure for generating their own codeinfrastructure for generating their own code

Page 21: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

SchemaSchema

AR

Stage name

AR AR

Stage nameStage name

Page 22: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

The AlgorithmThe Algorithm• We assume that a program that wants to We assume that a program that wants to

perform a computation at stage perform a computation at stage nn provide some provide some metadata to indicate where and what to dometadata to indicate where and what to do

• Methods handled by the rewriting engine should Methods handled by the rewriting engine should have a known signature: Code have a known signature: Code mm(Context c);(Context c);

• The basic operation is type safe code The basic operation is type safe code replacement of explicitly (annotations) or replacement of explicitly (annotations) or implicitly (method calls) annotated codeimplicitly (method calls) annotated code

foreach (Method m in Assembly)foreach (Method m in Assembly) if (annotated(m, stagename)) replaceCalls(m, a);if (annotated(m, stagename)) replaceCalls(m, a); else if (annotatedbody(m, stagename)) replace(m,a);else if (annotatedbody(m, stagename)) replace(m,a);

Page 23: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

The logger example The logger example revisedrevised

class LogAspect : Transformation {class LogAspect : Transformation { [MethodCall(SomeWork)][MethodCall(SomeWork)] void Log(Context c) {void Log(Context c) { Console.WriteLine(“Entering SomeWork”);Console.WriteLine(“Entering SomeWork”); c.MethodCall();c.MethodCall(); Console.WriteLine(“Exiting SomeWork”);Console.WriteLine(“Exiting SomeWork”); }}}}//...//...void SomeWork() { ... }void SomeWork() { ... }//...//...SomeWork();SomeWork();

Page 24: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

And pattern matching?And pattern matching?• Transformations are expressed on the Transformations are expressed on the

methods using custom attributesmethods using custom attributes• The transformation should be type-safeThe transformation should be type-safe• ARE will not provide general support for ARE will not provide general support for

pattern matching (maybe some restricted pattern matching (maybe some restricted form)form)

• An AOP compiler can anticipate pattern An AOP compiler can anticipate pattern matching and output an appropriate matching and output an appropriate transformation class.transformation class.

Page 25: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

AgendaAgenda• AOP and Code GenerationAOP and Code Generation• CodeBricks: quick introCodeBricks: quick intro• [a]C#: annotated join points[a]C#: annotated join points• ARE: a generic program rewriting ARE: a generic program rewriting

systemsystem• ConclusionsConclusions

Page 26: Aspect Oriented Programming in.NET with CodeBricks Antonio Cisternino Academic Days Milan, 2004 Università di Pisa Supported by Microsoft Research grant

ConclusionsConclusions• CodeBricks aims to become a general CLR CodeBricks aims to become a general CLR

support for meta-programming at runtimesupport for meta-programming at runtime• We have discussed how the typical We have discussed how the typical

transformations of AOP could be mapped transformations of AOP could be mapped on CodeBrickson CodeBricks

• Annotations can help AOP systems to Annotations can help AOP systems to define better join pointsdefine better join points

• A multi-stage code transformation system A multi-stage code transformation system is required to have “before runtime is required to have “before runtime stages”stages”