[ACM Press the 3rd ACM international workshop - San Diego, CA, USA (2003.09.19-2003.09.19)]...

8
Context-Oriented Programming Roger Keays ninth ave (dot net) Brisbane, Australia [email protected] Andry Rakotonirainy CARRS-Q Queensland University of Technology Brisbane, Australia [email protected] ABSTRACT In an environment where computing power is ubiquitous, software engineers need to cater for many different variables beyond their control. They face what has been termed the pervasive problem. Their products need to be adaptable and portable, yet still retain a simple code base. Context- Oriented Programming (COP) is a new method of program- ming which aims to alleviate these problems by incorpo- rating context as a first-class construct of a programming language, much in the same way that variables, classes, and functions form the first-class constructs of many modern lan- guages. A context-oriented program is one with many ‘gaps’ or ‘open-terms’, and the context-filling operation completes such a program by dynamically selecting portions of code from a repository of candidates to fill these gaps. This selection process is based on the execution context of the program and a description of the open-term’s requisites. This paper describes the requirements for COP, focusing on this fundamental operation of context-filling. An imple- mentation which meets many of these requirements is also presented. Categories and Subject Descriptors: D.3.3 [Language Classifications]: Multiparadigm Languages General Terms: Design, Experimentation, Languages, The- ory. Keywords: Context-oriented programming, context, pro- gramming, ubiquitous, pervasive, mobile. 1. INTRODUCTION Pervasive computing is a computing paradigm in which a variety of devices (computers, entertainment units, embed- ded chips in our cars, clothing appliances, mobile phones etc.) carry out computing in a relatively non-intrusive man- ner in order to support and improve many aspects of work and everyday activities. As stated by ubiquitous and perva- sive research communities, users and computers are becom- 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. MobiDE’03, September 19, 2003, San Diego, California, USA. Copyright 2003 ACM 1-58113-767-2/03/0009 ...$5.00. ing increasingly mobile and as the diversity of interacting devices proliferates, pervasive computation is becoming dif- ficult to predict and understand due to the complexity and the fluidity of the surrounding environment, or context. Pervasive computing has reached a level that puts it be- yond our ability to deploy, manage and keep functioning correctly through traditional programming techniques. For example, connecting to a database is no longer a trivial task: What transport protocols are available? What carriers are available? Where is the nearest mirror? What software does the server run? What is the level of SQL support? A cre- ative developer might choose to issue a database transaction over SMTP rather than a direct TCP stream because of its higher reliability in pervasive environments. Future scientists and engineers need programming tools that take into account the dynamic and complex characteris- tics of pervasive systems. COP (Context Oriented Program- ming) is a novel programming approach aimed at support- ing pervasive computation. It is a method of programming which aims to alleviate the pervasive problem (of adaptabil- ity, portability and complexity) that arises from continual change of context. 2. CONTEXT-ORIENTEDPROGRAMMING 2.1 Vision In practical terms COP allows the authoring of program skeletons, which are pieces of software that contain a num- ber of open terms. Open terms are simply gaps in a pro- gram, which specify a goal and context. Actual code to replace them is selected dynamically from a number of stubs in a context-dependant fashion. This idea is referred to as context-filling (figure 1). Context-filling is the distinguishing feature of COP, the result being a separation of code into a context-free skeleton and context-dependant stubs. Table 1 compares COP with other methods of programming. 2.2 Approach Four new programming constructs — goals, contexts, open terms and stubs — described in detail in section 4, form the backbone of COP. Goals and context are first-class, mean- ing they have syntax, operations and can be referenced; open terms are second-class, meaning they have syntax and oper- ations; and stubs are third-class — simply having syntax. Goals are used to describe the purpose of an entity. For example, the goal of an open term might be to greet the user, or output information in some (undefined) way. By 9

Transcript of [ACM Press the 3rd ACM international workshop - San Diego, CA, USA (2003.09.19-2003.09.19)]...

Page 1: [ACM Press the 3rd ACM international workshop - San Diego, CA, USA (2003.09.19-2003.09.19)] Proceedings of the 3rd ACM international workshop on Data engineering for wireless and mobile

Context-Oriented Programming

Roger Keaysninth ave (dot net)Brisbane, Australia

[email protected]

Andry RakotonirainyCARRS-Q

Queensland University of TechnologyBrisbane, Australia

[email protected]

ABSTRACTIn an environment where computing power is ubiquitous,software engineers need to cater for many different variablesbeyond their control. They face what has been termed thepervasive problem. Their products need to be adaptableand portable, yet still retain a simple code base. Context-Oriented Programming (COP) is a new method of program-ming which aims to alleviate these problems by incorpo-rating context as a first-class construct of a programminglanguage, much in the same way that variables, classes, andfunctions form the first-class constructs of many modern lan-guages.A context-oriented program is one with many ‘gaps’ or

‘open-terms’, and the context-filling operation completes sucha program by dynamically selecting portions of code froma repository of candidates to fill these gaps. This selectionprocess is based on the execution context of the programand a description of the open-term’s requisites.This paper describes the requirements for COP, focusing

on this fundamental operation of context-filling. An imple-mentation which meets many of these requirements is alsopresented.

Categories and Subject Descriptors: D.3.3 [LanguageClassifications]: Multiparadigm Languages

General Terms: Design, Experimentation, Languages, The-ory.

Keywords: Context-oriented programming, context, pro-gramming, ubiquitous, pervasive, mobile.

1. INTRODUCTIONPervasive computing is a computing paradigm in which a

variety of devices (computers, entertainment units, embed-ded chips in our cars, clothing appliances, mobile phonesetc.) carry out computing in a relatively non-intrusive man-ner in order to support and improve many aspects of workand everyday activities. As stated by ubiquitous and perva-sive research communities, users and computers are becom-

Permission to make digital or hard copies of all or part of this work forpersonal or classroom use is granted without fee provided that copies arenot made or distributed for profit or commercial advantage and that copiesbear this notice and the full citation on the first page. To copy otherwise, torepublish, to post on servers or to redistribute to lists, requires prior specificpermission and/or a fee.MobiDE’03, September 19, 2003, San Diego, California, USA.Copyright 2003 ACM 1-58113-767-2/03/0009 ...$5.00.

ing increasingly mobile and as the diversity of interactingdevices proliferates, pervasive computation is becoming dif-ficult to predict and understand due to the complexity andthe fluidity of the surrounding environment, or context.Pervasive computing has reached a level that puts it be-

yond our ability to deploy, manage and keep functioningcorrectly through traditional programming techniques. Forexample, connecting to a database is no longer a trivial task:What transport protocols are available? What carriers areavailable? Where is the nearest mirror? What software doesthe server run? What is the level of SQL support? A cre-ative developer might choose to issue a database transactionover SMTP rather than a direct TCP stream because of itshigher reliability in pervasive environments.Future scientists and engineers need programming tools

that take into account the dynamic and complex characteris-tics of pervasive systems. COP (Context Oriented Program-ming) is a novel programming approach aimed at support-ing pervasive computation. It is a method of programmingwhich aims to alleviate the pervasive problem (of adaptabil-ity, portability and complexity) that arises from continualchange of context.

2. CONTEXT-ORIENTED PROGRAMMING

2.1 VisionIn practical terms COP allows the authoring of program

skeletons, which are pieces of software that contain a num-ber of open terms. Open terms are simply gaps in a pro-gram, which specify a goal and context. Actual code toreplace them is selected dynamically from a number of stubsin a context-dependant fashion. This idea is referred to ascontext-filling (figure 1).Context-filling is the distinguishing feature of COP, the

result being a separation of code into a context-free skeletonand context-dependant stubs. Table 1 compares COP withother methods of programming.

2.2 ApproachFour new programming constructs — goals, contexts, open

terms and stubs — described in detail in section 4, form thebackbone of COP. Goals and context are first-class, mean-ing they have syntax, operations and can be referenced; openterms are second-class, meaning they have syntax and oper-ations; and stubs are third-class — simply having syntax.Goals are used to describe the purpose of an entity. For

example, the goal of an open term might be to greet theuser, or output information in some (undefined) way. By

9

Page 2: [ACM Press the 3rd ACM international workshop - San Diego, CA, USA (2003.09.19-2003.09.19)] Proceedings of the 3rd ACM international workshop on Data engineering for wireless and mobile

Paradigm Distinguishing featureProcedural Code organised sequentially, possibly encapsulated in libraries.Functional All constructs are functions.Object-Oriented Code encapsulated into task-specific objects. The objects have

methods which are called to access the objects code-base.Aspect-Oriented Code organised by common theme, not executed sequentially.

Weaving creates an executable program from a number of as-pects.

Context-Oriented Code organised into context-free skeleton and context-dependant stubs. Context-filling creates an executable programfrom the skeleton.

Table 1: Comparison of programming paradigms.

location = Australia

print "G’day!"

Skeleton

Stubs

<goal>greet</goal> <context>location</context></gap>

<gap>

location = France

print "Tjena!"

print "Salut!"

location = Sweden

Figure 1: Context-filling

using goals in the declaration of open terms, a more flexiblecontext-filling operation can be written which does not relyon the prior knowledge of an entities name. This is a fairassumption for pervasive environments.Context, which refers to any information that may have

impact on the behaviour of the program, is used by openterms and stubs to limit or describe their domain of valid-ity. The context of the executing host, or execution context,is considered during context-filling to select a stub that ismost appropriate for the given open term. For example,the context location:Australia and device:file mightresult in an open term being filled with a stub which greetsthe user in an Aussie way, or outputs information by writingit to disk.Although not examined here, it should be noted that COP

requirements also makes allowance for non-procedural exe-cution of code through the use of events. If an open termis associated with an event, it will be filled (and executed)when that event occurs. This would allow the developer,for example, to write a program which greets the user inthe locally spoken language when he or she enters a newcountry.Table 2 shows examples of code with open terms where

they could be replaced with programming primitives suchas operators, statements, terms, method calls, objects andothers. In this table, [?](ctx, gl) represents an open termassociated which a context and a goal.No requirements have been specified in regards to which

hardware and software technologies must be used to informthe skeleton of execution context. Context-oriented pro-

grams are independant of such architecture and each exe-cuting host may use whichever technologies it has access to.

3. RELATED WORKSeveral studies have suggested new concepts to deal with

pervasive systems. None of them proposed a practical lan-guage that takes context as first class contruct.There is a strong trend towards the authoring of appli-

cations that are context-aware. GUIDE is a context-awareelectronic tour guide [2] which creates customised tours aroundLancaster based on context such as location, available timeand money, users interests and the weather. GUIDE makesgreat inroads into assisting the development of adaptablesoftware which responds to its environment, however it isreliant on a specific programming language and various lay-ers of abstraction. In contrast, COP aims to remove theselayers and provide adaptable software directly from the com-piler or interpreter.Significant theoretical work exists on defining calculi for

contexts. The most noticeable work are: Mobile ambientwork by Cardelli and Gordon [1] and the calculi presentedby Sands [6] and Hashimoto [5]. Mobile ambients describethe navigation of mobile processes through contexts definedas administrative domains (e.g. a country), while the cal-culi are provide lemmas and proofs which show that contextand contextual operations can exist as first-class conceptsof a language. These theoretical works do not provide apragmatic programming language for software builders.

4. COP REQUIREMENTS

4.1 DefinitionsTo begin, it is important to have a clear idea of what

is meant by the term ‘first-class’ — which is used oftenamongst the computer science community but suffers frompoor definition. Second and third-class constructs are lessfrequently referred to, but also need defining. The defini-tions presented below were adopted from descriptions offirst-class functions as applied to functional languages [7].They are primarily used to distinguish between the capabil-ities of different COP constructs.

First-class A first-class construct is one which is an intrin-sic element of a language. The following propertiesmust hold.

• It must form part of the lexical syntax of the lan-guage

• It may have operators applied to it

10

Page 3: [ACM Press the 3rd ACM international workshop - San Diego, CA, USA (2003.09.19-2003.09.19)] Proceedings of the 3rd ACM international workshop on Data engineering for wireless and mobile

0. [?](ctx, gl, ev?) Statement as an open term1. W = 1 * [?](ctx, gl) Term as an open term2. W = 1 [?](ctx, gl) 5 Operator as an open term3. SomeObject.[?](ctx, gl) Method call as an open term4. if ([?](ctx, gl)) { print "Hello } Expression as an open term5. System.out.println([?](ctx, gl).toString()) Object instance as an open term

(context-oriented dispatching)6. (([?](ctx, gl)) SomeObject).clone() Cast as an open term (context-

oriented polymorphism)

Table 2: Open terms as a first-class programming construct

• It must be referencable (for example stored in avariable)1

Second-class A second-class construct is one which is anintrinsic element of a language with the following prop-erties.

• It must form part of the lexical syntax of the lan-guage

• It may have operators applied to it

Third-class A third-class construct is one which forms partof the syntax of a language.

Table 3 summarises these definitions and shows whereeach of the constructs of COP belong.

4.2 Context-fillingThe context-filling operation is the hallmark of COP (fig-

ure 1). It is the process where open terms are replaced bystubs and consists of two phases. In the first phase (match-ing) a single stub is selected from a number of candidatesto fill an open term. The second stage (binding) binds anystub parameters with skeleton variables in relevant scopesso the code can be executed.The requirements for the context-filling operation are as

follows.

R1.1 Transparent The developer and user are unawareof the matching (between open terms and stubs) andbinding process that is occurring during context-filling.

R1.2 Uses goal information Stub selections are made giv-ing consideration to information available about thegoals of the open term and the stub.

R1.3 Uses context knowledge Stub selections are madegiving consideration to information available about thecontext of the open term, the stub and the executioncontext.

R1.4 Uses partial context knowledge Where the exe-cution context does not include information requiredby an open term’s context, a stub selection can still bemade using that information which is available.

R1.5 Uses inferred context knowledge A knowledge baseexists that allows inferences to be made about con-texts. For example if the fact “Paris is in France” isknown, the context Location:Paris will be acceptedas a match of the context Location:France.

1Since first-class constructs are referencable it follows thatthey may be passed as parameters to functions or returnedas a function results.

R1.6 Selects closest match The stub whose goals andcontext most closely match those of the open term willalways be selected.

R1.7 Scoping Where open terms are nested, those vari-ables from each of the stubs that are declared ‘bound’,effectively bind into the same scope.

4.3 ContextThe term context is defined as any information that can

be used to characterise the situation of an entity. An entityis a person, place or object that is considered relevant to theinteraction between a user and an application, including theuser and application themselves [3]. Some examples of con-text include location, company policy, resource availability,hardware and software environment, physical environment,user identity and the goals of the user.The requirements for context in COP are as follows.

R2.1 First-class Context is a first-class construct, as de-fined above.

R2.2 Context representation In its simplest form, con-text may be represented as attribute/value tuples, suchas bandwidth:2Mbps or screen-size:small. However,a COP language should have more elaborate featuressuch as being able to express the contexts “the band-width varies by ± 1Mbps” and “the students can seethe screen”.

Context that is declared with no values specifies onlyits existence and can be used by open terms to indi-cated that stub selection should consider this context.

R2.3 Operations Valid operations on context are disjunc-tion, conjunction, subtraction, negation and compar-isons.

R2.4 Inheritance A context may be declared as an ex-tension of an existing context, in which case only newor overridden contextual information needs to be de-clared.

R2.5 Comparable A context must be comparable to an-other on a continuous scale which represents how sim-ilar they are (not only ‘equal’ or ‘not equal’).

R2.6 Associations Context can be associated with openterms and stubs. When a context is associated with astub it defines the contextual domain for that stub, i.ewhat context that stub is valid for. When a contextis associated with an open term it defines the contextunder consideration when a stub is to be found, or thecontextual domain for that open term.

11

Page 4: [ACM Press the 3rd ACM international workshop - San Diego, CA, USA (2003.09.19-2003.09.19)] Proceedings of the 3rd ACM international workshop on Data engineering for wireless and mobile

Syntax Operators Referencable COP constructFirst class Yes Yes Yes Context, GoalsSecond class Yes Yes No Open termsThird class Yes No No Stubs

Table 3: First, second and third-class constructs in COP

4.4 GoalsGoals are used to describe in generic terms what entities

represent. They are an important part of COP given thatskeletons are authored for a pervasive environment. In thisenvironment the assumption is made that the developer maynot know the names of the services and functions that areavailable and cannot therefore refer to them by name. Goalsare used to alleviate this problem.The requirements of goals are as follows.

R3.1 First-class Goals are first-class constructs as definedabove.

R3.2 Knowledge representation Goals need to have mean-ing to both humans and computers.

R3.3 Operations Valid operations on goals are disjunc-tion, conjunction, subtraction and negation. Addition-ally, the composition operation merges the semanticsof goals. For example the goal representing a credit toan account could be composed with a goal represent-ing a debit to another account to produce a third goalfor transferring money between accounts.

R3.4 Inheritance A goal may be declared by extendingan existing goal, adding or overriding information init.

R3.5 Comparable A goal must be comparable to anotheron a continuous scale which represents how similarthey are (not only ‘equal’ or ‘not equal’).

R3.6 Associations Goals can be associated with open terms,stubs, variables and parameters.

4.5 Open termsAn open term is a place-holder for a context-dependant

section of a program. They are associated with a goal anda context and are replaced with a stub at runtime by thecontext-filling operation. Their requirements are as follows.

R4.1 Second-class Open terms are a second-class construct,as defined above.

R4.2 Is associated with a goal An open term is associ-ated with a goal which provides information to assistselecting the stub that will replace it.

R4.3 Is associated with a context An open term is as-sociated with a context which may i) specify what con-textual information to consider during context-fillingand/or ii) restrict the contextual domain that the openterm is valid in, such that an open term may not befilled at all.

R4.4 May be associated with events When an open termis associated with an event the context-filling opera-tion will only occur when this event occurs. If the

open term represents a statement the filled term willbe executed at this time. For example, the psuedo-cprogram in figure 2 will greet the user appropriatelywhenever his or her location changes.

Valid events are enter, exit, change and discover andrefer to the context associated with an open term.

enter Occurs when a context goes from being invalid(not within the domain of the execution context)to being valid (within the domain of the executioncontext).

exit Occurs when a context goes from being valid tobeing invalid.

change Occurs when any information in the execu-tion context that is also in the (valid) contextchanges.

discover Occurs when information from a context be-comes a part of the execution context.

R4.5 Are ubiquitous An open term may be used in theplace of any first or second-class programming con-struct and some third-class constructs. Invalid third-class constructs include lexical keywords (such as if,while and break) and structural tokens (such as {, ;and ’).

R4.6 May be nested If an open term is filled by a stubwhich contains another open term, the second is filledin the same manner as the first.

R4.7 Operations The only valid operation on a open termis the composition of two other open terms which cre-ates a new term whose goal is the composition of thetwo terms goals’ and whose context is the conjunctionof the two terms contexts’.

R4.8 Inheritance Open terms may inherit goals and con-text from other open terms, adding to them or over-riding them.

4.6 StubsStubs are sections of code associated with a goal and

a context that are used to replace open terms during thecontext-filling operation. They have the following require-ments.

R5.1 Third-class Stubs are a third-class construct, as de-fine above.

R5.2 Is associated with a goal A stub has a correspond-ing goal which provides information for the context-filling operation when an open term is filled.

R5.3 Is associated with a context A stub’s context spec-ifies its valid contextual domain.

12

Page 5: [ACM Press the 3rd ACM international workshop - San Diego, CA, USA (2003.09.19-2003.09.19)] Proceedings of the 3rd ACM international workshop on Data engineering for wireless and mobile

void main() {

/∗ an open term which is filled and executed whenever location changes ∗/[?] ( goal : greet user , context: location , event:change)

/∗ wait for context change ∗/while (1) {}

}Figure 2: Open terms may be associated with events

R5.4 May use parameters A stub may contain referencesto variables that are not declared within the stub.Such variables may be bound to those in the scopeof the host skeleton and are referred to as the stubsparameters.

R5.5 Parameters bound by goal A stubs parameters can-not be bound to a skeletons variables on a naming ba-sis. This is due to the assumption that developers arenot aware of the names of entities in a pervasive envi-ronment. Instead, parameters and variables must beassociated with a goal and these are matched in thesame way as open terms and stubs.

R5.6 Bound, half-bound and unbound parameters Stubsmust support three different types of parameters. Boundand half bound parameters get their value from thehost skeleton, however only changes made to boundparameters retain these changes in the host skeleton’sscope. Unbound parameters exist independently in thescope of the stub.

R5.7 Optional parameters Stubs should support param-eters that are optional, either because a null value isacceptable or they have a default value.

R5.8 Default parameters Stub parameters may be givendefault values.

R5.9 Functions as stubs Normal functions can be usedas stubs through the use of a wrapper.

5. IMPLEMENTATIONIn order to meet as many of these requirements as pos-

sible, two important decisions were made. The first was touse an existing programming language rather than creatinga new one, and the second was to use the existing featuresof that language without modifying its grammar or compila-tion/execution model. The implication of the latter decisionis that (in this implementation) none of the constructs maybe considered first, second or third class.The Python language was chosen primarily because of its

flexible scoping abilities. Additionally, the implementationallows only statements (and not terms, operators and soforth) to be left as open terms. This is achieved by insertinga call to the fill gap() routine which initiates the context-filling process.Context-filling is not completed by the python interpreter

itself but instead relies on IPC with a separate process — thematchbox (figure 3). The matchbox is essentially a storagearea for stubs that have been registered prior to the context-filling operation. Stubs can be registered by local or remoteclients as well as stored in an existing database on disk.

Variables can also be registed and the purpose of this is toassist the binding of stub parameters to variables in the hostskeleton.In describing the implementation it is useful to partitions

the requirements into three domains: typing, matching andbinding, described in turn below.

5.1 TypingTyping addresses syntax and representation problems as-

sociated with the incorporation of COP constructs into aprogramming language. How are open terms and stubs lex-ically represented? How can goals be represented such thatthey have meaning to both humans and machines? What isthe best way to represent context?The approach adopted is to give open terms, stubs and

variables individual types which include representations oftheir goal, context (if any) and other relevant features. Astypes contain all the necessary information about such enti-ties they are used for all registration and matching processes,i.e. variable types are registered; open term and stub typesare matched.XML has been adopted for typing because of its popu-

larity, openness and human readable syntax. The <goal>node of a type represents the purpose of the typed entity andmay contain the tags <modify>, <inform>, <discover>,<action> and<represent> to express this purpose. Thesefive elements in turn contain a number of children (who,what, when, where and so forth) that can be used to de-scribe the subject or object being referred to.The<contexts> node contains children with name/value

pairs that represent which context this stub has been writtenfor. Name and value may be arbitrary strings, and numericalcontexts may have min/max attributes.

5.2 MatchingMatching involves selection of a single stub to fill an open

term based on the goals and context of that open term.Having defined a representation for open terms and stubs(by typing), how are these compared? How is executioncontext incorporated into stub selection?The decision to use a tree to tree (t2t) algorithm for

matching was driven primarily by the choice of using XMLfor typing. Such algorithms can be used to give a metric onthe differences between two trees (their edit cost).While there are several t2t algorithms, Logilab’s tool xmld-

iff.py supports both the Extended Zhang and Shasha (ezs)[8, 4] and Fast Match / Edit Script (fmes) algorithms. It hasbeen used for this reason and its direct support for xml de-scriptions. The open source nature of the tool has allowedthe ezs algorithm to be modified to fit the exact needs ofthe application (referred to as the modified ezs algorithm,or just mezs).

13

Page 6: [ACM Press the 3rd ACM international workshop - San Diego, CA, USA (2003.09.19-2003.09.19)] Proceedings of the 3rd ACM international workshop on Data engineering for wireless and mobile

0) Execution context is kept current via the elvin notification service (seehttp://elvin.dstc.edu.au).1) Skeleton requests a context-filling operation.2) A stub is selected from a database of stubs.3) Necessary modifications are made to the stub for binding and the codeis returned for execution.

Figure 3: Context-filling is a three step process.

Both the ezs and fmes algorithms suffer from poor timecomplexity and as such, a simple, fast algorithm has alsobeen written. This algorithm takes an XML type, andsearches another for each of the leaf nodes found in the first.If a node is not found, or is found but has a different valuethe edit cost of the comparison is incremented. It is notdesigned to detect subtle differences in open term and stubtypes such as the renaming of a <with> tag to a <what>tag, but has proven to be useful for testing and demonstra-tion.

5.3 BindingThe final phase of context-filling, binding, is concerned

with the safe replacement of an open term with a stub. Howare these stub parameters bound to the skeletons variables?How is the bound code executed?This implementation allows i) stubs to have parameters

which bind to variables within the host skeleton; ii) stub pa-rameters and skeleton variables to be bound by goal, ratherthan name; iii) flexible scoping where some stub parame-ters are bound in the host skeleton’s scope while others arenot; and iv) a number of other features such as default andoptional stub parameters and a URI schema which allowsstubs to be located locally or remotely.Stub parameters are bound to the skeletons variables by

matching their goals and not their names. To achieve this,each stub is executed in a new scope with bound and half-bound variables being copied from the previous scope. Python’sexec statement is used as a part of the fill gap() methodto execute the stub in a fresh scope.

6. WORKING EXAMPLETo demonstrate how COP can be used to write adaptable

software, a simple dynamic hello world program has beenwritten. It consists of a single open term with the goal ofgreeting the user which is location dependant. The stubswhich fill this open term contain open terms themselvesthat respond to other contexts such as weather, recipient,and the greeter’s profession. Output is device-dependant,demonstrating the portability features of COP and can ap-

pear as text on the screen, sent as an email, printed to a lineprinter, written to a file or displayed in an X-Window.Figure 4 shows some of the behaviours of this Interna-

tional Hello World skeleton when executed in different con-texts.

7. EVALUATIONThe work that has been done so far on COP has been pri-

marily for proof of concept (particularly for context-filling),and many of the requirements have been met. Table 4 showsa brief summary of which were met and how.COP addresses the pervasive problem in the following

ways:

Adaptability Context-sensitive sections of the program areleft as open terms which are filled appropriately for thecurrent context. As there is typically more than onecandidate for an open term, the skeletons behaviourwill change (adapt) according to its context while theoriginal source code remains unchanged.

Portability Device capabilities are simply another type ofcontext. Device-dependant sections of the programare left as open terms which are filled in a device-dependant fashion.

Complexity The automatic selection of the most appro-priate stub eases the developers reasoning task. Ad-ditionally, the reuseability of skeletons across softwareand hardware platforms saves the software engineerredevelopment time.

8. CONCLUSIONThe concept of COP has been introduced with the in-

tention of increasing software adaptability and portabilitywhilst still maintaining code simplicity.The paradigm addresses such issues through the inclusion

of contexts and open terms as first and second class con-structs into a language respectively.

14

Page 7: [ACM Press the 3rd ACM international workshop - San Diego, CA, USA (2003.09.19-2003.09.19)] Proceedings of the 3rd ACM international workshop on Data engineering for wireless and mobile

Requirement SupportContext-fillingR1.1 Transparent PartialR1.2 Uses goal information Yes during matchingR1.3 Uses context knowledge Yes during matchingR1.4 Uses partial context knowledge Yes tolerates incomplete execution contextR1.5 Uses inferred context knowl-edge

No

R1.6 Selects closest match Yes with the ezs algorithmR1.7 Scoping Yes by manipulating python dictionariesContextR2.1 First-class NoR2.2 Context representation Partial name/value or name/range pairs allowedR2.3 Operations Partial conjunction onlyR2.4 Inheritance Yes subtyping through ‘extends’ attributeR2.5 Comparable Yes using t2t algorithmsR2.6 Associations Yes typing associates open terms and stubs with

their contextGoalsR3.1 First-class NoR3.2 Knowledge representation Partial XML types havemeaning to humans, and are

machine parsableR3.3 Operations NoR3.4 Inheritance Yes subtyping through ‘extends’ attributeR3.5 Comparable Yes using t2t algorithmsR3.6 Associations Yes typing associates open terms, stubs and vari-

ables with goalsOpen termsR4.1 Second-class NoR4.2 Is associated with a goal Yes through typingR4.3 Is associated with a context Yes through typingR4.4 May be associated with events NoR4.5 Are ubiquitous NoR4.6 May be nested Yes open terms may appear in open termsR4.7 Operations NoR4.8 Inheritance NoStubsR5.1 Third-class NoR5.2 Is associated with a goal Yes through typingR5.3 Is associated with a context Yes through typingR5.4 May use parameters Yes these are declared in the stubs typeR5.5 Parameters bound by goal Yes during bindingR5.6 Bound, half-bound and un-bound parameters

Yes dynamic scoping allows this

R5.7 Optional parameters YesR5.8 Default parameters YesR5.9 Functions as stubs Yes existing python functions can be added to the

matchbox’s databaseTable 4: Summary of supported requirements

15

Page 8: [ACM Press the 3rd ACM international workshop - San Diego, CA, USA (2003.09.19-2003.09.19)] Proceedings of the 3rd ACM international workshop on Data engineering for wireless and mobile

$ ./04-hello-world-advanced.py

Hello world!

i) No execution context

$ ./04-hello-world-advanced.py

Bonjour

ii) Location = France

$ ./04-hello-world-advanced.py

wrote output to /tmp/out

$ cat /tmp/out

Cheers

iii) Location = Australia, device = file, job = brickie

$ ./04-hello-world-advanced.py

iv) Location = Sweden, device = x-windows, weather = good

Figure 4: Sample outputs of the International Hello World program

Context-filling, where open terms are filled by stubs in acontext-dependant fasion, is the hallmark of COP and hasbeen implemented and demonstrated in the work described.Software written using COP is i) more adaptable due

to the ability to include open terms that are filled in acontext-dependant fashion; ii) more portable since devicecapabilities are simply a type of context, allowing for device-dependant open terms and iii) less complex, as reasoningabout context is no longer the responsibility of the devel-oper.

9. REFERENCES[1] Luca Cardelli and Andrew D. Gordon. Mobile

ambients. Theoretical Computer Science,,240/1:177–213, June 2000. Special Issue onCoordination, D. Le Mtayer Editor.

[2] Keith Cheverst, Nigel Davies, Keith Mitchell, andAdrian Friday. Experiences of developing and deployinga context-aware tourist guide: the GUIDE project. InProc. of MOBICOM’2000, Boston, ACM Press., 2000,pages 20–31, 2000.

[3] A. Dey and G. Abowd. Towards a better understandingof context and context-awareness. In ProceedingsConference on Human Factors in Computing Systems:Workshop on the What, Who, Where, When and Howof Context-Awareness., 2000.

[4] Shasha D. et al. Exact and approximate algorithms forunordered tree matching. IEEE Transactions onSystems, Man and Cybernetics., 24(4), April 1994.

[5] Masatomo Hashimoto and Atsushi Ohori. A typedcontext calculus. Theoretical Computer Science,266(1-2):249–272, 2001.

[6] D. Sands. Computing with contexts: A simpleapproach. In A. D. Gordon, A. M. Pitts, and C. L.Talcott, editors, Second Workshop on Higher-OrderOperational Techniques in Semantics (HOOTS II),volume 10 of Electronic Notes in Theoretical ComputerScience. Elsevier Science Publishers B.V., 1998.

[7] R. Sethi. Programming Languages Concepts andConstructs. Addison-Wesley Publishing Company.,1989.

[8] J. et al. Wang. An algorithm for finding the largestapproximately common substructures of two trees.IEEE Transactions on Pattern Analysis and MachineIntelligence., 20(8), 1998.

16