[advanced information and knowledge processing] meta-programming and model-driven meta-program...

20
Chapter 6 Open PROMOL: A Meta-Language for Heterogeneous Meta-Programming 6.1 Introduction and Motivation Though other authors (see a review in [DKV00]) have suggested many interesting ideas, models and solutions, nevertheless, it was difficult to find a language at the time that would suit best for expressing explicitly the composition, modification and generalization simultaneously. As a consequence, we have designed the language Open PROMOL aiming at the development of generic specifications, which specify the wide range modifications of target language (also domain language) programs to support the design of generic components and generators. Our approach has some similarities and differences in the model as well as in the implemented concepts to Bassett’s frame commands [Bas97]. Open PROMOL is an experimental language aiming to support extensive research of component-based and generative reuse in various domains. The full meaning of the acronym Open PROMOL should be read as ‘Open for extension PROgram MODification Language’. Due to simplicity of the syntax (the language implements the external function concept very similar to those used in preprocessing directives), it is a very useful tool for teaching purposes. Though at the very begin- ning the use of the language was restricted by one-two domains (i.e. an extension of reuse capabilities of VHDL-based components and teaching of generative reuse), later, we have approved usefulness of the language for other domains too (e.g. for embedded software components, or generative learning objects, see also Chap. 16). It was possible to do that because the essential feature of Open PROMOL is its independence upon any external language (e.g. domain-specific or programming language). As a result, it can be combined along with any external language to express multi-linguistic specifications. The specifications are actually program generators that are implemented in the form of heterogeneous meta-programs. The language is not dedicated to a particular domain or a specific target language. It does not extend a given target language directly but rather expresses concisely and explicitly the pre-programmed modifications at a higher level of abstraction. Of course, it may be achieved at some extent using a target language only, for V. ˇ Stuikys and R. Damaˇ seviˇ cius, Meta-Programming and Model-Driven Meta-Program Development, Advanced Information and Knowledge Processing, DOI 10.1007/978-1-4471-4126-6 6, © Springer-Verlag London 2013 93

Upload: robertas

Post on 08-Dec-2016

214 views

Category:

Documents


1 download

TRANSCRIPT

Chapter 6Open PROMOL: A Meta-Languagefor Heterogeneous Meta-Programming

6.1 Introduction and Motivation

Though other authors (see a review in [DKV00]) have suggested many interestingideas, models and solutions, nevertheless, it was difficult to find a language at thetime that would suit best for expressing explicitly the composition, modification andgeneralization simultaneously. As a consequence, we have designed the languageOpen PROMOL aiming at the development of generic specifications, which specifythe wide range modifications of target language (also domain language) programsto support the design of generic components and generators. Our approach has somesimilarities and differences in the model as well as in the implemented concepts toBassett’s frame commands [Bas97].

Open PROMOL is an experimental language aiming to support extensiveresearch of component-based and generative reuse in various domains. The fullmeaning of the acronym Open PROMOL should be read as ‘Open for extensionPROgram MODification Language’. Due to simplicity of the syntax (the languageimplements the external function concept very similar to those used in preprocessingdirectives), it is a very useful tool for teaching purposes. Though at the very begin-ning the use of the language was restricted by one-two domains (i.e. an extensionof reuse capabilities of VHDL-based components and teaching of generative reuse),later, we have approved usefulness of the language for other domains too (e.g. forembedded software components, or generative learning objects, see also Chap. 16).It was possible to do that because the essential feature of Open PROMOL is itsindependence upon any external language (e.g. domain-specific or programminglanguage). As a result, it can be combined along with any external languageto express multi-linguistic specifications. The specifications are actually programgenerators that are implemented in the form of heterogeneous meta-programs.

The language is not dedicated to a particular domain or a specific target language.It does not extend a given target language directly but rather expresses conciselyand explicitly the pre-programmed modifications at a higher level of abstraction.Of course, it may be achieved at some extent using a target language only, for

V. Stuikys and R. Damasevicius, Meta-Programming and Model-Driven Meta-ProgramDevelopment, Advanced Information and Knowledge Processing,DOI 10.1007/978-1-4471-4126-6 6, © Springer-Verlag London 2013

93

94 6 Open PROMOL: A Meta-Language for Heterogeneous Meta-Programming

example, using meta-programming capabilities of VHDL (see Chap. 4). However,by introducing an external language, we can separate concerns clearly, enhancethe abstraction level significantly and express modifications explicitly and moreflexibly, thus avoiding the over-generalization of a target program.

Thus, we motivate the need for a new scripting language by the followingreasons:

1. To deliver flexible means for representing the wide range modifications2. To support the component-based and generative reuse3. To express variations for describing a generic functionality more flexibly than

using the homogeneous meta-programming capabilities of CCC (Java) and/orVHDL

4. To approve concepts, ideas and approaches of the automatic program generationbased on using heterogeneous meta-programming

5. To have a suitable tool (which would be as simple as possible and an application-independent) for teaching purposes to demonstrating how heterogeneous meta-programming works in practice

6. To have a simple tool for learning meta-programming and carrying out experi-ments

6.2 What Concepts Does the Language Implement?1

Currently, the multi-language design paradigm prevails in designing complexsystems (e.g. System-on-Chip (SoC), web-based components and systems, etc.). Forexample, the state-of-the-art research in Electronic Design Automation communitymainly focuses on the HW/SW co-design, where the hardware parts are usuallydescribed in the hardware description languages (e.g. VHDL, SystemC, etc.) andthe software parts in C/CCC [CHMC99, JE99, JRMC99]. The configuration ofthe overall system is generally described using scripting means of a higher-levelspecification language for specifying the interconnections between blocks.

The multi-language design paradigm for web-based systems from the perspectiveof heterogeneous meta-programming is discussed in detail in Chap. 15.

In a wider context, scripting languages has been used for a long time; however,only recently they have attracted a great attention. The reason of this change is theneed to manage more efficiently the ever-increasing complexity of the systems. Theexamples are component-based frameworks, like those used in hardware design. Ifalgorithmic languages are mainly for expressing computations and domain-specificlanguages are for describing domain functionality, scripting languages are for gluinga system from components, whose functionality is given in other language [Ous98,Sch99, SN99]. The role of scripting can be summarized by the Ousterhout’s phrase:‘Scripting is a higher level programming for the 21st century’ [Ous98].

1Parts of Sect 6.2 reproduced with kind permission from Springer Science+Business Media B.V.

6.2 What Concepts Does the Language Implement? 95

Open PROMOL also can be considered as a scripting language. But we preferto treat it as a modification language because, in our view, the term modificationhas a wider meaning than the term scripting. The term ‘modification’ expresses allkinds of manipulations/transformations of any textual fragment of a program (alsoa reader should remember that meta-programming is defined as manipulation onprograms as data), while the term ‘scripting’ expresses manipulations on scripts, thatis, syntactically and semantically complete structures. The modifying and scriptingcapabilities of Open PROMOL will be disclosed later.

In a wider context, scripting languages can be categorized as domain-specificlanguages (DSLs). So far, at some extent, we have considered VHDL. It is a typicalrepresentative of DSLs for matured domains (see Chap. 5). The languages usedfor web programming also fall into this category (see Chap. 15 for details). Thescope of research and use of DSLs is constantly increasing. However, it is beyondthe scope of the book to consider this field of research in a broader context. Werecommend the following list of references for separate studies on DSLs (earlyworks [DKV00, DKV02, Hud98, IEEE99, Ous98], or recent works [KLBC08,KOMC10, OPHC09, Vis07]), on program changeability ([BAA09, BMZC03,Fel03]) and on program evolution (maintainability) and transformations ([Bec00,Bec10, Bec99, Boe10, Der02, Flu07, Fow99, GG08, GKK08, GSCC06, MDJ02,Raj06, RL00, RL07, Vid09, Win04]). All those are closely related to our vision tometa-programming as a language-centric high-level paradigm to realize the large-scale program modification, change, evolution and transformation.

Using a scripting language, a designer accepts a multi-language design paradigm,which clearly implements the ‘separation of concepts’ principle. The application ofthis paradigm allows handling the variety of the different tasks in system designsseparately, thus simplifying the general problem, raising the abstraction level andgaining a great deal of flexibility and reusability [CHMC99, JE99]. Scriptinglanguages contribute not only for composing a complex system from the pre-designed components. They can serve for modifying and adapting components, too.The modification is a part of the reuse process, which in the pure technological sensecomprises the activities such as finding, understanding, modifying and using in thenew context artefacts (documentation, components, etc.) previously developed andused by others.

Here, we consider modifications of a given program as a process of meta-programming at the meta-program construction phase. In this context, we distin-guish modifications which allow (1) to collect the existing instances of a component,(2) to perform a tiny modification (if needed) and (3) to represent the family ofvariations as a single specification in the form of heterogeneous meta-program.

Our main objective is to achieve higher reuse. We implement it through thegeneralization of domain commonalties and variations. While the extraction andisolation of domain commonalties is a relatively easy step, handling of the variationsmay require a more sophisticated manipulation. We argue that many variations of theprogram source code can be expressed in the generic form via the simple parame-terized textual modifications, which have similar meaning as if, for, case statementsin the declarative programming languages. These variations are pre-programmed

96 6 Open PROMOL: A Meta-Language for Heterogeneous Meta-Programming

Modification

Scripting

Generic Component

Instance

Gluing (scripting)

a piece of a target program

a function of the ScL

a

b

Fig. 6.1 The interpretation of the modification and scripting concepts at a lower (a) and higherlevel (b) ([SDZ02]. With kind permission from Springer ScienceCBusiness Media B.V.)

by a set of the externally parameterized PROMOL functions, which describe theparticular text modifications needed to generate the instance-specific target code.

The PROMOL functions are freely scripted into the source code, which iscommon for all target programs. The result is a composition of the PROMOLfunctions and the text of a target language, which is a generalization of the particulartarget program family, characterized by the common functionality or architecture(see Fig. 6.1).

According to Ousterhout, the main idea of scripting is that an applicationdeveloper is provided with a collection of useful components, and he (she) onlyhas to write a small amount of wiring code in order to establish connectionsbetween components [Ous98]. It can take various forms, depending on the natureand granularity of the components, the framework of a domain problem and thecomposition model.

Typically, components themselves are highly parameterized domain entities (e.g.multipliers, decoders, etc., for HW domain and many other domains), which aregeneralized with PROMOL functions. The purpose of these functions is to performthe necessary modifications of the target language code during the generationprocess in order to receive a concrete instance of the component tailored to thespecific needs of the developer. The combination of the modification and scriptingconcepts leads to the creation of parameterized systems [GV00], that is, heavilyparameterized architectures adaptable in terms of power, performance and arearequirements.

Therefore, summarizing the discussion, we suggest using meta-programmingto implement the modification concept and to use scripting to implement the

6.4 Main Capabilities of the Language 97

composition of the target language code. To achieve this, we suggest the higher-level constructs – PROMOL functions, which generate and glue together the domain(target) language code.

6.3 Basic Features of the Syntax and Semantics

Open PROMOL is a functional language and consists of an open set of externalfunctions [SD09]. The context of their usage is a prescribed specification (i.e.PROMOL script). All modifications in the specification are represented as a specificcomposition of the external functions with the target language code to be modified.Functions are called external because they represent a higher level of programmingand have parameters, whose values are defined externally.

A PROMOL function has the format as follows:

@function name [ argument list ]

We present a basic set of functions, their syntax and semantics in Tables 6.1 and6.2, respectively. The functions support the hierarchical parameterization. At thehighest level, the usage of a parameter may depend upon a specific condition orother parameter. Additionally, the conditional parameterization yields a great dealof flexibility.

In summary, Open PROMOL is an open set of external functions, whichimplement modification and scripting through the hierarchical and conditionalparameterization models.

6.4 Main Capabilities of the Language

The language and its processor EREBUS implement the following capabilities:

• Generalization. We can merge similar components into a single generic specifi-cation.

• Abstraction. We introduce two separate levels of abstraction: a higher level isthe interface, where parameters are defined, and a lower level is the specificationbody.

• Parameterization. The language implements two parameterization models: con-ditional (the assignment of a value to a parameter depends on a condition) andhierarchical (through deep nesting and the usage of external modules) ones.Parameters are not constrained to a particular type (as, e.g. in CCC templates[Vel95]) but can take the string values of any length and content.

• Separation of concerns. We clearly separate abstractions of the scripting lan-guage from a given target language, the interface of the generalized specificationfrom its implementation and the development of a specification from its usage.

98 6 Open PROMOL: A Meta-Language for Heterogeneous Meta-Programming

Table 6.1 List of basic set of the functions ([SDZ02]. With kind permission from SpringerScienceCBusiness Media B.V.)

Function name # of args Arg Meaning of an argumentActions performedby the function

@sub 2 1 Expression Parameter value substitution,expression calculation2* Precision

@if 3 1 Condition If-selection2 ‘Then’ branch3* ‘Else’ branch

@case �2 1 Selector Case-selection�2 Branches

@for 4 1 Loop parameter For loop2 Initial value3 Final value4 Loop body

@gen 5 1 Number of substrings String generation2 Separator3* Substring4* Initial index5* Step

@move 2 1 Parameter name Value assignment2 Assigned value

@rep 2 1 Number of repetitions Repetition of the text2 Script to be repeated

@include �1 �1 External module names External module declaration@macro �1 1 External module name External module instantiation

Note: An asterisk denotes optional arguments of a function

Table 6.2 List of basic Open PROMOL functions: their syntax and semantics ([SDZ02].With kind permission from Springer ScienceCBusiness Media B.V.)

Function name Examples of the usage Parameter value The returned value

@sub V :D @sub[n*2C1]; n :D 2 V :D 5;@if X: bit@if[n>1, f n :D 4 X: bit vector (0 to 3);

vector (0 to @sub[n-1])g];@case Y <D @case[n, fB1g, fB2g,

fB3g];n :D 2 Y <D B2;

@for @for[i, 0, n-1,fL(@sub[i])g]

n :D 5 L(0) L(1) L(2) L(3) L(4)

@gen Y <D @gen[n, f AND g,fXg, 0];

n :D 3 Y <D X0 AND X1 ANDX2;

@move @move[f, fNOTg] f :D NOT <null>@rep X <D “@rep[n,

f@sub[sym]g]”;n :D 4; X <D “0000”;sym :D 0

@include @include[gate] <null>@macro @macro[gate, fANDg, n] n :D 2 2-input AND gate instance

6.5 Case Study: VHDL Code Modification via Widening. . . 99

Fig. 6.2 Implementationof the Horner scheme:(a) – initial form,(b) – PROMOL interface,(c) – specification body,(d) – an instance derivedfrom the specification and(e) – another descriptionusing three functions([SDZ02]. With kindpermission from SpringerScience+Business MediaB.V.)

• Composition. A set of the external functions used in the specification implementsan internal composition through the concatenation of strings. The usage of exter-nal modules (via @macro function) allows a more sophisticated composition.

• Generation. There are specific functions for generating strings of a particularstructure.

• Extension. The language is an open set of external functions, which are indepen-dent. Hence, the new ones (if needed) can be introduced easily.

• Modification. The language performs modifications of a target program usingabstractions similar to that of the structural programming (i.e. if, for, case).

• Computation. The language allows the arithmetic, relation and logic operations.• Independence from a target language. Open PROMOL treats a target language

program as a simple text without any particular meaning and uses lexicalmechanisms independent of any target language syntax and usage context toperform the necessary modifications.

• Rapid prototyping. The language processor generates either a selected instanceor all instances prescribed by the meta-specification.

To illustrate some capabilities, we deliver two simple specifications in Figs. 6.2and 6.3.

Figure 6.2b, c represents a description which after processing yields differentvariants of polynomials in the form of the Horner scheme (Fig. 6.2d). The specifica-tion body can be represented using different PROMOL functions too (Fig. 6.2e). Thesecond specification (see Fig. 6.3) introduces a context of the used target language.The type of a language is treated as a parameter lang having three values.

6.5 Case Study: VHDL Code Modification via Widening,Narrowing and Isolation

Sametinger has described four general methods for generalizing components (i.e.generalization by widening, by narrowing, by isolation and by configuration)[Sam97]. We have adopted some of them for the modification of VHDL code with

100 6 Open PROMOL: A Meta-Language for Heterogeneous Meta-Programming

Fig. 6.3 Specificationexpressing the differences ofthe DLs: interface (a), body(b) and instances for therespective language (c)([SDZ02]. With kindpermission from SpringerScienceCBusiness MediaB.V.)

Open PROMOL. The first example (Fig. 6.4a) illustrates how modifications areimplemented in the language by narrowing functionality. The latter one (Fig. 6.4b)illustrates the modification by widening functionality. The generated instances aregiven in Fig. 6.5a, b, respectively.

The third example below demonstrates a modification by isolating functionality.For simplicity, we present it without the explicit VHDL context. Suppose we needto include in several different places of a higher-level design the slightly differentcomponents (fragments), which are given in the isolated files a1, a2, a3. This mightbe represented in the PROMOL specification as follows:

@case[k,f@macro[a1]g, f@macro[a2]g, f@macro[a3]g]

where a1, a2, a3, a4 are file names and k is a parameter for the customization forparticular context of the usage.

In general, by widening, we mean not only the extension of the space ofthe parameter values but the addition of the new parameters too. By narrowingfunctionality, we conceive the reduction of the number of the parameters, as wellas narrowing of the application domain. By isolation, we imply the splitting of thefunctionality into smaller parts. However, multitude of similar components makes itdifficult to decide which one implements the required feature.

6.6 Comparative Studies

6.6.1 Open PROMOL vs. Java (CCC) as Meta-Languages

In this section, we compare the Open PROMOL capabilities with the ones ofJava, when it is used in the role of a meta-language. This study includes acomparison of the operational capabilities only but not computational capabilities

6.6 Comparative Studies 101

Fig. 6.4 The modifications by narrowing (a) and widening (b) functionality ([SDZ02]. With kindpermission from Springer ScienceCBusiness Media B.V.)

because the two languages belong to the different categories: Open PROMOL isa scripting meta-language, and Java is a general-purpose programming language.Furthermore, their status is also different. Open PROMOL is an experimentallanguage oriented primarily at demonstrating the principles of meta-programming to

102 6 Open PROMOL: A Meta-Language for Heterogeneous Meta-Programming

Fig. 6.5 Instances (a) and (b) obtained as a result of preprocessed specifications of Fig. 6.4a, b,respectively (With kind permission from Springer ScienceCBusiness Media B.V.)

university students, while the second one is a de facto standard, controlled throughthe formalized Java Community Process that allows interested parties to get involvedin the definition of future versions and features of the Java platform.

The non-comparable features of the language are the data type system and thecomputational model. Open PROMOL has a poor data type system, and Java is astrongly typed language. The first supports the structural programming model; thesecond supports the object-oriented model.

In general, this comparison can be viewed in a wider context: as cons and prosin selecting between the universal and specialized solutions. First, we comparethe expressiveness of the two languages for the meta-interface specification. Themeta-interface of Open PROMOL is oriented for the users, who may not have anyknowledge about Open PROMOL language (see an example below):

$‘‘Enter function’’ fAND, OR, XORg func :D AND;‘‘Enter number of inputs’’ f2..8g num :D 2;

$

The text in the natural (English) language between doubled apostrophes is notinterpreted by the language processor at all; it serves as an explanation for humanreading only. The string between the pair of braces, for example fAND, OR,XORg, specifies the range of meta-parameter values; it serves for both a human and

6.6 Comparative Studies 103

Fig. 6.6 Running of Open PROMOL meta-program and a user view of meta-interface

machine. The rest part of the meta-interface command is the assignment statementthat assigns a default value to a meta-parameter. The assignment may depend upona condition, which is specified in square brackets at the beginning of the parameterdeclaration command in the meta-interface as it is shown below:

$‘‘Enter function’’ fAND, OR, XOR, NOTg func :D AND;[func neq fNOTg] ‘‘Enter number of inputs’’ f2..8g num :D 2;

$

To use the meta-program, the user only has to run a language processor inthe command prompt of the Windows OS. Then, a simplistic text-based interfaceappears (see Fig. 6.6) that guides the user through the process of meta-parametervalue selection.

The Java meta-interface is programmer-oriented and requires knowledge of Javalanguage syntax and semantics. Suppose, we have an already implement codegenerator as a Java class in some package:

public class Gate fprivate String func;private int num;

: : :

public Gate (String func, int num) fthis.func D func;this.num D num;

gg

To use it, the programmer in his application has to call a constructor of Javaclass and to pass the parameter values to it. If there are many dependencies betweenparameter values, or many parameters are optional (the user is not required to makethe selection of the parameter values), a separate constructor should be declared foreach combination of constructor parameters because Java does not support defaultvalues in the arguments of class constructors. Therefore, when we want to have a

104 6 Open PROMOL: A Meta-Language for Heterogeneous Meta-Programming

NOT gate with just one input selected for generation, we would have to implementnot one but three constructors for each case. See the additional two constructorsbelow:

public Gate (String func) fthis.func D func;this.num D 1;

gpublic Gate (int num) fthis.func D "NOT";this.num D num;

gAs the number of meta-parameters and their dependencies in a real-world system

meta-programs can be a large number, the amount of code that should be written willbe growing exponentially. Thus, the growth of verbosity is evident. This is a cost oneneeds to pay for universality.

The function-by-function comparison of two languages is given in Table 6.3.There is no principal difference in semantics of the functions for the languages. Thedifferences are syntactic. Perhaps, one feature illustrating cons and pros betweena dedicated and universal language should be mentioned. There are many modelsin VHDL, which contain fragments within the models that can be treated as‘look-alike’ strings, such as (X1, X2, X3, X4) and (X1 AND X2 AND X3 AND X4).They differ only in that they have different separators (‘,’ and ‘AND’), respectively.The @gen function in Open PROMOL is a look-alike string generator. It allowsa designer to concisely express the algorithm for representing look-alike strings indifferent places of a meta-specification. The Java implementation of the algorithmrequires several statements as it is shown in Table 6.3.

So far we have discussed Java capabilities for static heterogeneous meta-programming, when a Java program, when executed, generates another programin Java or any other language. The generated program is used only later for thedevelopment of other systems and applications.

Another capability Java has is code generation on-the-fly, when a generated pro-gram in Java is dynamically compiled by the same Java virtual machine and loadedinto the class system of the same application that generated the program [HP10].The generated code is executed and used on-the-fly, without any interruption ofexecution. Such a mode of meta-programming can be called dynamic heterogeneousmeta-programming. While it is based on the same principles of heterogeneous meta-programming as explained in Chap. 5, it also has some similarity to homogeneousmeta-programming since the only one working environment is used, and the entireprocess from the user’s view is performed at the same stage of execution, that is,at run time. However, the usage of this technique can be restricted by a variety ofJava’s deployment environments.

One can find more details for comparison of Open PROMOL and Java in OpenPROMOL Tutorial Release 1.5 for EREBUS Processor version 3.25, available atwww.soften.ktu.lt/�damarobe/promol/

6.6 Comparative Studies 105

Table 6.3 Comparison of Open PROMOL (left column) and Java abstractions for imple-mentation of meta-specification body

@sub[expr] System.out.print(expr); Calculate anyexpression, printparameter value

@move[name, value] name D value Assign a value@if [cond, f@- process if cond is trueg,f@- process if cond is falseg]

if (cond) f//execute if cond is truegelse f//execute if cond is falseg

Conditionalstatement

@case[expr,f@- process if expr D 1g,f@- process if expr D 2g,f: : :

g]

switch (expr) fcase 1://if expr equals 1

break;case 2://if expr equals 2

break;: : :

g

Selection by value

@for[var, start, end, f@ - do somethingg]

for (int var D start;var <D end; varCC) f

//do somethingg

For loop

@while[cond,f@- do while cond is trueg]

while(cond)f//do while cond is trueg

While loop

@repeat[n, f@- repeat n timesg]

for (int i D 0; i < n; iCC) f//do something n timesg

Repeat loop

@gen[n,separator,substr,init,step]

string s D””;for(int i D 0; i < n; iCDstep)f

s CD substr C (init C i);if (i !D n - 1) sCD separator;

g

Look-alike stringgeneration

@macro[metaspec name,list of params]

object.method(list of params); Call to an externalentity

We conclude the comparison here by providing the summarizing results inTable 6.4.

6.6.2 PHP as Meta-Language for Web-Based Applications

PHP is a server-side scripting language that primarily is used for the web appli-cation development. Meta-programming techniques in PHP include [SKL06] codegeneration, magic methods, stream wrappers, reflection and various experimentalextensions of PHP. Code generation uses PHP output commands (such as echo orprint) to generate code in PHP or any other language. The approach works well

106 6 Open PROMOL: A Meta-Language for Heterogeneous Meta-Programming

Table 6.4 Dedicated meta-language vs. general-purpose programming language used in the roleof a meta-language

Criteria Open PROMOL Java

Language class Domain-specificmeta-language

General-purpose programming

Programming paradigm Functional-structural Object-orientedConcept Set of external functions Classes and methodsLength of operands for

manipulationFrom program code

strings to completecomponents

Suits better for complete components

Data types Type-less language Typed languageUnderstandability Low ModerateVerbosity Lower HigherDynamic code generation None Allows dynamic compilation and

class loadingReliability status Experimental Industry wide

for generating optimized code in linear algebra domain [SS05]. Generated codecan be executed at a later stage or at once using the built-in PHP interpreter (theeval function). See, for example, code generation using PHP output statements inChap. 14.

Magic methods (or interceptor methods) are special methods (usually calledget, set, and call) that manage the dynamic creation or read-only (or

write-once) properties of classes in object-oriented programming.The methods get() and set() are called by the interpreter as soon as a

property, which is not part of a class’ description, is read from or written to[GMM05]. The call method can be used to call a method that originallydid not exist when the code was written but was later added dynamically usingthe construct magic method. Magic methods are especially useful for codeadaptation and reuse.

Stream wrappers are special components, which use PHP’s I/O functions forrepresenting any object as a byte stream.

Reflection allows getting information about a program and its elements (objects,variables, etc.) at run time using a Reflection API. An example of such reflectionfunction is get class vars(), which returns information about class variables.

Experimental extensions of PHP, which specifically address meta-programming,are the Runkit package (available at http://pecl.php.net/package/runkit), whichallows transforming classes (e.g. replace functions and methods, change classancestry, etc.) dynamically at run time using byte code modification, the AspectPHPlanguage [BK06], PHPAspect [GAR08], Aspect-Oriented PHP [SHE06] or GAP(Generic Aspects for PHP) [BK06], which introduce the concepts of aspect-orientedprogramming into PHP.

6.7 Evaluation of the Approach 107

6.7 Evaluation of the Approach2

From the viewpoint of the modification capabilities, the language implements theadvanced preprocessing. It covers not only a simple inclusion (@sub), conditionalinclusion (@if, @case), but also the generation of the ‘look-alike’ strings (@gen),repetition (@for, @rep) and other functions. The external functions combinedtogether with the text of a TL support the scripting concept, as well as the externalcomposition, that is, gluing of the external PROMOL modules into a target system(@macro).

The above-mentioned capabilities can be also seen as the external meta-programming ones because PROMOL functions manipulate with the other (target)program. From this standpoint, VHDL allows the meta-programming at someextent, that is, homogeneous meta-programming (see Chap. 4). Hence, it isinteresting to compare the ‘pure’ VHDL approach with the one, which usessimultaneously Open PROMOL and VHDL.

The meta-programming capabilities of VHDL (generic, generate, if-generate)only partially implement the separation of concerns. As a result, the pure VHDLapproach lacks flexibility for expressing and handling wide range modificationsincluding those which can overcome the limitations of the synthesis tools [Cha97].The attempts to express functionality in the generalized form may lead to the over-generalization problem [Sam97, SZDC02].

On the other hand, the usage of Open PROMOL can cause some problems,which are not known in the pure VHDL approach. Those are the naming problem(the developer himself should care that every instance of a generic componenthas a unique name) and name clashing (multiple instances with the same namecan be generated). These problems have to be solved at a higher level (e.g. bya system generator). Other problems relate to the multi-language programmingitself, such as learning (different languages and environments have to be mastered),reliability (less maturity and experience of usage), testing (of instances as well asgeneric components) and pretty printing. These problems can be solved using theappropriate methodology.

The comparison is given in Tables 6.5 and 6.6. The accepted notations 1LAand 2LA mean the one-language approach (i.e. homogeneous meta-programming inVHDL) and two-language approach (VHDLCOpen PROMOL, i.e. heterogeneousmeta-programming), respectively. The framework of the comparison is a statementof features (in positive sense) and problems that are evaluated abstractly by weights(in negative sense), respectively [SZDC02, Zib01].

We summarize the strength of Open PROMOL as a tool for implementing themulti-language-programming paradigm to describe the transformational processes(modification, generation, wrapping, etc.) in the variety of application domains.

2Section 6.7 reproduced with kind permission from Springer Science+Business Media B.V.

108 6 Open PROMOL: A Meta-Language for Heterogeneous Meta-Programming

Table 6.5 Comparison of1LA and 2LA by features([SDZ02]. With kindpermission from SpringerScienceCBusiness MediaB.V.)

Features Weight

Integration1LA

2LA

Maturity1LA

2LA

Adaptability forsynthesis limitations

1LA2LA

Rapid prototyping 1LA2LA

Automatic documentationgeneration

1LA2LA

Table 6.6 Comparison of1LA and 2LA by problems([SDZ02]. With kindpermission from SpringerScienceCBusiness MediaB.V.)

Problems Weight

Interfacing capabilities 1LA 2LA

Naming 1LA2LA

Over-generalization: designer’s viewpoint

1LA 2LA

Over-generalization: user’s view point1LA

2LA

Pretty printing 1LA2LA

Dependence from a target language1LA

2LA

Generalization dependency uponalgorithm and/or architecture 1LA

2LA

6.8 Summary, Current State of the Languageand Conclusions

We have described the core aspects (i.e. the concept, syntax, semantics andcapabilities) of the dedicated meta-language Open PROMOL we have developed.We treat Open PROMOL not only as a meta-language but also as a scriptinglanguage because it enables to specify scripting of syntactically complete structuresof a target language. Open PROMOL is a functional language aiming to describethe wide range textual modifications of a target program. The language is a setof external functions independent upon any target language syntax to perform thenecessary modifications. The language supports design reuse through the deepand flexible parameterization. The Open PROMOL specification is a higher-leveldescription, which manipulates with a target program as data.

We have also evaluated the approach by providing a comparative study(Open PROMOL vs. Java as a meta-language). The study has showed that a

6.9 Exercise Questions 109

general-purpose programming language (usually its subset) can be used as ameta-language to support heterogeneous meta-programming (in Chap. 14, we willdemonstrate that using also PHP).

We were using and till now are using the language and its processor as anexperimental tool. The language (and its processor) is beneficial to use in thefollowing cases for teaching and research: (1) to learn and understand the basicsof heterogeneous meta-programming, (2) to better understand the preprocessinglanguages because Open PROMOL functions, in fact, extend and generalize thepreprocessing concept, (3) to demonstrate an easy way to construct compilerssemi-automatically (e.g. using Lex and Yacc) because the compiled language canbe represented as a few external functions only, (4) to develop and test programgenerators (generative components) for well-understood domains and, in this way,to demonstrate generative reuse and (5) to investigate the program modification,specialization, changeability and evolution.

Over more than 10 years, the current version of the language processor has passedthrough the intensive experiments by more than 500 users, mostly postgraduatestudents. From the current perspective, the main drawback of the language is itsexperimental status and the lack of internet support. Knowing that, we advise readersnot to restrict themselves by using one meta-language instead to try and test otherlanguages such as PHP.

This is the final chapter of Part I, in which we discussed the basics of meta-programming including the introduction to the topic, backgrounds and kinds ofmeta-programming based on domain-specific languages (such as VHDL). As, ingeneral, meta-programming is a generalization of programming and generalizationmay have many different aspects and views, we provide a deeper insight into theissues in the remaining parts of the monograph.

6.9 Exercise Questions

6.1. Clarify the terms ‘program modification’ (as it is used in software reuseliterature) and ‘program change’ (as it is used in software maintenance andevolution).

6.2. What operations are needed to cover all kinds of program text modifications?6.3. How does program modification work in preprocessing systems (e.g.

C/CCC)?6.4. Classify Open PROMOL functions according to basic operations as defined by

structural programming.6.5. Use Open PROMOL processor (see address in Sect. 6.7) and test examples of

meta-functions given in Tables 6.1 and 6.2.6.6. Use Open PROMOL processor (see address in Sect. 6.7) and test meta-

programs given in Figs. 6.2 and 6.3.6.7. Rewrite meta-programs of Figs. 6.2 and 6.3 using (a) Java as a meta-language

and using (b) PHP as a meta-language.

110 6 Open PROMOL: A Meta-Language for Heterogeneous Meta-Programming

6.8. Provide a comparative study of the solutions of Exercises 6.6 and 6.7 in termsof capabilities of meta-interface and meta-body for three languages: OpenPROMOL, Java and PHP.

References

[BAA09] Benestad AC, Anda B, Arisholm E (2009) Understanding software maintenanceand evolution by analyzing individual changes: a literature review. J Softw MaintEvol Res Pract 21:349–378

[Bas97] Bassett PG (1997) Framing software reuse: lessons from the real world. PrenticeHall Inc., Upper Saddle River

[Bec00] Beck K (2000) Extreme programming explained. Addison-Wesley, Reading[Bec10] Beck K (2010) The inevitability of evolution. IEEE Softw 27(4):28–29[Bec99] Beck K (1999) Embracing change with extreme programming. Computer

32(10):70–77[BK06] Bergmann S, Kniesel G (2006) GAP: generic aspects for PHP. In: Proceedings of

the EWAS 2006 – third European workshop on aspects in software. 31 August2006, Enschede

[BMZ+03] Buckley J, Mens T, Zenger M, Rashid A, Kniesel G (2003) Towards a taxonomy ofsoftware change. J Softw Maint Evol Res Pract 17(5):309–332

[Boe10] Boehm B (2010) The changing nature of software evolution. IEEE Softw 27(4):26–28

[Cha97] Chang KC (1997) Digital design and modeling with VHDL and synthesis. IEEEComputer Society Press, Los Alamitos

[CHM+99] Coste P, Hessel F, Ph Le Marrec, Sugar Z, Romdhani M, Suescun R, Zer-gainoh N, Jerraya AA (1999) Multilanguage design of heterogeneous systems.In: Proceedings of the 7th international conference on hardware/software codesign(CODES’99), 3–5 May, Rome. ACM Press, New York

[Der02] Deridder D (2002) Facilitating software maintenance and reuse activities with aconcept-oriented approach. Programming Technology Laboratory, Vrije Univer-siteit Brussel, Brussels, Belgium. http://prog.vub.ac.be. 15 May 2002

[DKV00] van Deursen A, Klint P, Visser J (2000) Domain-specific languages: an annotatedbibliography. SIGPLAN Notices 35(6):25–35

[DKV02] van Deursen A, Klint P, Visser J (2002) Domain-specific languages. In: Theencyclopedia of library and information science. Marcel Dekker, New York

[Fel03] Felici M (2003) Taxonomy of evolution and dependability. LFCS, School ofInformatics, The University of Edinburgh

[Flu07] Fluri B (2007) Assessing changeability by investigating the propagation of changetypes. In: Proceedings of the 29th international conference on software engineering(ICSE’07 Companion), Minneapolis

[Fow99] Fowler M (1999) Refactoring: improving the design of existing programs. Addison-Wesley, Reading

[GAR08] Garcia JE (2008) Aspect-oriented web development in PHP. Doctoral symposiumon informatics engineering DSIE’08, Porto, Portugal

[GG08] Godfrey MW, German DM (2008) The past, present, and future of software evo-lution. University of Waterloo/University of Victoria, Canada. http://plg.uwaterloo.ca/�migod/papers/2008/icsm08-fosm.pdf

[GKK08] Grover PS, Kumar R, Kumar A (2008) Measuring changeability for generic aspect-oriented systems. SIGSOFT Softw Eng Notes 33(6):1–5

[GMM05] Gabrysiak G, Marr S, Menge F (2005) Meta programming and reflection in PHP.Hasso-Plattner Institute, at the University of Potsdam, Germany. http://instantsvc.sourceforge.net/docs/metaprogramming-and-reflection-with-php-paper.pdf

References 111

[GSC+06] Gupta A, Slyngstad OPN, Conradi R, Mohagheghi P, Rønneberg H, Landre E(2006) An empirical study of software changes in industry – origin, priority leveland relation to component size. In: ICSEA’06, 29 October–3 November 2006,Tahiti, French Polynesia. IEEE CS Press, pp 12–19

[GV00] Givargis T, Vahid F (2000) Parameterized system design. In: Proceedings ofthe eighth international workshop on hardware/software codesign CODES’ 2000.ACM Press, New York

[HP10] He D, Periyasamy K (2010) Exploring dynamic compilation facility in Java.In: Midwest instruction and computing symposium (MICS), 16–17 April 2010,Wisconsin

[Hud98] Hudak P (1998) Modular domain specific languages and tools. In: Devanbu P,Poulin JS (eds) Proceedings of the 5th international conference on software reuse;2–5 June 1998, Victoria. IEEE Computer Society Press, Los Alamitos

[IEEE99] Special issue on domain-specific languages. In: Wile, DS, and Ramming, JC (eds)IEEE Trans Softw Eng 25(3), May/June 1999

[JE99] Jerraya AA, Ernst R (1999) Multi-language system design. In: Proceedings of thedesign, automation and test in Europe (DATE 1999); 9–12 March, Munich. ACMPress, New York

[JRM+99] Jerraya AA, Romdhani M, Ph Le Marrec, Hessel F, Coste P, Valderrama C,Marchioro GF, Daveau JM, Zergainoh NE (1999) Multilanguage specificationfor system design and codesign. In: Jerraya AA, Mermet J (eds) System-levelsynthesis. Kluwer Academic Publishers, Boston

[KLB+08] Kosar T, Lopez PEM, Barrientos PA, Mernik M (2008) A preliminary studyon various implementation approaches of domain-specific language. Inf SoftwTechnol 50(5):390–405

[KOM+10] Kosar T, Oliveira N, Mernik M, Pereira MJV, Crepinsek M, da Cruz D, HenriquesPR (2010) Comparing general-purpose and domain-specific languages: an empiri-cal study. ComSIS 7(2), Special Issue: 247–264

[MDJ02] Mens T, Demeyer S, Janssens D (2002) Formalising behaviour preserving programtransformations. In: Corradini A, Ehrig H, Kreowski H-J, Rozenberg G (eds)Graph transformation, proceedings of the first international conference, ICGT2002, Barcelona, Spain, 7–12 October. LNCS, vol 2505. Springer, Heidelberg, pp286–301

[OPH+09] Oliveira N, Pereira MJV, Henriques PR, da Cruz D (2009) Domain-specific lan-guages: a theoretical survey. http://inforum.org.pt/INForum2009/docs/full/paper86.pdf

[Ous98] Ousterhout JK (1998) Scripting: higher level programming for the 21st century.IEEE Comput 31(3):23–30

[Raj06] Rajlich V (2006) Changing the paradigm of software engineering. Commun ACM49(8):67–70

[RL00] Ramil JF, Lehman MM (2000) Cost estimation and evolvability monitoring forsoftware evolution processes. In: WESS 2000 workshop on empirical studies ofsoftware maintenance, San Jose, 14 Oct 2000

[RL07] Robbes R, Lanza M (2007) A change-based approach to software evolution.Electron Notes Theor Comput Sci 166:93–109

[Sam97] Sametinger J (1997) Software engineering with reusable components. Springer,Berlin

[Sch99] Schneider JG (1999) Components, scripts, and glue: a conceptual frameworkfor software composition. PhD thesis, University of Bern, Institute of ComputerScience and Applied Mathematics

[SD09]ˇ Stuikys V, Damasevicius R (2009) Measuring complexity of domain modelsrepresented by feature diagrams. Inf Technol Control 38(3):179–187

[SHE06] Sheiko D (2006) Aspect oriented software development in PHP. PHP Archit 5(4):17–25

112 6 Open PROMOL: A Meta-Language for Heterogeneous Meta-Programming

[SKL06] Sklar D (2006) Metaprogramming with PHP. In: PHP Conference 2006, New York[SN99] Schneider JG, Nierstrasz O (1999) Components, scripts and glue. In: Barroca L,

Hall J, Hall P (eds) Software architectures — advances and applications. Springer,Heidelberg

[SS05] Shah NA, Skjellum A (2005) A metaprogramming approach to generating opti-mized code for algorithms in linear algebra. In: Proceedings of the ACMSE’05,18–20 March 2005, Atlanta

[SDZ02]ˇ Stuikys V, Damasevicius R, Ziberkas G (2002) Open PROMOL: an experimentallanguage for domain program modification. In: Mignotte A, Vilar E, Horobin L(eds) System on chip design languages. Kluwer Academic Publishers, Boston, pp235–246

[SDZ+02]ˇ Stuikys V, Ziberkas G, Damasevicius R, Majauskas G (2002) Two approaches fordeveloping generic components in VHDL. Microelectron J 33:271–277, Oxford:Elsevier Science Ltd

[Vel95] Veldhuizen T (1995) Using CCC template metaprograms. CCC Rep 7(4):36–43[Vid09] Vidacs L (2009) Software maintenance methods for preprocessed languages.

Summary of the PhD dissertation, Institute of Informatics, University of Szeged[Vis07] Visser E (2007) WebDSL: a case study in domain-specific language engineering. In:

Lammel R, Saraiva J, Visser J (eds) Generative and transformational techniques insoftware engineering (GTTSE 2007), Lecture notes in computer science. Springer,Berlin

[Win04] Winter VL (2004) Program transformation: what, how and why. In: Wah BW (ed)Wiley encyclopedia of computer science and engineering. Wiley, Hoboken

[Zib01] Ziberkas G (2001) Analysis of component-based program generation methodsof an application domain. Doctorial dissertation, Technical Sciences, InformaticsEngineering, Kaunas University of Technology