DSL02.pdf

(319 KB) Pobierz
Concrete Syntax for Objects
Domain-Specific Language Embedding and Assimilation without Restrictions
Martin Bravenboer
Institute of Information and Computing Sciences
Universiteit Utrecht, P.O. Box 80089
3508 TB Utrecht, The Netherlands
martin@cs.uu.nl
Eelco Visser
Institute of Information and Computing Sciences
Universiteit Utrecht, P.O. Box 80089
3508 TB Utrecht, The Netherlands
visser@acm.org
ABSTRACT
Applicationprogrammer’sinterfacesgiveaccesstodomain
knowledgeencapsulatedinclasslibrarieswithoutproviding
theappropriatenotationforexpressingdomaincomposition.
Sinceobject-orientedlanguagesaredesignedforextensibil-
ityandreuse,thelanguageconstructsareoftensucient
forexpressingdomainabstractionsatthesemanticlevel.
However,theydonotprovidetherightabstractionsatthe
syntacticlevel. InthispaperwedescribeMetaBorg,a
methodforprovidingconcretesyntaxfordomainabstrac-
tionstoapplicationprogrammers.Themethodconsists
ofembeddingdomain-specificlanguagesinageneralpur-
posehostlanguageandassimilatingtheembeddeddomain
codeintothesurroundinghostcode.Insteadofextending
theimplementationofthehostlanguage,theassimilation
phaseimplementsdomainabstractionsintermsofexisting
APIsleavingthehostlanguageundisturbed.Indeed,Meta-
BorgcanbeconsideredamethodforpromotingAPIsto
thelanguagelevel.Themethodissupportedbyprovenand
availabletechnology,i.e. thesyntaxdefinitionformalism
SDFandtheprogramtransformationlanguageandtoolset
Stratego/XT.Weillustratethemethodwithapplications
inthreedomains:codegeneration,XMLgeneration,and
user-interfaceconstruction.
1. INTRODUCTION
Classlibrariesencapsulateknowledgeaboutthedomain
forwhichthelibraryiswritten.Theapplicationprogram-
mer’sinterfacetoalibraryisthemeansforprogrammers
toaccessthatknowledge.However,thegenericlanguage
ofmethodinvocationprovidedbyobject-orientedlanguages
doesoftennotprovidetherightnotationforexpressing
domain-specificcomposition.Generalpurposelanguages,
particularlyobject-orientedlanguages,aredesignedforex-
tensibilityandreuse.Thatis,languageconceptssuchas
objects,interfaces,inheritance,andpolymorphismsupport
theconstructionofclasshierarchieswithreusableimplemen-
tationsthatcaneasilybeextendedwithvariants.Thus,OO
languagesprovidetheflexibilitytodevelopandevolveAPIs
accordingtogrowinginsightintoadomain.
Althoughthesefacilitiesareoftensucientforexpress-
ingdomainabstractionsatthesemanticlevel,theydonot
providetherightabstractionsatthesyntacticlevel.Thisis
obviouswhenconsideringthedomainofarithmeticorlogical
operations.Mostmodernlanguagesprovideinfixoperators
usingthewellknownnotationfrommathematics.Program-
merscomplainwhentheyhavetoprograminalanguage
wherearithmeticoperationsaremadeavailableinthesame
syntaxasotherprocedures.Considerwriting e1+e2 as
add(e1,e2) oreven x:=e1;x.add(e2) .However,when
programminginotherdomainssuchascodegeneration,doc-
umentprocessing,orgraphicaluser-interfaceconstruction,
programmersareforcedtoexpresstheirdesignsusingthe
genericnotationofmethodinvocationratherthanamore
appropriatedomainnotation.Thusprogrammershaveto
writecodesuchas
Categories and Subject Descriptors
D.1.5[ProgrammingTechniques]:Object-orientedPro-
gramming;D.2.3[SoftwareEngineering]:CodingTools
andTechniques;D.2.3[ProgrammingLanguages]:Pro-
cessors
JPanelpanel=
newJPanel(newBorderLayout(12,12));
panel.setBorder(
BorderFactory.createEmptyBorder(15,15,15,15));
General Terms: Languages,Design
Keywords: MetaBorg,Stratego,SDF,EmbeddedLan-
guages,SyntaxExtension,ExtensibleSyntax,Domain-Spe-
cificLanguages,Rewriting,MetaProgramming,Concrete
ObjectSyntax
inordertoconstructauser-interface,ratherthanusinga
morecompositionalsyntaxreflectingthenicehierarchical
structureofuser-interfacecomponentsintheSwinglibrary.
Buildinginsyntacticsupportforsuchdomainsinagen-
eralpurposelanguageisnotfeasible,however,becauseof
thedierentspeedsatwhichlanguagesanddomainabstrac-
tionsdevelop.Alanguageshouldstriveforstability,while
librariescanbemorevolatile.
InthispaperwedescribeMetaBorg,amethodforpro-
vidingconcretesyntaxfordomainabstractionstoappli-
cationprogrammers.Themethodconsistsofembedding
Permission to make digital or hard copies of all or part of this work for
personal or classroom use is granted without fee provided that copies are
not made or distributed for profit or commercial advantage and that copies
bear this notice and the full citation on the first page. To copy otherwise, to
republish, to post on servers or to redistribute to lists, requires prior specific
permission and/or a fee.
OOPSLA’04, Oct. 24-28, 2004, Vancouver, British Columbia, Canada.
Copyright 2004 ACM 1-58113-831-8/04/0010 ... $ 5.00.
domain-specificlanguagesinageneralpurposehostlan-
guageandassimilatingtheembeddeddomaincodeintothe
surroundinghostcode 1 .Insteadofextendingtheimplemen-
tationofthehostlanguage,theassimilationphaseimple-
mentsdomainabstractionsintermsofexistingAPIsleaving
thehostlanguageundisturbed.Indeed,MetaBorgcanbe
consideredamethodforpromotingAPIstothelanguage
level[33].
Forexample,toimprovetheconstructionofuser-interfaces
inJava,wehavedesignedalittleSwingUser-interfaceLan-
guage(Swul)thatmakesthecompositionalstructureof
theSwingcomponentsvisibleinapplicationprograms.Us-
ingourmethodwehaveembeddedthislanguageinJava,
suchthatitisdirectlyavailabletoapplicationprogrammers.
TheycannowwritewithintheirJavaprogramsexpressions
suchas
withuser-definableoperators[23],overloadingof(a
fixedsetof)operators,syntaxmacros[30],orgram-
marformalismssupportingonlyasubset,suchasLL
orLALR,ofthecontext-freegrammars[13,2].The
onlyprovisowemakeisthathostandembeddedlan-
guagehaveacontext-freesyntax.
NotrestrictedtoasinglehostlanguageThemethod
isnotspecifictoaparticularhostlanguage[2],butcan
beusedtoembedanylanguageinanyhostlanguage.
InteractionwithhostlanguageEmbeddedcodefrag-
mentsshouldbeabletorefertoartifactsinthehost
programandviceversa.Thisisincontrasttoap-
proachesbasedonaseparatedomain-specificlanguage
fromwhichcodeisgenerated[40,33].
CombinationofextensionsItshouldbepossibletocom-
binemultipledomainnotations.Thisincontrastto
hard-wiredlanguageextensions.
NorestrictionsonassimilationThetranslationofem-
beddedfragmentstothehostlanguageshouldnotbe
limitedtoasimplehomomorphismorotherfixedtrans-
lationorder[6],butshouldallowuseofcontext-sensitive
information,globalanalysis,andmulti-stagetransfor-
mations.
Asaconsequenceofthesecharacteristicswedonotre-
quirethatlanguageextensionsareimplementedwithinpro-
gramsinthehostlanguageitself[13],sincesuchapproaches
leadtorestrictionsinmanyoftheareasmentionedabove.
Wealsodonotexpectlanguagedesignandimplementation
skillsfromtheaverageapplicationprogrammer.Insteadwe
optforaseparationofrolesbetweenthemeta-programmer
definingthelanguageembeddingandassimilation,andthe
applicationprogrammerusingadomainnotation.However,
ourtechniquesaresucientlyhigh-levelthataknowledge-
ableprogrammercanusethemtocreatenewembeddings.
Thatis,themethodisbasedonSDF2[10,44,45],asyntax
definitionformalismusedtodefineembeddings,andStrat-
ego/XT[26,47]alanguageandtoolsetforprogramtrans-
formationusedtoimplementassimilation.Thesetoolsare
matureandfreelyavailablefrom[38]and[41],respectively.
TheapplicationsofMetaBorgdevelopedinthispaperare
Weproceedasfollows. InSection2weexaminethe
practiceofobject-orientedprogramminginthreedomains:
codegeneration,documentgeneration,andgraphicaluser-
interfaceconstruction.Foreachofthesedomainsweshow
howthereadabilityofprogramsimprovesdramaticallyby
employingdomain-specificconcretesyntax. Inparticular,
weshowhowtogenerateJavaprogramsandXMLdocu-
mentsinJava.Furthermore,wedescribethedomain-specific
SwingUser-interfaceLanguage(Swul),whichprovidesa
nicecompositionallanguageforuser-interfacecomposition
inJava.InSection3weexplainhowconcretesyntaxem-
beddingsandthecorrespondingassimilationsarerealized
usingtheMetaBorgmethodandillustratethisbytheim-
plementationofembeddingsforthethreeapplicationsfrom
Section2.InSection4wegiveanoverviewofthesyntax
definitionformalismSDF2.InSection5.2wediscussthere-
lationwithcompetingapproachessuchasuser-definableop-
erators,syntaxmacros,applicationgenerators,anddomain-
specificlanguages.WediscussfutureworkinSection5.3,
andconcludeinSection6.
JPanelpanel=panelofborderlayout{
north=label"Welcome"
center=scrollpaneof
input:textarea{
rows =20
columns=40
}
south=panelofborderlayout{
east=buttonforExitAction
}
};
inordertoimplementauser-interfaceconsistingofapanel
withborderlayout,containingalabel,atextarea,andan-
otherpanelwithabutton.Suchaprogramisassimilated
intothesurroundingJavacodebytranslatingittothese-
quenceofSwingmethodcallsthatonewouldwritebyhand.
Ourworkstandsinalonglineofapproachestoaddsyn-
tacticextensibilitytoprogramminglanguages[30,50,13,39,
2,6,3].Althoughourworkhasmanycommonalitieswith
otherapproaches,itisdistinguishedbyitsgenerality,i.e.
thelackofrestrictionsoneitherthesyntaxorthesemantics
ofembeddingandassimilation. Inaddition,implementa-
tionofembeddingsishigh-levelandconcise;definitionand
embeddingofSwulrequiredonly100linesofsyntaxdefi-
nitionand170linesofassimilationrules.Ourmethodhas
thefollowingcharacteristics:
SyntacticEmbeddedcodefragmentsarecheckedsyntac-
ticallyatcompile-time.Thisisincontrastwithap-
proachestocomposeprogramfragmentsusingstring
literals.
NorestrictionsonsyntaxdefinitionOurmaximisthat
itshouldbepossibletodesignanotationthatisfitting
forthedomainwithoutplacingartificialrestrictionson
thesyntaxtobeused.Thismeansthatbothlexical
andcontext-freesyntaxshouldbedefinable.Further-
more,allaspectsoftheembedding,includingquota-
tionsymbols,ifany,shouldbeadaptable.Onlythe
fullclassofcontext-freegrammarsallowssuchnatu-
ralsyntaxdefinition.Thisisincontrasttolanguages
1
MetaBorgprovidesgenerictechnologyforallowingahostlan-
guage(collective)toincorporateandassimilateexternaldomains
(cultures)inordertostrengthenitself.Theeaseofimplementing
embeddingsmakesresistancefutile.
942503838.049.png 942503838.060.png 942503838.071.png 942503838.082.png 942503838.001.png 942503838.002.png 942503838.003.png 942503838.004.png 942503838.005.png 942503838.006.png 942503838.007.png 942503838.008.png 942503838.009.png 942503838.010.png 942503838.011.png 942503838.012.png 942503838.013.png 942503838.014.png 942503838.015.png 942503838.016.png 942503838.017.png 942503838.018.png 942503838.019.png 942503838.020.png 942503838.021.png 942503838.022.png 942503838.023.png 942503838.024.png 942503838.025.png 942503838.026.png 942503838.027.png 942503838.028.png
2. CONCRETE SYNTAX FOR OBJECTS
Inthissectionweexaminethreeapplicationdomainsthat
suerfromthemisalignmentbetweenlanguagenotationand
thedomain:codegeneration,XMLdocumentgeneration,
andgraphicaluser-interfaceconstruction.Foreachofthese
domainswediscussthemethodsthatareusedforprogram-
minginthesedomainsusinganobject-orientedlanguage
andweshowhowourconcretesyntaxmethoddramatically
improvesthereadabilityandwritabilityofapplicationsin
thesedomains.ForallexamplesinthispaperweuseJava
asthehostlanguage,butthetechniquesareequallywell
applicabletootherlanguages.
Stringx="propertyChangeListeners";
jsc.add("if(");
jsc.append(x);
jsc.append("==null)return;");
jsc.add("PropertyChangeEventevent=new");
jsc.append("PropertyChangeEvent");
jsc.append("(this,f,v1,v2);");
jsc.add("");
jsc.add("for(inti=0;i<");
jsc.append(x);
jsc.append(".size();i++){");
jsc.indent();
jsc.add("((PropertyChangeListener)");
jsc.append(x);
jsc.append(".elementAt(i)).");
jsc.append("propertyChange(event);");
jsc.unindent();
jsc.add("}");
2.1 Code Generation
Acodegeneratorautomatestheproductionofboilerplate
codebytranslatingacompacthigh-levelspecificationofa
problemintofullblowncode.Typicalapplicationsinclude
thegenerationofdata-typesfortherepresentationofab-
stractsyntaxtrees,thegenerationofXMLdatabinding[5]
codeforconvertingXMLtoaspecificdata-type,andthe
generationofobject-relationalbindingcodeforconnecting
anobject-orientedprogramtoadatabasesystem.Numer-
oustoolsareavailableforthesepurposes;LLBLGen[4]
isanobject-relationalbindinggenerator;ApiGen[16]and
JTB[42]areabstractsyntaxtreegenerators,JAXB[25]and
Castor[14]areXMLdatabindingtools,tonamebutafew.
Theimplementationofacodegeneratorrequiresanin-
ternalrepresentationofprogramcodeandaninterfacefor
accessingthisrepresentationinordertocomposeandtrans-
formcodefragments.Ideally,generatorsuseastructured
representationofprograms,i.e.adata-structuretorepre-
sentabstractsyntaxtrees.Sucharepresentationmakesit
easytocompose,analyze,andtransformfragments.For
example,theXMLdatabindingtoolJAXBusesafullab-
stractsyntaxtreeinitscodegenerator.However,inprac-
tice,manygeneratorsarestring-based,meaningthatcode
isgeneratedbydirectlyprintingstringstoafile,orbyrep-
resentingfragmentsasstringsandcomposingthose.For
exampleandironically,theabstractsyntaxtreegenerators
ApiGen[16]andJTB[42]aretext-basedcodegenerators.
Castor[14]isanexampleofahybridapproachwhichusesa
combinationofanabstractsyntaxtreefortheglobalstruc-
tureandtextformethodbodies.
Neitherimplementationusingadata-structure,norusing
stringliteralsissatisfactory.Theadvantageofusingstring
literalsortexttemplatesisthatonecanuseconcretesyn-
tax,i.e.thefragmentsarereadableasprogramcode,and
itistrivialtoimplement.Theapproachisillustratedby
theCastorexampleinFigure1,whichbuildsupastring
representationofaprogramfragment.However,thedis-
advantagesfaroutweightheadvantages.Escapingtothe
hostlanguagetoinsertafragmentofcodecomputedelse-
whereiscumbersome.Thesyntaxofthegeneratedcodeis
notchecked.Nofurthermanipulationofthecodeispossi-
ble.Andruntimeoverheadisincurredforparsing,analysis,
compilationorinterpretationifcodeistobeexecuted.
Theadvantageofusingadata-structureisthatthegener-
atedcodeisstructuredandisamenabletofurtherprocess-
ing.Typecorrectnessofthegeneratoroftenentailssyntactic
correctnessofthegeneratedprogram.Itisalsoeasytoim-
plementinageneralpurposeobject-orientedlanguage.The
approachrequiresthecreationofaclasshierarchywhichcan
besubstantialforareallanguage.Codegeneratorssuchas
Figure1:CodegenerationinCastor.
ATermx=id|[propertyChangeListeners]|;
ATermstm=bstm|[{
if(x==null)return;
PropertyChangeEventevent=
newPropertyChangeEvent(this,f,v1,v1);
for(intc=0;c<x.size();c++){
((...)x.elementAt(c)).propertyChange(event);
}
}
]|;
Figure2:Codegenerationwithconcretesyntax.
ApiGenandJTBcanbeusedforthatpurpose.However,
compositionofcodefragmentsisdoneviacallstothecode
API,leadingtoveryverbosemeta-programs.Itisusually
hardtounderstandthestructureofthegeneratedcodewhen
inspectingsuchmeta-programs.
TheMetaBorgmethodcombinesthebestofbothworlds.
Codefragmentsarewrittenusingtheconcretesyntaxofthe
programminglanguage,buttheimplementationisbasedon
anAPIforcoderepresentation.ThisisillustratedinFig-
ure2withafragmentofaJavaprogramgeneratingaJava
program,correspondingtotheexampleinFigure1.The
generatorusesATerms[8]fortherepresentationofgener-
atedcode.InsteadofusingconstructorsfromtheATerm
classhierarchytocreateacodefragment,itiswrittenas
aregularpieceofJavacode.Thecodefragmentsaredis-
tinguishedfromthesurroundingcodebythedelimiters |[
and ]| .ThedelimitersarenotfixedinMetaBorgandcan
evenbeleftoutwhenappropriate.The bstm and id tags
areusedtoindicatethatthefragmentsareofsyntacticcate-
gorystatementandidentifierrespectively.Afragmentdoes
notneedtobeclosed,butcanincorporatecodefragments
generatedelsewhere.Forexample,inFigure2theidentifier
assignedtovariable x isusedinthefragmentassignedto
thevariable stm .
Meta-programswithembeddedobject-programfragments
aretranslatedtopureJavaprogramsinwhichcodecon-
structionisexpresseddirectlyintermsofcallstothecode
942503838.029.png 942503838.030.png 942503838.031.png 942503838.032.png 942503838.033.png 942503838.034.png 942503838.035.png 942503838.036.png 942503838.037.png 942503838.038.png 942503838.039.png 942503838.040.png 942503838.041.png 942503838.042.png 942503838.043.png 942503838.044.png 942503838.045.png 942503838.046.png 942503838.047.png 942503838.048.png
out.startDocument();
out.startElement("","html","html",noAttrs);
out.startElement("","body","body",noAttrs);
out.startElement("","p","p",noAttrs);
out.characters(text.toCharArray(),0,
text.length());
out.endElement("","p","p");
out.endElement("","body","body");
out.endElement("","html","html");
out.endDocument();
parse-java-xml
Java
Java
assimilate-sax
XML
Figure5:Aprogramwithembeddedconcretesyn-
tax(e.g.,forXML)istranslatedtoapureJavapro-
gram.
Figure3:CompositionofanXMLdocumentinCo-
coon.
out.writedocument%>
<html>
<body>
<p><%text::cdata%></p>
</body>
</html>
<%;
whichcanbeanXMLserializeroraDOMconstructor,as
illustratedinFigure3withacodefragmentfromCocoon
[15].ByusingtheseAPIsthecodeisguaranteedtoproduce
well-formedXMLaslongasthelibrarydoesitsjobprop-
erly.However,thesesolutionsresultinsequencesofmethod
invocationsthatarehardtoread.
TheMetaBorgsolutionisthesameasinthecaseofcode
generation.Thereisagoodnotationforthisdomain,i.e.,
XMLitself.WiththeMetaBorgmethodwemakethisno-
tationavailabletotheapplicationprogrammer,whilekeep-
ingthepropertiesofAPIsforstructuredrepresentationof
documents.Figure4showsastatementinaJavaprogram
withanembeddedXMLdocument.Thesymbols %> and <%
areusedtodelimittheembeddedXMLfromthesurround-
ingcode.Withinthedocumentisareferencetoadocument
fragmentdefinedearlierintheprogram,usingthe <% and
%> antiquotationdelimiters.Theassimilationprocess(Fig-
ure5)transformsaJavaprogramwithembeddedXMLto
apureJavaprogramwithcallstoaSAX ContentHandler .
ThebigdierencebetweentheembeddingofXMLand
theembeddingofaprogramminglanguageisthatthelexical
structureofXMLiscompletelydierentfromthatof,say,
Java.Thismakestheparsingproblemmorecomplicated.
Figure4: CompositionofanXMLdocument
withconcretesyntaxwithunderlyingSAXCon-
tentHandlerinvocations.
representationAPI.Thistoolalsoguaranteesthatthecode
fragmentsaresyntacticallycorrect.Thetypesystemofthe
hostlanguageandaproperlydefinedunderlyingAPIwill
thenguaranteethatcompositionsaresyntacticallycorrect
aswell.
NotethatMetaBorgisnotrestrictedtoJavainJava.
Thesamemethodcanbeusedtoembedotherlanguagesin
Java(e.g.togenerateC#code),ortouseadierenthost
language(e.g.togenerateJavacodewithaC#program).
TherealizationoftheseembeddingswillbediscussedinSec-
tion3.
2.2 XML Document Generation
XMLisusedonalargescalefortheexchangeofdatabe-
tweenprograms.Thisrequiresprogramstoreadandwrite
XMLdocumentsandtoconvertinternaldatatoXMLand
back.ApplicationsthatgenerateXMLdocumentsbyfilling
intemplatessuerfromthelackofsupportforXMLsyn-
taxingeneralpurposeprogramminglanguages.Theprob-
lemsaresimilartothatincodegeneration.Text-basedsolu-
tionscannotguaranteethattheproducedtextiswell-formed
XML.Typicalexamplesareserver-sidescriptinglanguages
suchasJSPandASP.NET,whichsupporttheembedding
ofaprogramminglanguageinXMLorHTML.Furtherma-
nipulationofthedocumentaftergenerationisimpossible.A
typicalexampleofpostgenerationtransformationisthead-
ditionofstatisticstoageneratedwebpage.Manywebpage
generatorsjustputthisinformationoutsidetheHTMLtags,
whichisofcourseinvalid,butisacceptedbywebbrowsers
ifthepagedoesnotclaimtobewell-formedXML.
Othersolutionsarebasedondatastructures.Inlibraries
suchasW3CDOM,JDOM,andXOM,documentsarerep-
resentedbyinstancesofclassescorrespondingtothegeneric
structureofXML,e.g. Document , Element ,and Attribute .
Thusdocumentconstructionisachievedwiththeconstruc-
torsoftheseclasses.Alternatively,constructioncanbe
achievedwitheventsemittedtoaSAX ContentHandler ,
2.3 Graphical User-Interface Construction
InthecasesofcodeandXMLgenerationadomainnota-
tionisreadilyavailabletoimprovethereadabilityofappli-
cationprograms.However,therearemanyotherdomains
withAPIsrepresentinga‘language’inthesenseofacoher-
entsetofconceptsandcompositionfacilities,butwithouta
concretenotation.Programminginthesedomainscanalso
beimprovedbyemployingdomain-specificnotation,which
shouldthenfirstbedesigned.Considerforexamplethecon-
structionofgraphicaluser-interfacesinJava.
Graphicaluser-interfacescanbegeneratedwithavisual
toolorcanbewrittenbyhand.Ahandwrittenuser-interface
typicallyinstantiatesGUIcomponentssuchasbuttonsand
textfieldsandarrangesthesecomponentsinpanelsbyusing
fixedpositioningoralayoutmanagerthatallowstheuser-
interfacetoadaptitselftochangesinthesizeofthewindow.
Despitecatalogsofdesignpatternsfordevelopinggraphical
user-interfaces,thiscodeisstilloneofthemostunwieldy
partsofaprogram(Figure6;left).Ahandwrittenuser-
interfacetakesquiteafewlinesofcodeandtheresulting
codeisdiculttounderstandandmaintain.
Thereareafewproposalsforlanguagesspecificallygeared
towardsuser-interfaces,e.g.Mozilla’sXUL,W3C’sXForms
andMicrosoft’sXAML,butthesesolutionsdonotintegrate
942503838.050.png 942503838.051.png 942503838.052.png 942503838.053.png 942503838.054.png 942503838.055.png 942503838.056.png 942503838.057.png 942503838.058.png 942503838.059.png 942503838.061.png 942503838.062.png 942503838.063.png 942503838.064.png 942503838.065.png 942503838.066.png 942503838.067.png 942503838.068.png 942503838.069.png 942503838.070.png 942503838.072.png 942503838.073.png 942503838.074.png 942503838.075.png 942503838.076.png 942503838.077.png 942503838.078.png 942503838.079.png 942503838.080.png 942503838.081.png
JTextAreatext=newJTextArea(20,40);
JPanelpanel=newJPanel(newBorderLayout(12,12));
panel.setBorder(
BorderFactory.createEmptyBorder(15,15,15,15)
JPanelpanel=panelofborderlayout{
hgap=12vgap=12
north=label"Pleaseenteryourmessage"
center=scrollpaneoftextarea{
rows=20
columns=40
);
panel.add(BorderLayout.NORTH,
newJLabel("Pleaseenteryourmessage"));
panel.add(BorderLayout.CENTER,newJScrollPane(text));
JPanelsouth=newJPanel(newBorderLayout(12,12));
JPanelbuttons=newJPanel(newGridLayout(1,2,12,12));
buttons.add(newJButton("Ok"));
buttons.add(newJButton("Cancel"));
south.add(BorderLayout.EAST,buttons);
panel.add(BorderLayout.SOUTH,south);
}
south=panelofborderlayout{
east=panelofgridlayout{
hgap=12vgap=12
row={
button"Ok"
button"Cancel"
}
}
Figure6:Sequenceofstatementsforcomposingauser-interface
withSwingAPImethods(left)andSwulimplementationfor
composingthesameuser-interface(right).
}
};
wellwiththehostlanguage.TheyabstractfromaGUI
toolkit,whichisnotalwaysanadvantage,andrestrictthe
waytheGUIcaninteractwiththehostlanguage.XUL
clonesforJava,suchasSwiX ml andLuxor,usereflection
andaconventionforthelocationofmethods(or Action
fields)toinvokecodeinthehostlanguage.Althoughthis
worksreasonablywell,itlimitsthewaythehostlanguageis
abletointeractwiththeGUIcode.Forexample,amodel-
view-controllerdesign,wheretheGUIcomponentsaredi-
rectlyupdatedfromtheir(Swing)models,isnotpossiblein
thesetoolkits.Furthermore,theXMLformattedGUIspec-
ificationsareinterpreted,notcheckedstaticallyforinternal
consistencyorcorrectinteractionwithcodeinthehostlan-
guage.
UsingtheMetaBorgmethodwehavedevelopedasolu-
tionthatprovidesdomain-specificnotationfortheconstruc-
tionofuser-interfacesandintegrateswellwiththerestofthe
programwritteninthehostlanguage.Expressionsinthe
SwingUser-interfaceLanguage(Swul)correspondtocom-
ponentsofaSwinguser-interface.Thelanguageencourages
thecompositionalconstructionofcomplexcomponents,in
contrasttotheassemblylanguagespaghettistyleusedwith
directcallstoSwing.Thus,subcomponentsaresubexpres-
sions,andarenotaddedafterwards.Attributesofcompo-
nentsarenamed,avoidingtheneedtocontinuouslylooking
uptheorderofmethodparameters.Thedeclarationofthe
layoutstyleiscombinedwiththeinstantiationofthesub-
components.EmbeddedinJavatheSwullanguagecanbe
useddirectlytoprogramuser-interfaces.Swulexpressions
canrefertoelementssuchasvariablesandmethodsfrom
otherpartsoftheprogram.Forexample,inordertosetthe
valueofalayoutattributeortopassanevent-handler.
TheexampleinFigure6(right)illustratestheuseof
Swul,creatinginasingleJavaassignment(beitmultiline),
thesameuser-interfaceimplementeddirectlyusingSwing
methodsontheleft.AlthoughtheSwulsolutionusesmore
lines,thedierenceinnumberofnon-spacecharacters(507
vs243)indicatesthattheSwulsolutionissignificantlymore
concise.
approachcanbeappliedtomanyotherdomains,including
embeddedquerylanguagessuchasXPathandSQL.Unfor-
tunately,queriesintheselanguagesareusuallyembeddedin
stringliterals.Theyareoftenevencomposedatruntimeby
concatenatingstrings.InthiscasetheSQLstatementsand
XPathqueriescannotbecheckedsyntacticallyatcompile
time.Thismightresultinruntimeerrorsor,evenworse,
securityproblems.Ifavaluefromthehostlanguageisem-
beddedinanSQLquerybystringconcatenation,thenthere
isnoguaranteethatthestringactuallyisofthesyntactic
categoryexpectedatthispointintheSQLstatement.This
resultsinasecurityissuethatisrathereasytoexploitby
enteringSQLconstructswhereplainstringsareexpected.
Topreventthis,theembeddedstringhastobeescaped.
Amissingescapewillimmediatelyposeasecuritythreat.
Thisisageneralproblemofruntimecompositionofcode
fragmentsbystringconcatenation.XMLapplicationsthat
usestringconcatenationmightbeasecurityriskaswell.In
suchapplicationsproperescapingisrequiredatmanydif-
ferentplacesinthecode.Thistaskcanbeautomatedby
applyingourlanguageembeddingtools.
Anotherexampleofalittlelanguagethatisoftenembed-
dedinstringliteralsisthelanguageofregularexpressions
usedforpatternmatchingofcharactersequences.Aregular
expressionisencodedinastringliteralwhichisinterpreted
orcompiledatruntimetoamatcher.Theclarityofareg-
ularexpressionisreducedbyrequiringspecialcharactersto
beescaped.C#reducesthenumberofcharactersthathave
tobeescapedbyaddingverbatimstringstothelanguage,
whereonlydoublequoteshavetobeescaped.Justasinall
stringliteralbasedembeddingstheregularexpressionisnot
checkedsyntacticallyatcompile-time.
Thedierencewiththeotherexamplesisthatthelibraries
operatingontheselanguagesusuallyonlyaccepttextual
input.Thismakesastructuredrepresentationofthequery
moreannoyingthanadvantageous.Yet,theMetaBorg
methodcanstillbeusedbyassimilatingtheembeddedcode
fragmentstothecorrespondingstringoperations.Thiswill
maketheembeddingofmetavaluessaferandeasier,andthe
embeddingwillguaranteethesyntacticcorrectnessofthe
embeddedexpressions.TothisendtheMetaBorgtools
supporttherepresentationofembeddedfragmentsinafull
parsetree,whichcanbeyieldedtoastring.
2.4 Other Applications
Wehavediscussedthreeapplicationdomainsinwhich
concretedomainnotationimprovesprograms.Thesame
942503838.083.png 942503838.084.png 942503838.085.png 942503838.086.png 942503838.087.png 942503838.088.png 942503838.089.png
 
Zgłoś jeśli naruszono regulamin