Stateful aspects can react to the trace of a program execution; they can support modular implementations of several crosscutting concerns like error detection, security, event handling, and debugging. However, most proposed stateful aspect languages have specifically been tailored to address a particular concern. Indeed, most of these languages differ in their pattern languages and semantics. As a consequence, developers need to tweak aspect definitions in contortive ways or create new specialized stateful aspect languages altogether if their specific needs are not supported. In this paper, we describe ESA, an expressive stateful aspect language, in which the pattern language is Turingcomplete and patterns themselves are reusable, composable firstclass values. In addition, the core semantic elements of every aspect in ESA areopen to customization. We describe ESA in a typed functional language. We use this description to develop a concrete and practical implementation of ESA for JavaScript. With this implementation, we illustrate the expressiveness of ESA in action with examples of diverse scenarios and expressing semantics of existing stateful aspect languages.
Trang 1Paul Legera,∗ , Éric Tanterb, Hiroaki Fukudac
aUniversidad Católica del Norte, Escuela de Ciencias Empresariales, Chile
bPLEIAD Lab, Computer Science Department, University of Chile, Chile
cShibaura Institute of Technology, Japan
©2015ElsevierB.V.All rights reserved
1 Introduction
Modularity favors systemevolution and maintenance by allowing separate concerns to be localized [1] Modules are
crucialforraisingtheunderstandability,maintainability,reusability,andevolvabilityofsoftware.However,concernslikegingandeventhandlingcannotbeimplementedinonemodule;theseareknownascrosscutting concerns.Aspect-OrientedProgramming (AOP)[2]allowsdevelopers touseaspects,asembodied ine.g., AspectJ[3],tomodularizecrosscuttingcon-cerns Inthepointcut-advicemodelofAOP[4],anaspectspecifiesprogramexecutionpointsofinterest,namedjoin points,
log-through predicates called pointcuts.When an aspect matches a join point, it takesan action, calledadvice. Typically,anaspectmatchesaprogramexecutionpointinisolation,orinthecontextofthecurrentcallstack.However,themodulariza-tionofsomecrosscuttingconcernsrequiresaspectstomatchatrace ofjoinpoints,e.g., debugging[5],security[6],runtimeverification[7],andeventcorrelation[8].Aspectsthatcanreacttoajoinpointtracearecalledstateful aspects[9]
Several stateful aspect languages have been proposed [6,8,10–15], specifically tailored to address particular domains.Because of thesedomains, theselanguages donot share thesame semantics [15].Some of themlike Tracematches[11]
supportmultiplematches,evensimultaneously,ofajoinpointtracepattern(justpattern fromnow).Eachlanguageprovidesits owndomain-specificlanguage todefinepatternsofinterest.Inaddition,each languagehasits ownmatching semantics
Trang 2to define howa patternis matched, andadvising semantics todefine how an advice is executed Todate,stateful aspectlanguagedesignhasfocusedmostlyonperformance,leavingasidetheexplorationofmoreexpressivenessinthefollowing:
Pattern language Thelackofexpressivenessinpatternlanguageslimitsdevelopersfroma)reusingandcomposingpatternsandb)toaccuratelydefineprogramexecutiontracepatternsthatmustbematched
Semantics In stateful aspect languages, limitedexpressiveness generates two problems in terms ofsemantics: fixed and common semantics forall statefulaspects Byfixed wemean developerscannot customize thematchingandadvising se-manticsoftheaspectlanguage Additionally,ifdevelopersare abletocustomizethelanguage semantics,all aspectsmustsharethesecustomizationsbecausesemanticsiscommon forallaspects
1.1 Contributions
Theproblemsrelatedtothelackofexpressivenessofcurrentstatefulaspectlanguagesserveasmotivationforthiswork,whichproposesaprecisedescriptionofanexpressive statefulaspectlanguage.1 Concretely,thecontributionsofthispaperare:
• Four problems identified Throughthispaperweexposefourproblemsassociatedwithstatefulaspectlanguages.Twoproblemsbelongtothelackofreuse,composition,andexpressivenessofcurrentpatternlanguages.Thetworemainingproblemsarerelatedtothecommonandfixedsemanticsoftheseaspects
• An Expressive Stateful Aspect language (ESA) description Wedescribe astateful aspectlanguage, namedESA,whichaddressesthepreviousproblems.UsingESA,developerscan:
– usefirst-classpatterns,meaningthatapatternisavalueofthelanguage(e.g., function,object)thatcanbecomposed
to other language valuesto create morecomplex patterns First-class patterns offer thebenefits of the reuse andcompositionofpatterns.Apartfromreuseandcomposition,thesefirst-classpatternsallowdeveloperstocleanlyusethefactorydesignpattern[16]tobuildtheirownpatternlibraries.Inaddition,developerscanuseaTuringcompletelanguagetodefinepatterns
– customize thematching andadvising semantics ofevery statefulaspect With this, every stateful aspect can havedifferentsemantics and developerscan customize any aspect.To achieve this goal,we follow open implementation
designguidelines[17],allowingdeveloperstocustomizestrategiesofaprogramimplementation,whilehidingdetails
ofitsimplementation
• A concrete and practical implementation of ESA WeusetheproposeddescriptiontoimplementaconcreteandticalversionofESAforJavaScript,namedESA-JS Thisversion supportsmodern browserssuch asFirefoxandChromewithouttheneedofanadd-on.Inaddition,weimplementESA-AS3,aproofofconceptofESAforActionScript
prac-• A reference frame of comparison To contrast ourproposal withexisting stateful languages,we develop a referenceframethatcomparestheexistingproposalsintermsofexpressiveness.Asaresult,we clarifyanddiscusssomediffer-encesbetweentheseproposals
Paper roadmap Section 2introducesandgoesintodetailonstatefulaspectlanguages.Section 3discussesthestate oftheartoftheselanguages.Evaluations andlimitationsofexistingproposalsare shownthroughvariousexamplesinSection 4.Section5presentsthedescriptionofanexpressivestatefulaspectlanguage;wedescribeESAusingafunctionaltypedlan-guage,TypedRacket [18].Toillustratehowourproposaladdressestheaforementionedlimitations,weuseaconcreteandpracticalimplementationofESAforJavaScriptinSection 6.Section7assessestheexpressivenessofESAthroughtheemu-lationofsomeexisting statefulaspectlanguages.Section 8discussesdesignconsiderations ofourproposal,andSection9
concludes
Availability ESA-JSandESA-AS3alongwiththeexamplespresentedinthispaper,isavailableonlineathttp://pleiad.cl/esa.ESA-JScurrentlysupportstheFirefox,Safari,Chrome,andOperabrowserswithouttheneedofanextension
2 Architecture of a stateful aspect language
Stateful aspects [9] support the modular definitionof crosscutting concerns for which matching join point traces, asopposedtosinglejoin points,isnecessary.InAspect-OrientedProgramming (AOP)[2],joinpoints aretheeventsthatcan
begatheredbyanaspect,andthevarietyoftheirtypes(e.g., methodcalls,objectcreations)dependsonthejoinpointmodelsupportedbytheaspectlanguage [4].AsFig 1shows,astatefulaspectiscomposedofa(joinpointtrace)patternandanadvice.The adviceisexecutedbefore, around,orafter thelast joinpointthat mustmatchwiththepattern.Dependingonthedeploymentstrategyused,astatefulaspectmayreactfromaparttoallhistoryofaprogramexecution.2
1 This work extends and refines our previous work on open trace-based mechanisms, discussed in Section 3
2 Although the concrete implementation of our proposal uses different deployment strategies (Section 5 ) [19] , the discussion of these strategies is beyond this paper.
Trang 3Fig 1 The anatomy of a stateful aspect and main processes of its language.
Fig 2 A program execution that triggers an exception if Enumeration supports fail-fast.
Overthenextthreesections,wedescribeandillustratethecoreelementsoftheselanguages:patternlanguage,matchingprocess,andadvisingprocess.Toillustrate,weusearuntimeverificationexampleimplementedinJavaMop[15],agenericstateful aspect framework for Java.Patterns in JavaMop can be expressedin differentdomain-specific languages: regularexpressions, context-free grammars,lineartemporallogic,etc Anaspectin thisframework iscomposed ofasetofeventdeclarations,apattern,andapieceofcode.Aneventdeclarationrepresentsasetofjoinpoints.Thepatternisdefinedovertheseevents,andthepieceofcoderepresentstheadvice
failFast (Vector v , Enumeration e) {
/ / events
event create after(Vector v) returning(Enumeration e):
call (Enumeration Vector elements()) && target(v) {}
event addVector after(Vector v): call(∗ Vector add∗( ) ) && target(v) {}
event nextEl before(Enumeration e): call(∗Enumeration.nextElement()) && target(e) {}
/ / pattern , ’ ere ’ means that the pattern i s defined by a regular expression
ere: create nextEl∗addVector+ nextEl
/ / advice
@match {
throw new ConcurrentModificationException ( );
} }
TheJavaMopstatefulaspectaboveprovidesthefail-fast featureforthe Enumeration interface,whichtriggersanexception
iftheunderlyingenumerationismodified whileaniteration isinprogress.InJavaMop,theaspectdeclarationstarts withits name,e.g., failFast.Next,eventsare declared.Todefine thepattern,a developerfirstselectsapatternlanguage withakeyboard(e.g., ere),thenapatternisdefined.Fig 2illustratesthissituationthroughtheexecutionoftwothreads,where e
isanenumerationoveravector v.InLine3ofthread2, v addsanewobject,triggeringanexceptionbeforethenextcallofnextElementinthread1
2.1 Pattern language
Astatefulaspectlanguage usesadomain-specificlanguagetodefinepatterns.Somepatternlanguagesallowdevelopers
to specify bindings that are gatheredwhile a pattern is beingmatched For example,patterns of Tracematches[11] are
Trang 4Fig 3 Twomatches of the pattern used forfail-fast.In the figure, the match of up side gathers the bindings v1 and e1, and the match of down side gathers the bindings v2 and e2.
definedas regular expressions andcan gather bindings Instead,PTQL [12] uses a SQL-like language toexpress patterns,wherebindings arespecifiedinthe SELECT statement.Gatheredbindings canbe usedtofilterunwantedmatchesofthepatternandgive context informationto theexecutionof advice.This section definesa patternlanguage andexplainsitsmainfeatures
Definition (Pattern language). A language that allows developers to specify the join point trace pattern that should bematchedbyastatefulaspect
Asthe failFast aspectcodeshows,inJavaMop,bindingsgatheredare specifiedintheheader Inthispieceofcode,twobindings: a vector v and its enumeration e When an eventof the patternis matched, a binding can be gathered; forexample, v isgathered when create ismatched As weneed to catchunsafe uses ofenumerations, thepatternfirst seesthecreationofanenumerationthenzeroormore nextElement calls,oneormore addElement calls,andfinallyanerroneousattempttocontinuetheenumeration
2.2 Matching process
Inmostexistingproposals,thematchingprocessimplementationisinsideofthestatefulaspectlanguage.Thedefinition
ofitsprocessandoftheimpactofitschosensemanticsareexplainedinthissection
Definition (Matching process).Aprocess thattriesmatchingagivenpatternagainstthecurrentjoin pointtrace according
toitssemantics
Fig 1showsthatwhenastatefulaspectisdeployed,theaspectlanguageusesitsmatchingprocesstomatchtheaspectpattern Dependingonthesemanticsofthisprocess,a patternmaymatchmultipletimes.Weusetheimplementationofthefail-fast featuretoillustratethisprocess
Thematchingprocess ofJavaMop,likemostexistingstateful aspectlanguages,supportsmultiplematches Particularly,JavaMop cansupport multiplematches ofa pattern, iftheenvironment ofbindings gathered bypotential matches ofthepatterndiffersbetweenthem.Forexample,Fig 3exemplifiesthissemanticsbecausethepatternmatchestwice(represented
by dottedcontinuation lines)dueto thefact thattheenvironments ofboth matches, v=v1 , e=e1 and v=v2 , e=e2 ,differ
fail-fast: ifa vector removesan element between hasMoreElements and nextElement invocations, an exception is thrown
In thisvariant,we haveadded two stateful aspectinstance variables, vec and enum,that are bound to thevector v andenumeration e respectively when the create event is matched In JavaMop, instance variables allow developers to linkbindingsfromthematchingtotheadvisingprocess
restrictedFailFast (Vector v , Enumeration e) {
Vector vec;
Enumeration enum;
Trang 5Fig 4 Twosimultaneous matches of the pattern of the restrictedfail-fast.In the figure, the match of up side gathers the bindings v1 and e1, and the match
of down side gathers the bindings v1 and e2.
event create after(Vector v) returning(Enumeration e):
call (Enumeration Vector elements()) && target(v) {vec = v; enum = e;}
event nextEl before(Enumeration e): call(∗Enumeration.nextElement()) && target(e) {}
event hasMore after(Enumeration e) : call(∗Enumeration.hasMoreElements()) && target (e) {}
event removeVector before(Vector v): call(∗ Vector removeElement( ) ) && target(v) {}
ere: create hasMore removeElement
thesamepieceofcodegivenasadvice
3 Existing stateful aspect languages
Douenceetal.[9,20]initiatedthebodyofworkonstatefulaspects.Inaddition,thereisalargebodyofworkonstatefulaspects,whichwereviewinthissection.Foreachproposal,wefocusonthreecomponentsdescribedintheprevioussection
Tracematches TheTracematchesproposal,implementedasanAspectJ[3]extension,isanefficientstatefulaspectlanguageforJava Theproposalonly allowsdevelopers tousea regularexpression language todefine patterns.Its patternscannot
be reused orcomposed The matchingprocess is implementedthrough a nondeterministicfinite-state automaton,whoseactive statescorrespondtopotentialmatches ofa pattern.Theadvisingprocess supportsbefore,around,andafteradvice.Forthearoundadvice,TracematchesfollowtheAspectJguidelines:whentherearetwoormorematchesofapatternwiththesamejoinpoint,theadviceexecutionsarechainedandnested
Tracecuts TheTracecutsstatefulaspect [21]isalanguage thatworksforJavaasanAspectJextension.Thismechanismisusedtocheck theuseofprotocols(e.g., FTP[22],a communicationprotocol).InTracecuts,ifthejoinpointtrace doesnotfollowapattern,whichrepresentsacertainprotocol,anactioncanbetriggered.AccordingtotheauthorsofTracecuts,thecheckingofsomeprotocolsneedstoproperlyidentifythenestedentriesandexitsoftheexecutionsofdifferentmethodsof
a class.Thisfeatureisreducibletorecognitionofproperlynestedparentheses, meaningthatafinitestatemachinecannotcorrectly check theuseof theseprotocols.Therefore, Tracecutsallow developersto expresspatternsusing a context-free
Tracematches
Alpha Alpha[14]isanaspect-orientedextensionofL2,asimpleobject-orientedlanguageinthestyleofJava.AlphausesPrologqueriestoexpresspatterns.Thematchingprocessisimplementedthroughqueriestoadatabasethatcontainsinfor-mationaboutthestaticrepresentation(e.g., abstractsyntaxtree)andthedynamicrepresentation(i.e., executiontrace)ofaprogram Thematchingprocess correspondsto theinternalprocess ofProlog(i.e., abackward chainingalgorithm [23]) toanswer a query.Everysolution toa Prologquerycorresponds to amatchof apattern Thesesolutions arepassed to theadvisingprocess,whichonlysupportsbeforeandafteradvicekinds.Advicesareexecutedinaconsecutivemannerforeachsolution,whichcontainsasetofgatheredbindings
Halo Herzeel etal.[13]proposeHalo,aCommonLispextension.TheHaloproposalallowsdeveloperstousealmost allthebaselanguagetoexpresspatternsbecauseloopsandrecursionsarenotallowed.Despitetheselimitations,Halopatternsarefirst-classvalues.ThematchingprocessisimplementedwiththeRetealgorithm[24],anefficientpatternmatchingalgorithmused forexpertsystems[25].InRete,patterns arerepresented asrules that mustbe satisfiedby aset of(matched)join
Trang 6points The advisingprocess onlyexecutes theadvice witheach setof bindings that satisfythe rules Theadvice can beexecutedbeforeorafterthelastmatchedjoinpoint.
EventJava EventJava[8]allowsdeveloperstoexecuteapieceofcode(i.e., advice)whenasetofdistributedevents(i.e., join
points)hasacorrelationspecifiedbydevelopers.Tospecifythecorrelation,everydistributedeventcontainsasetofertiesavailabletodevelopers(e.g., thetimeatwhichtheeventisobserved).TheEventJavapatternlanguageonlysupports
prop-an adhoc for and if constructs tocomparetheseevents.No user-defined constructstocompareeventsaresupported Forthematchingandadvisingprocesses,EventJavafollowsthe sameguidelinesofHalo,buttheadvicecan onlybe executedafterthelastjoinpointismatched
AWED It is a language for Aspects WithExplicit Distribution (AWED) [5,26] This stateful aspect language supports themonitoringofdistributedcomputationsinJava.Inaddition,thisaspectlanguagetakesintoconsiderationdistributedcausalrelationsintasksofdebuggingandtestingofmiddleware.AWEDpatternsare expressedusingadomain-specific languageforregularexpressions.SimilartoTracematches,thematchingprocessusesafinitestatemachinetocarryoutthematching
ofpatterns.Fortheadvisingprocess,AWEDfollowsthesameprocessofEventJava
PQL ProgramQueryLanguage(PQL)[6]isatooltodetecterrorsandcheck/forceprotocolsofprogramming(e.g., filedling).Thistoolusesastaticanalyzertoreducethepossiblematchesandthenusesadynamic matcher thatreallymatches
han-agivenpattern.AdeveloperexpressesapatternusinganASTdescription(usingaJava-likesyntax).Thematchingprocess
(i.e., dynamic matcher)usesa specializedstatemachine Theadvice canonlyusethe execute, whichisusedto executeamethodbefore thelast join pointmatched, or replace,used toreplace theoriginal computation ofthe lastmatched joinpoint
PTQL Program Trace Query Language (PTQL) [12] is another tool to detect errors Developers use the SQL language toexpressapattern,whichisactuallyaSQLquery.Joinpointsarestoredindatabases,whichareusedbyitsmatchingprocess,namedPARTIQLE,tomatchaquery.PTQLdoesnotallowdeveloperstotakeactionsifapatternismatched,i.e., thereisnoadvisingprocessinPTQL
JavaMop JavaMop [15,27,28]is a generic and efficient runtime-verification framework forJava Patterns in JavaMop can
be expressedin different(previouslydefined)domain-specific languages:regular expressions, context-free grammars,ear temporallogic,stringrewriting system[29],etc Thislast patternlanguage isTuringcomplete.However, theJavaMoppatternsarenotfirst-classvalues,reusable,andcomposable.Afixedsetofmatchingprocesssemanticsisavailable forthedevelopers.AsJavaMop compilestheir codetoAspectJcode,theJavaMopadvisingprocess followsthesameguidelinesofAspectJforthisprocess
lin-EventReactor Eventcompositionmodel[30]isacomputationalmodelthatisbasedonthedefinitionsofsoftwareconcerns
as event modules. An eventmodule groupsa set of events,i.e., join points, that are relatedto a concern and can react
to this set ofevents The software construction is achieved through the composition of theseevent modules, where aneventmodulecan be composedusing input(events received)andoutput (eventspublished)interfaces.EventReactor [10,31,32]providesasetoflanguageconstructstoimplementtheeventcompositionmodel.Theproposalcanbeimplementedfor multi languageslike Java and C Similarly to JavaMop, patterns in EventReactor are expressed in a user-defined andpotentiallyTuringcompletelanguage,butthesepatternsarenotfirst-classvalues,reusable,andcomposable.Thematchingprocesssupportsmultiplematches,whichcanbespecializedperthread.InEventReactor,asaneventcanbe“beforecalling
toafunction”andtheadvisingprocesscanreacttoanyeventdescribedbyaneventmodule,theadvicekindofEventReactorsupportsbefore and after.
OTM Thispaperisnotourfirstattemptatimplementinganexpressivestatefulaspect.In[33,34],weimplementastatefulaspectlanguage forJavaScript,namedOTM TheOTMpatternlanguage isTuringcomplete andallowsdevelopersto reuseandcomposepatterns.Althoughthe matchingprocessof anyOTM stateful aspectcan becustomized, developershavetoupdate the definitions oftheir patternsto support a particular customizationof the matchingprocess For example,thedefinitionofa patternforthesingle matchingsemantics differs fromthedefinitionofthe samepatternforthemultiplematching semantics.In other words, thematching process doesnot really customizethe semantics, ratherthe power ofthepatternlanguageallowsdevelopersto “codearound”patternstoachieve therequiredsemantics.The advisingprocesscannot be customized in OTM In [35], OTM is extended to control causal relations among Ajax messages in JavaScriptapplications
Fig 5sumsup thereviewsofstatefulaspect languagesanalyzedinthispaper.Moststateful aspectlanguagesprovidedifferentpatternlanguages,wherethelanguageexpressivenessvaries.Forinstance,AlphausesProlog,PTQLusesSQL,andTracecutsusescontext-freegrammars.Regardingthematchingprocess,alltheseaspectlanguagessupportmultiplematches
ofapattern.Similartopatternlanguages,semanticsofmatchingprocessesofexistingstatefulaspectlanguagesvaryaswell.Forexample,JavaMop[15]allowsdeveloperstochooseoneofthreefixedspecificationsforthematchingprocessforeverystatefulaspect.Finally,mostadvisingprocessesofstatefulaspectlanguagesonlysupportbeforeandafteradvice
Trang 7Fig 5 Summary of stateful aspect languages discussed in this section.
4 Shortcomings of existing stateful aspects
This sectionillustrates currentshortcomingsofexisting statefulaspect languages.Forthisillustrationwe focusonthethree componentsdescribed inthispaper:patternlanguages,matching process,andadvisingprocess Eachcomponentisevaluated withregard tofourproblemsmentionedintheintroductionofthispaper.Toclearlyidentifyeveryproblem,weassignaidentifier:
•PatternLanguages:
– p1 istheinability to reuse and compose patterns.
– p2 isthelimited expressiveness todefinepatterns
•MatchingandAdvisingProcesses:
– s1 isthefixed semanticsofstatefulaspects
– s2 isthecommon semanticsforallstatefulaspects.Anaspectlanguagewithcustomizablesemantics(i.e., s1 solved)
doesnotaddresstheproblems2 ifthesecustomizationsareatlanguagelevelbecauseallaspectswouldsharethesesemanticvariations
Considering the same components and problems mentioned above, this section also evaluates and compares statefulaspect languagesdescribed in Section 3 Thissection concludesdescribing requirementsto achieve an expressive statefulaspectlanguage
4.1 Illustrating shortcomings of stateful aspect languages
Toillustrate thefourproblemsmentionedabove, weusevariants oftwodifferentapplicationsofa statefulaspectproach:
ap-Toggle airplane mode Intouchdevices,atoggle airplane mode featureallowsuserstoenable(ordisable,ifitwasenabled)theairplanemode.Supposeausercanusethisfeaturewiththesequenceup, down,andup inthetouchdevice.Thefollowingaspectimplementsthisfeature:
Trang 8toggleAirplaneMode() {
event s−up after (): call (∗ Screen up()) {}
event s−down after (): call (∗ Screen down()) {}
acomputerisonlyvalidforaperiodoftime.However,thisdiscountmustbeapplied(evenifitisnotvalidanymore)whentheclientchecksout.Implementingthisdiscountpolicyisacrosscuttingconcernthatcanbemodularizedusingastatefulaspectasfollows:
discountPolicy(Computer c , User u) {
Computer comp;
User user;
event add after(User u,Computer c ): call(∗ Cart add(User,Computer))
&& args(u, c) {user = u; comp = c;}
event checkout before(User u): call(∗Form checkout(User)) && args(u) {}
ere: add checkout
@match {
Cart cart = this user getCart ( );
cart applyDiscount(this comp, DiscountPolicy getDiscount(this comp));
toreusethepatternofthepreviousfeature.However,moststatefulaspectlanguageslikeJavaMopdonotallowdevelopers
toreuseandcomposepatterns,i.e., problem p1.Itisthereforenecessarytowriteallofthepatternagain:
toggleAirplaneModeWithTime () {
/ / events as in toggleAirplaneMode
event s−left after (): call (∗ Screen left ()) {}
ere: s−left s−up s−down s−up / / a l l pattern was defined again
@match{
Device toogleAirplaneMode(10∗60∗60); / /10 hours
} }
Thepieceofcodeaboveisnoteasilymaintainable,becauseifthepatternof toggleAirplaneMode changes,itisnecessary
torewritealltheofpatternof toggleAirplaneModeWithTime
Problem p2 Apartfromthelackofreusingandcomposingapattern,thelimitedexpressivenessdoesnotallowdevelopers
to directlydefine patternsthat gather a variablelistof bindings:problem p2 isan exampleof this Consider avariation
ofthe currentdiscountpolicy,named limited discount policy. Thisvariationonly appliesthe discountstothree computersthathavethebestassociateddiscounts.Thissmallvariationcannotbeimplementedasanupdateofthesolutionpresented
Trang 9Fig 6 Four simultaneous matches of the pattern used to implement the discount policy feature, where a user u1 buys four products: c1, c2, c3, c4.
previously.Thisissobecausethecurrentsolutiondoesnotuseonlyonematchthatcontainsalistwithallcomputers(see
Fig 6), which isnecessary forchoosing the best discounts Astateful aspect that matches a list ofcomputers wouldbeadequate,however,mostoftheselanguagesdonotallowdeveloperstodefineapatternthat gathersavariable-sizelistofbindings.Areadermightwonderifthefollowingpieceofcodecanwork:
limitedDiscountPolicy(User u, List l ) {
/ / discountPolicy code
}
Thispieceofcodeabovegathersalistinsteadofcomputers.Thissolutiondoesnotworkbecausethelistofcomputers
isnot availableinthepieceofcodeofthebaselanguage.Althoughthislistwouldbeavailable, thislistwouldbeuselessbecause we cannot know whichcomputers were added to the cart before the period of time of an associated discountfinishes.Therefore,weneedtocodearoundthecurrentadvicetoimplementtheupdateofthisfeature:
limitedDiscountPolicy(User u, Computer c) {
int computerCounter = 0;
ArrayList computers = new ArrayList ( );
/ / instance variables , events , and pattern as in limitedDiscount
@match {
if (this computerCounter++ < this u getCart ( ) size ())
this computers.add(this comp); / / adding to the l i s t of computers
else {
ArrayList computersWithBestDiscounts = getBestDiscounts(this computers);
/ / executing the original advice with every computer of the previous l i s t
}
} }
The original advice is only executed when the final match is triggered In addition, the new advice is now stateful
becauseofitsmutablebindings, computers and computerCounter.Thebehaviorofstatefuladvicesdependsonbindingsthatare outside ofit Therefore,developers keep inmind thestate ofouter bindings to knowthe realbehavior of a statefuladvice.Although,inJavaMop,weuseaTuringcompletepatternlanguagelikestring rewriting system[29],thisadvicehasto
bemodifiedincontortivewaysaswell.ThisisbecauseavailablepatternlanguagesinJavaMoparesufficientlyexpressivetospecifyajoinpointtrace,butnotexpressiveenoughtospecifywhatandhowbindingsaregathered,e.g., avariablelistofbindings
4.1.2 Matching and advising processes
In thissection, we firstillustratetheproblem s1 throughan examplerelatedtothe advisingprocess.We thenuseanexamplerelatedtothematchingprocesstoexemplify s2.
Problem s1 Inanadvisingprocess,iftherearesimultaneousmatchesofapattern,theadviceisexecutedseveraltimes:eachonewithanenvironmentofbindings.Existingstatefulaspectlanguagesdonotallowdeveloperstocustomizetheadvisingprocess, i.e., problem s1.Acustomizable advisingprocess semanticsisnecessary inscenarios likeaddinganewvariation
to the discount policy Suppose thestore Web applicationnow allows clients to customize thepieces (i.e., hardware)oftheir computers Thereby,thestore establisheda newdiscount policy,named personalized discount policy.Thisnewpolicyestablishes that the discount policy only applies the discount to the computer with the greatest number ofcustomizedpieces In thisscenario, it is not possibleto overburdenthe patterndefinition to implementthisrestriction because thetotal numberofpiecesofeverycomputer isonlyknownwhenaclientgoestocheckout Theimplementationofthisnewdiscount policy extension requires the stateful aspect to execute the advice only once, withthe matchwhose bindingsgatheredcontainthecomputerwithmorecustomizedpieces:
personalizedDiscountPolicy(User u, Computer c) {
int maxCustomizedPieceNumber = 0;
int computerCounter = 0;
int computerSelected;
Trang 10Fig 7 Two matches of airPlaneMode due to semantics of multiple matches.
Fig 8 A correct implementation of toggle airplane mode with JavaMop needs a special keyboard.
/ / events and pattern as in discountPolicy
@match{
Cart cart = this user getCart ( );
/ / select the computer with the more customized pieces
if (this maxCustomizedPieceNumber < getCustomizedPiecesNumber( this comp)) {
this maxCustomizedPieceNumber = getCustomizedPiecesNumber( this comp);
this computerSelected = this comp;
}
if (++this computerCounter == cart size ())
/ / executing the original advice for "computerSelected"
} }
As we have seen before, coding around the advice is the most used option forthe currentspectrum ofstateful pectlanguages.In thispieceofcode,theoriginal adviceisonlyexecuted once,whichuses computerSelected toapplythediscounts
as-Problem s2 Althoughthepatternoftoggle airplane mode implementationlookscorrect,thispatterndoesnotworkbecausemoststatefulaspectlanguagesperformmultiplematchesofapattern Asaresult,oncethepatternismatched,each sub-sequentup and down togglestheairplanemode.Fig 7showstheprevious pointwhereobservethatbeforethefirstmatch
ofthepatternfinishes withthecalltotheup function,newpotentialmatchesofthepatternstart.Althoughsemanticsofmultiplematchesisusefulinmanycases(e.g., fail-fast and discount policy),thissemanticsisnotadequateinallcases:prob-lems2.Particularly,JavaMopsuppressesmultiplematchesofapatternifthisdoesnotgatherdifferentbindings;therefore,the toggleAirplaneMode patternonlymatchesonceinthewholeprogramexecution Touseasemanticslikesingle match at
a time,aprogrammerhastotweaktheaspectdefinition.Inthe toggleAirplaneMode implementation inJavaMop,anad-hockeyboard, RESET, hasto be used insideof theadvice This keyboardreinitializes the stateful aspect patternto matchagain(seeFig 8):
Trang 11Fig 9 Evaluations of some stateful aspect proposals regarding their pattern language, matching and advising processes.
oneoftheprevioustwoproblems.Halousescomposableandreusablepatterns,butitspatternlanguageislimitedbyafixedandsmallsetofpatterns.JavaMopandEventReactorallowdevelopersto createdomain-specific languages,whichmaybeTuringcomplete,however,theirpatternsarenotfirst-classvaluesandreusable
Regarding thematching process,JavaMop, EventReactor,andOTMsupport semanticvariations fortheir aspects
(prob-lem s1).Finally,weobservethereisnosupporttocustomizethestatefulaspectlanguagesemantics.Atthebottomofthelist,weseethatESA,theproposalofthispaper,completelyaddressesthefourproblems
4.3 Requirements for an expressive stateful aspect language
We havepresentedmanyexamplesthatillustratedifferentkindsoflimitationsofexistingproposals.Inouropinion,toovercometheaforementionedlimitations,itiscrucialtoconsideranexpressivepatternlanguageandcustomizableseman-ticsperaspect(seeFig 10):
Expressive pattern language ATuringcompletelanguage allowsdeveloperstoexpressadvancedpatterns,e.g., patternsthatgather a variable-sized listof bindings.In addition,first-class patternsare usefulforcleanly reusingandcomposing pat-terns
Customizable semantics UnlikeFig 1,Fig 10showsthateach statefulaspectcontains itsmatchingandadvisingprocesses.Using thisnewapproach,eachaspectcan haveits ownsemantics,whichshouldbeaccordingtoitstarget concern(prob-
lem s1).Inaddition,thefigureshowsthat developerscancustomizetheaspectsemantics(problems2), andnotchooseaparticularsemanticsfromapre-definedsetofsemanticsavailableinastatefulaspectlanguage
Trang 12Fig 10 Requirements for Expressive stateful aspect language: a) an expressive pattern language and b) customizable semantics per stateful aspect.
5 ESA
Thissectionpresentsthedescriptionofourexpressive statefulaspectlanguage,namedESA.Weuseatypedfunctionallanguage,TypedRacket[18],topreciselydescribeESA.Forreadingcomprehensionreasons,someimplementationdetailsofTypedRackethavebeenomitted(Appendix Ashowsthesedetails)
ESA overview TosatisfytherequirementsofSection4.3,thisdescriptionallowsdeveloperstoimplementastatefulaspectlanguage, whosepatternlanguage isTuringcomplete andthe semanticsofeach stateful aspectiscustomizable.The cus-tomization ofsemantics per aspect maybe an extra complexity fordevelopers becauseit requires a detailedknowledge
ofaspect language implementations.Toaddress thiscomplexity,we useopen implementations [17] –usefulprogrammingguidelines that suggest intuitive default semantics fora program For customizations, these guidelines suggest that ab-stractions used must not depend on a specific implementation of the program, meaning that customizations should be
self-contained:theycanbeunderstoodandimplementedinanisolatedmanner
Inthefollowingtwosections,wefirstintroducetheESApatternlanguage,andthenexplainhowESAallowsdevelopers
tocustomizestatefulaspectsemantics.Althoughstatefulaspectlanguagescommonlyusearichjoinpointmodel(e.g., call
join points,executionjoin points,field write joinpoints, etc.), wewill onlyfocusonfunction-call joinpoints asthey aresufficientfordescribingESA
5.1 Pattern language
In the standard formulation vision of the pointcut/advice model,a pointcutis a function that matches a single joinpoint.ThedescriptionbehindtheESApatternlanguageisanaturalextensionofthepointcut-advicemodel.Weexplainthisaffirmationintwoparts.Inthefirstpart,patternscouldnotbeusedtogatherbindings.Inthesecondpart,theESApatternlanguageisextendedtosupportdefinitionsofpatternsthatgatherbindings
Unlikemostexisting approacheswherea patternisa specification(e.g., regularexpression), the ESApatternlanguageapproachusesafunctionthatcantakeactions (e.g., match).Thisapproachisinspiredbycontinuation-passing style[36].As
anexampleofourapproach,theimplementationofapatterntomatchacalltothe up functioninatouchdeviceis:
Trang 13Fig 11 How a pattern is consumed during its matching.
(: s−up Pattern) ; ;Pattern is the type name for "JoinPoint−> Boolean U Pattern"
(define (s−up jp)
(eq? jp up))
The function above returns true if it matches the call to the up function; it returns false otherwise The first line isusedtodefine thetypeofafunctioninTypedRacket;inthiscode,thetype of s-up is Pattern.The lastlinecomparesthereferencesbetween up and jp,where jp isthefunctionreferencethatiscallingatthatmoment.Inthepieceofcodeabove,thepatterncanneverreturnapattern,meaningthatthepatternbehaviorisequivalenttoapointcut
(: call (Procedure−> Pattern ))
(define ( call fun)
(λ(jp)
(eq? jp fun)))
(defines−up ( call up))
(defines−down ( call down))
We canusehigher-orderfunctionstodefine patternsdesignators(i.e., functionsthat returnpatterns),whichallowveloperstoreusecodeandsimplifythedefinitionsofpatterns.Forexample,thepieceofcodeaboveshowsthedefinition
de-ofthepatterndesignator call anditsusetodefinethepatterns s-up and s-down
1 (: seq (Pattern Pattern−> Pattern ))
2 (define (seq left right )
3 (λ (jp)
4 (let ([ result ( left jp )])
5 (cond
In ESA pattern language, we can compose patterns For example, the piece of code above is the implementation ofthe seq pattern designator, whichis used to matcha sequence oftwo patterns The returned patternby seq is used tomatcha sequenceof a left patternfollowed bya right pattern Thepiece ofcodeabove showsthat depending onthe leftevaluation, differentvaluesarereturned.If left evaluation returnsanotherpattern, asequencepatternthatiscomposedofthecontinuationof left and right is returned(Line 6) If left evaluationreturns #t (i.e., true), right isonlyreturneddueto leftmatched completely(Line 7).Finally,if left doesnotmatchthecurrentjoinpoint, false isreturned (Line 8).Noticevaluesreturnedonthelines 6and 7arepatterns,whichspecifythenextjoinpointsthatmustbematched
(: toggle−airplane−mode Pattern)
(definetoggle−airplane−mode (seq s−up (seq s−down s−up)))
We illustrate the useof seq to define the patternof the toggle airplane mode feature. Fig 11 showshow the
execution trace Thispattern changes every time it matches a join point, notice a pattern is drawn withnon-filled angle.Inthebeginning,thepatternbeginswiththepatternexpressedbyaprogrammer.Forthefirstcallto up,thepatternchanges tothepatterns-downs-up.Withthe down call,thepatternchangestoonly s-up.Finally,oncetheusertouchesthescreen,thewholepatternmatches
tri-Usingourpatternlanguage,wecaneasilyreusepatternstocreateadvancedones.Forexample,thepieceofcodebelowshowsthe pattern timed-toggle-airplane-mode,which reuses toggle-airplane-mode.Inaddition,the pieceofcode showstheseqn patterndesignator,whichreuses seq to createapatternthat matchesa variable-sizesequenceof patterns.The foldlfunction,alsoknownas reduce and accumulate,processesalistofpatternsintheleftordertoreturnanewpattern.(: timed−toggle−airplane−mode Pattern)
(definetoggle−airplane−mode−with−time (seq ( call left ) toggle−airplane−mode))
Trang 14Fig 12 Evaluation of a pattern and its potential kinds of results.
(: seqn ((ListofPattern) −> Pattern ))
(define(seqn patterns)
( foldl (λ (pattern acc−pattern) (seq acc−pattern pattern ))
( f i r s t patterns) ( rest patterns )))
5.1.2 Gathering bindings in a environment
The previous description ofour pattern language is incomplete because a pattern cannot gather bindings while it ismatching.Pointcutsandpatternsshouldbeabletogatherbindings.Thestandardandcompletevisionofthepointcut-advicemodelestablishes apointcutasa function Pc:JoinPoint →Env
False Thisdefinitionmeansthat apointcutreturns anenvironment ofbindings (instead of true)ifthe pointcutmatches the currentjoin point.The ESApatternlanguage is anextensionofthestandardpointcut-advicemodelbecauseapatternisafunction:
Pattern:JoinPoint×Env→Env
False
Pattern×Env
A pattern now also takes an environment as a parameter As Fig 12 shows, this environment contains the bindingspreviouslygatheredbyapattern.Likepointcuts,apatternreturnsanenvironment whenitmatches.Inaddition,a patterncan return a pair(instead ofa pattern only) composed of another patternand an environment ifthe evaluated pattern
progresses initsmatching.Toexemplifytheextensionofthepatternlanguage,weredefinethepatterndesignators call andseq:
(: call (Procedure−> Pattern ))
(define( call fun)
(λ (jp env)
(if(eq? jp env) env #f )))
1 (: seq (Pattern Pattern−> Pattern ))
2 (define(seq left right )
4 (let([ result ( left jp env)])
5 (cond
7 [( pair? result ) (cons (seq (get−pat result ) right ) (get−env result ))]
Weillustratethepowerofourpatternlanguagethroughanenhancementofthefeaturetoggle airplane mode.Thisfeature
isnowtriggeredonlyifthetraceupdownup isperformedwithinofatimeintervaloffiveseconds:
(definefast−toggle−airplane−mode
(seqn ( l i s t (bind s−up ' t0 get−time)
Trang 15Fig 13 a) Theleft cell creates a cell that expects to match the next join point and gathers bindings.b) Whena cell matches the last join point specified
by a pattern, the cell creates amatch cell.
(cond
[(Env? result ) (add−env result id (proc))]
[elseresult ] ) ) ) )
; ;where 'time−diff ' is
(define (time−diff pattern t1 t0 time)
(λ (jp env)
(let ([ result (pattern jp env)])
(if(and(Env? result ) (< (env−lookup result t1) (env−lookup result t0) time)))
env result )))
To express the fast-toggle-airplane-mode pattern, we define two reusable and composable patterns: bind and time-diff.Thefirstpatternbindsavaluewhenthepassed patternmatches.Thesecondonechecksthetimedifferencebetweentwobindingsstoredintheenvironmentwhenthepatternpassedasargumentmatches
5.2 Semantics
Inmoststatefulaspectlanguages,aspectsofalanguagesharethesameexactsemantics[6,8,11–14].InESA everystatefulaspectsharesthesamedefaultsemantics,whichcanbecustomizedbydevelopers.Inordertofollowtheguidelinesofopenimplementations,weusedifferentandindependentabstractionsofanyparticularstatefulaspectlanguageimplementation.Indeed,we useMatcherCells[37],aflexible algorithmtomatchprogram executiontraces.Inthissection,wefirstexplainthepreviousalgorithm,andwethenusetoopenitthesemanticsofastatefulaspect
5.2.1 MatcherCells
Toflexiblymatchjoinpointtraces,MatcherCellsuseself-replicating algorithms[38],algorithmsthatemulatethereactions
ofasetofbiologicalcells toatraceofreagents.Topersistintheenvironment,thereactionofacelltoareagentcanbethecreation ofan identicalcopyofitselfwithasmallvariation,nothing,death, orsome ofthesecombinations.An algorithmthat followsself-replicatingbehaviorisdefinedbya pair,wherethefirstelementisthesetoffirstcells(a.k.a seeds)andthesecondoneisthesetofrulesthatgovernstheevolutionofthesecells
MatcherCells terminology AsMatcherCellsisinspiredbybiology,thissectionusesbiologicaltermstoexplainit.Forexample,this section usesterms asreagents torefer tojoin points, cells fordifferentstates ofapotential matchof apattern, and
match cells formatchesofthepattern.Afterthissection,wewillkeepAOPterminology
InMatcherCells,acellcontains thepatternofastatefulaspect,bindingsgatheredduring thematching,andareference
to itscreator Cellsreacttojoin points,which correspondtoreagents.Usingtheexampleofthediscount feature, Fig 13ashowsthat ifa cellmatches a joinpoint, thiscellcreates anewcell that expectstomatchthenext join point specified
by thepattern Inaddition,thisnewcellcontainsanenvironmentofbindingsgatheredwhenthejoinpointwas matched
Fig 13bshowsthatwhenthereisnonextjoinpointtomatch,amatch cell iscreatedtoindicateamatchofapattern.Using theexample ofthetoggle airplane mode feature, we illustratethematching ofapatternin MatcherCells.Fig 14
showstheevolutionfromaseed,whichcreatesasetofcellsduringajoinpointtrace.Thefigurealsoshowsthatthereisamatchcellwhenthecellwiththes-up patternmatches.Asthecellwiths-up isneverkilled,eachsubsequentup joinpointwilltriggeranewmatchofthepattern(anunwantedsemanticsfortoggle airplane mode).
MatcherCellsallowdeveloperstoaddrulestocontroltheevolutionofasetofcells.Fig 15showsfourdifferenttions,whereeachonehasadifferentsetofrulesthatareusedtocustomizethematchingsemanticsofapattern.Althoughevolutionshavedifferentrules,weappreciatethatallevolutionshavetheapply reaction rule,whichonlyappliesthereaction
evolu-ofeachcell toajoinpoint.Fig 15ashowsthatthekill creators rulekillsthecells thatcreateanewcell.Addingthisrule,
a patterncannotmatchmultipletimesanymore.Fig 15bshowsthat theadd seed ruleaddsaseediftherearenocellsoronly matchcells.Thisruleallows apatternto matchagain Fig 15cshowsthatthekeep seed rulealways keepsa seedtopermitthestartingofanewpotentialmatchofapatternatanymoment.Finally,Fig 15dshowsthatthelife-time for a trace
rulekillsallcellswhoseperiodoftimeofajoinpointtracehasexceededadeterminedperiod.Thisruleallowsdevelopers
toonlymatchtracesofjoinpointsthatoccurataperiodoftime
Trang 16Fig 14 Evolution of a seed during the matching of a pattern.
Fig 15 Different matching semantics to match a pattern (figure adapted from[37] ).
Inspired by the Decorator design pattern [16], rules of MatcherCells are functions which can be composed in order
to customize the matchingsemantics Forinstance, the single match semantics (Fig 15a)is achievedby the composition
of kill creators with apply reaction. Inthe two sections,we explain how these rules are definedandused to supportthecustomizationoftheprocessesofmatchingandadvisingofeachstatefulaspectinESA
react:SMatch×JoinPoint× [Env×Pattern×SMatch→Env] →SMatch
Trang 17rule:List<SMatch> ×JoinPoint→List<SMatch>
Aruleisafunctionthattakesasparametersalistofsmatchesandajoinpoint,andreturnsthelistofsmatchesthatareevaluatedwiththenextjoinpoint.Forexample,theapply reaction ruleimplementationis:
1 (: apply−reaction Rule)
2 (define (apply−reaction smatches jp)
3 (remove−duplicates (append smatches
The apply-reaction function returnsthesmatchesreactions Asmatch,whosereactionisitself,isinthelistof smatchesandtheirreactions(Line 4).Thismeansthatthissmatchisduplicatedwhenbothlistsarejoined.Topreventthisduplication,the remove-duplicates functionisused.Usingruledesignators(i.e., functionsthatreturnrules),developersareabletocreaterulesthatcanbecomposed:
(: kill−creators (Rule−> Rule))
(define (kill−creators rule)
(λ (smatches jp)
(let ([next−smatches (rule smatches jp )])
( diff next−smatches (get−creators (get−sons next−smatches smatches) ) ) ) ) )
(: add−seed (Pattern−> (Rule−> Rule)))
(define (add−seed pattern)
(λ (rule)
(λ (smatches jp)
(let ([next−smatches (rule smatches jp )])
(if(empty? ( f i l t e r no−match? next−smatches))
(cons (make−seed pattern) next−smatches)
next−smatches) ) ) ) )
(: keep−seed (Pattern−> (Rule−> Rule)))
(define (keep−seed pattern)
(λ (rule)
(λ (smatches jp)
(let ([next−smatches (rule smatches jp )])
(if(= (count−seeds next−smatches) 0)
(cons (make−seed pattern) next−smatches)
ofrulestoobtainthedifferentsemanticsofFig 15are:
(definesingle−match (kill−creators apply−reaction))
(definesingle−match−at−a−time ((add−seed pattern) single−match))
(definea−potential−match−can−always−start ((keep−seed pattern) single−match))
(definetiming−to−match ((add−seed pattern) ((trace−life−time delta) single−match)))
Adding context information to smatches Somerulesmayneedallsmatchestocontainspecificcontextinformation.Forple, trace-life-time needsallsmatchestocontainthe time intheirenvironmentswhenapotentialmatchstarts:
exam-3 Notice that add-seed is in fact a higher-order rule designator, parameterized by the original pattern or a new one.