144
AN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE PRESEXTED IN PARTIAL FULFILLMENT OF THE REQUIREMENTS FOR THE DEGREE OF MASTER OF COMPUTER SCIEKCE CONCORDIA UNIVERSITY MONTRÉAL, QUÉBEC, CANADA

AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Embed Size (px)

Citation preview

Page 1: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

AN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE

PRESEXTED I N PARTIAL FULFILLMENT OF THE REQUIREMENTS

FOR THE DEGREE OF MASTER OF COMPUTER SCIEKCE

CONCORDIA UNIVERSITY MONTRÉAL, QUÉBEC, CANADA

Page 2: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

National Library I*I of Canada Bibliothèque nationale du Canada

Acquisitions and Acquisitions et Bibliographie Services services bibliographiques

395 Wellington Street 395. me Wellington Ottawa ON K I A O N 4 Ottawa ON K I A ON4 Canada Canada

Your Me Voire rderence

Our ale Nom refdreoca

The author has granted a non- L'auteur a accordé une licence non exclusive licence allowing the exclusive permettant à la National L i b r q of Canada to Bibliothèque nationale du Canada de reproduce, loan, distribute or seil reproduire, prêter, distribuer ou copies of this thesis in microfom, vendre des copies de cette thèse sous paper or electronic formats. la forme de microfichelnlm, de

reproduction sur papier ou sur format électronique.

The author retains ownership of the L'auteur conserve la propriété du copyright in this thesis. Neither the droit d'auteur qui protège cette thèse. thesis nor substantial extracts fiom it Ni la thèse ni des extraits substantiels may be printed or otherwise de celle-ci ne doivent être imprimés reproduced without the author's ou autrement reproduits sans son permission. autorisation .

Page 3: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Abstract

An Interpreter for Ob j ec t Comprehension Query Language

Minh Hang Pham

Object Comprehensions are a new query notation introduced in 1994 by Chan

and Trinder to provide a declarative query Ianguage for object-oriented databases.

Object Comprehensions allow queries to be expressed clearly, concisely, and processed

efficiently, while incorporating many features that are missing from or inadequate

in existing object-oriented query languages such as support of object-orient a t ion.

computational power and support of collection. However t here is no ob ject-oriented

database (OOD) so far which incorporates Object Comprehension Language (OCL)

as a query interface. This paper introduces an interpreter that evaluates the OCL querp language against an in-mernory database.

Page 4: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Acknowledgement s

1 would like to thank my supervisor? Dr. Gregory Butler, for his patience and valuable

guidance.

1 am also grateful to Georges Ayoub for the explanation of his collection utility rou-

tines, Bao Dang for his mentor during the source code writing process, and Darma-

lingum Muthiayen for his big help around the lab and particularly for his friendship

which makes my school life much more enjoyable.

My special words of gratitude go to my family, especially rny late father for his de-

votion thorough his life to provide the best for his children and my rnother for her

unceasing encouragement, support and sacrifice for her children's ambition.

Last, but not least, my appreciation goes to my better-half for al1 the sharing. love

and understanding during my years in university.

Page 5: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Contents

List of Tables vii

List of Figures

1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1 Introduction

. . . . . . . . . . . 1.1.1 Overview of the OCL Project Components

. . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.2 Organization

1.2 Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2.1 Set Comprehensions

1.2.2 List Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2.3 Object Comprehensions

. . . . . . . . . . . . . . . . . . . . . . . 1.3 Overview of the Interpreter

2 OCL . . . . . . . . . . . . . . . . . . . . . . . . . 2.1 The Sample Data Mode1

. . . . . . . . . . . . . . . . . . . . . . . . 2.2 The OCL Sample Queries

. . . . . . . . . . . . . . . . . . . . . . . 2.2.1 OCL Sample Queries

3 Interpreter 18

. . . . . . . . . . . . . . . . . . . . . . . 3.1 The Phases of Interpretation 18

. . . . . . . . . . . . . . . . . . . . . . . . . 3.1.1 Lexical Analyzer 18

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.1.2 Parser 20

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.1.3 Interpreter 23

. . . . . . . . . . . . . 3.1.4 Table-Management and Error Handling 28

. . . . . . . . . . . . . . . . 3.1.5 Intermediate Values OCLVALUE 29

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.1.6 Passes 29

Page 6: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

3.2 Class Dictionary . . . . . . . . . . . - - . . . . . . . . . . . . - . . . 29

4 Conclusion 33

References 35

Appendices 37

A Header files: *.h 37

B Interpreter files: *.C 56

C Utility Code 104

D Grarnrnar 127

Page 7: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

List of Tables

1 The Scherna Defi=iit.ion . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

2 The OCL Grammar . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Page 8: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

List of Figures

1 Interpretation Process for OCL Query Language . . . . . . . . . . . . 5 . 2 University Model Diagram . . . . . . . . . . . . . . . . . . . . . . . . . I

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Qualifier Hierarchy 24

4 Example 3: The Object Model for Example 1 after Parsing . . . . . . 25

. . . . . . . . . . . . . . . . . . . . . . . 5 The Object Diagram of Expr 26

6 The Methods of Expr . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

Page 9: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Chapter 1

Background

1.1 Introduction

There are many object-oriented query languages [2, 51 that have been proposed in

recent years. Some of them are designed particularly for object-oriented databases

(OOD) and some are adapted from other areas: the relational data mode1 and its

extension [9], ob ject-oriented programming languages [5]. According to [6], al1 of

thern are inadequate in one aay or another. These inadequacies are categorised in (81

into four groups:

0 Support of object-orientation. A few 00 query languages do not capture the

class hierarchy which is defined by the ISA relationship between classes defined

in a database schema.

0 Structuring power. It refers to the ability to explore and synthesize complex

objects from the components of OOD. The creation of a new object may require

a collection of objects as a parameter. To do so a query language must provide

somet hing like nested queries and allow orthogonal composition of construct s.

Computational power. Recursion and quantification are two examples that char-

acterise the computational power of a query language. Traversal of recursive

queries as well as quantification are supported poorly. Recursive queries with

computation are supported even worse.

0 Support of collection. Usually "Set" is widely supported and its operations are

well defined. It is not the case for other collection classes. Interaction between

Page 10: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

the different collection classes is also unclear.

TO overcome the above-ment ioned inadequacieso Chandra and Trinder [4] introduces a

new query notation called Object Cornprehensions, which t akes into considerat ion the

fundamental properties of object-oriented data models and eliminates the drawbacks

above. Their Object Comprehensions Language (OCL) is clear? consise and powerful.

The extension of List Comprehensions [IO] to Object Comprehensions was done by

consolidating and improving constructs found in existing query languages.

1.1.1 Overview of the OCL Project Components

The interpreter in this report is responsible for evaluating the OCL query on a

database which resides in the memory. The database setup as well as update, and

search for the proper tuple/record is handled by the DBEntity class. DBEntity in-

teracts directly with the database and in the meantime, is the bridge between the

interpreter and the database. The Database DBEntity classes are created bu Dr.

Gregory Butler. The Database class handles the creation of the database, and the

search. It returns DBEntity objects, that are responsible for updates, and navigation.

In parallel with the interpreter presented in this paper, there are two other projects

that are involved with OCL. The first project is the creation of an Ode-based database.

which is used as a target database for the second one, the translation of the OCL

queries into the O++ query language that is used by Ode. The author of the first

project is Georges Ayoub, and of the second one is Alexander Lakher. Even though

this interpreter does not use the Ode-based database: the above three projects are

interrelated. The irnplementation of the interpreter employs the utility collection

routines created by G. Ayoub. Furthermore, the understanding of the OCL query

notation is enhanced thanks to the report of -4. Lakher.

Organizat ion

The organisation of this report is as follows. The remaining sections of this chapter

provide a background of Comprehensions and an overview of the interpreter. Chapter

2 describes the sample data model, OCL and the sample queries. Chapter 3 outlines

the implementation of the interpreter. Chapter 4 concludes. The bibliography is

followed by appendices which contain the actual code of the interpreter.

Page 11: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

1.2 Comprehensions

1.2.1 Set Comprehensions

The inspiration for comprehensions was the standard and convenient mathematical

notations for sets. For example in mathematics the set of squares of al1 the even

nurnbers in a set S would be written as:

Cornprehensions first appeared as Set Comprehensions in an early version of the

programming l angage N P L that later evolved into Kope [12] but without compre-

hensions. The- were followed by List Comprehensions [13].

1.2.2 List Comprehensions

A full description of List Comprehensions can be found in [IO]. The above mathe-

matical expression written using List Comprehensions would have a look:

where L stands for a list.

List Comprehensions have been incorporated into several functional languages, c g .

Miranda [14] and Haskell [SI. The syntax of list comprehensions is:

where E stands for an expression, Q stands for a qualifier, P stands for a pattern,

and E stands for an empty qualifier.

The result of evaluating the comprehension [E 1 Q] is a new list, computed from

one or more existing lists. The elements of the new list are determined by repeatedly

evaluating E, as controlled by the qualifier Q. A qualifier is either a filter or a gen-

erator, or a sequence of these. A filter is a boolean-valued expression, expressing a

condition that must be satisfied in order for an element to be included in the result.

Page 12: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

An example of a filter in the example above is euen(t ) . A generator of the form T +

E, where E is a list-valued expression, makes the variable T range over the elements

of the list. An example of a generator is x t L above. More generally, a generator

of the form P t E contains a pattern P that binds one or more new variables to

components of each element of the list.

1.2.3 Object Comprehensions

A generalisation of list cornprehensions is collecfion comprehensions, which provide

a uniform and extensible notation for expressing and optimizing queries over man)

collection classes including sets. lists; bags. trees and ordered sets. That is what

Chandra and Trinder [4] have called object comprehensions. The most significant

benefit is that, although each primitive operation will require a separate definition

for each collection class, only one query notation is needed for al1 these collection

classes. .A single definition is al1 that is required for high-level operations defined in

terms of collection comprehensions. It significantly reduces the syntactic cornplexit-

of the query notation:

{ x 2 [ x + C: even(x)}

where C stands for a collection, i.e. could be a bag, a set or a list. Here are some

examples of object comprehensions using the notation supgested in [dl.

Example 1. Return a set of elements of the bag B. A bag allows duplicates, however

they are to be eliminated in the resulting set.

S e t C e < - B I e l

Example 2. Return a bag of elements of the list L. Possible duplicates are preserved'

however the order of the elemenh is lost.

Example 3. Return a list of elements of the list L provided they comply with some

specific 'condition'.

L i s t [ e <- L ; c o n d i t i o d e ) 1 e 1

It is worth mentioning that comprehensions are a declarative specification of a query.

and as it is shown in [4], are a good query notation for being concise: clear, expressive

Page 13: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

and easily optimized. Kowever the optimization was out of scope of this project and

left for t.he future work.

1.3 Overview of the Interpreter

The interpreter for the Object Comprehension Query is based on a BXF (Backus

Naur Form) grammar, the OCL grammar itself is presented in Chapter 2. From

the grammar, we can automatically construct an efficient parser that determines if a

query is syntactically well formed. The interpreter is stmctured as a typical compiler.

The parser, which obtains a string of tokens from the lexical analyzer, verifies that

the string can be generated by the grammar and constructs a parse tree for query

evaluation as indicat.ed in Figure 1.

1 Symbol

lnterpreter THE INTERPRETER

Figure 1: Interpretation Process for OCL Query Language.

-

4

The parsing technique using for this interpreter is LR(1) parsing, which scans

parser BISON

i

Token

6

Get next Token

Source Language I Lexical

the input from left to right, conducts a rightmost derivation in reverse and uses one

input symbol of lookahead to make a parsing decision. BISON [Il], which is similar

Parse +

Tree OCL Query

Object Data Model Schema

to YACC, is used to create the parser. It uses the scanner generated by FLEX

[15]. BISON generates an integrated parser, a file of C program, which provides for

semantic stack manipulation and the specification of semantic routines. BISON is

used instead of YACC since it is more compatible with Cf+. The query evaluation

process is then implemented in C++.

AnaMer FLEX

- DATABASE Collections of

DBEntitys

Page 14: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Chapter 2

OCL

The sample data model is a simplified university system which records information

about students, staff members of a university, its academic departments and courses.

Figure 2 presents the data model.

2.1 The Sample Data Mode1

The class Person has two subclasses: Student and StaB Visiting Sta8 is a subclass

of Staf . Tvtor inherits from both Student and Sta8 to incorporate students doing

part-time teaching. The calculation of the salary of a tutor is different from that of

a staff member. The variation is captured by overloading SaZary method to Tutor.

Every person has an address which is an object of the class clddress. -4 student has

at least one superviser. This is modelled by the SupervisedBy method as a list of

staff members. Every and each student as well as a staff member is associated to

a department of class Department by rneans of Major and department accordingly.

Courses of class Course are mnBy a department provided there is a staff member who

teaches this particular course which enables a student to take this course via takes.

A course may have a set of prerequisites. The following table presents the scherna

definition. Using this model the next section describes OCL by presenting different

kinds of queries in OCL notation.

Page 15: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Figure 2: University Model Diagram.

Page 16: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Table 1: The Schema Definition.

C l a s s Person isa E n t i t y methods name : - - S t r i n g , address : - - Address.

C l a s s S t a f f isa Person methods department : - - Department, t eaches : - - S e t of Course, s a l a r y : - - I n t e g e r .

C l a s s Student isa Person methods major : - - Department, t akes : - - S e t of Course, supervisedBy : --> L i s t of S t a f f .

C l a s s Tutor i s a S tuden t , S ta f f methods s al a r y : - - f n t e g e r .

C l a s s Course isa E n t i t y method code : - - S t r i n g , runBy : - - S e t of Department, p r e r e q u i s i t e s : --> S e t of Course, assessments : - - Bag of In t ege r , c r e d i t s : - - I n t e g e r .

C l a s s V i s i t i ngS ta f f isa S t a f f . C las s Address isa E n t i t y methods s t r e e t : - - S t r i n g , c i t y : - S t r i n g .

Database is Persons : S e t of Person, Departments : Set of Department, Courses : S e t of Course, StaffMembers: S e t of S t a f f , Students : Set of Student , Tu to r s : S e t of Tutor .

Page 17: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

2.2 The OCL Sample Queries

Before starting the query examples we would like to elaborate on the grammar of the

object comprehensions. Table 2 presents the OCL Grammar. That would be useful

while examining the queries and aiso later when discussing the implementat ion issues

of the interpreter in Chapter 3.

Table 2: The OCL Grammar.

e x p r - l i s t expr

: := expr 1 expr , e x p r - l i s t . . .= . e x p r "union" expr 1 expr " d i f f er" expr

1 expr "and" expr 1 expr "or" expr 1 "notu expr 1 i d e n t i f i e r [ " . " expr 1 1 i d e n t i f i e r Il(" expr-list ") " 1 "s ize i l expr 1 c o n s t a n t 1 expr "hasc l a s s " expr 1 expr "hasclass" expr " w i t h " expr 1 expr "(" expr " ) " 1 expr a r i t h - o p expr 1 quant i f i e r expr op Q u a n t i f i e r expr 1 col lec t ion-k ind "{" e x p r - l i s t ")"

1 col lec t ion-k ind "{" expr " . . . " expr "3" 1 { c o l l e c t ion-kind [ I l q u a l i f iers " 1 " expr "3 "3

col lect ion-kind: := "Set" 1 I1Bag" 1 ' L i s t " q u a l i f i e r s : := q u a l i f i e r [ qua l i f iers 1 q u a l i f i e r : := [ g e n e r a t o r ] 1 [ l oca lde f 1 1 [ expr 1 generat o r : := i d e n t i f i e r V-" expr localdef : : = i d e n t i f i e r "AS" expr q u a n t i f i e r : := [ some of 1 I [ atleast expr o f 1 I [: j u s t expr of ]

I [ atmost expr o f ] 1 C every of 1 OP

..= i t > l l 1 11<11 1 11<=11 1 1 1 > = 1 1 . . 1 t l = = l l 1 I I ! = I l

a r i th -op . . .- .- t ~ * ~ ~ 1 Il/" 1 "+" I "-"

Presented in conventional BNF it still might need some explanation. The best

way is to do it by examples. The exarnple of a typical expr that can be used in a

localdef is a compound indentifier S. address . city. Another type of expr that can

be used in a query is s . addres s . city == Vienna" . A generator example: s +

Students. A localdef example: a AS S . address . street. A query then would be

expressed in the following style:

Page 18: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Set f s <- Students ; a AS s.address.city ; a == "Viema" 1 s 1

2.2.1 OCL Sample Queries

The following novel features of OCL as a query language should be noted:

a a predicate-based optimizable language providing support for the class

hierarchy;

0 numerical quantifiers for dealing with occurrences of collection elements:

a operations addressing collection elements by position and order:

0 a high-level support for interaction between different collection kinds;

0 recursive queries wit h computation.

Now we are to demonstrate object comprehensions by using queries posed against the

described university database. Queries Q1 - Q6 demonstrate the support of Object-

Orientation; Q'i and Q8 explore the result expression. QS - Q11 focus on generators.

Quantifiers are highiighted in QI3 - Q17. Support of Collection is emphasized in Q18

- Q27. The last query, 428, is to reflect the ability of Query Functions and Recursion.

Al1 queries dernonstrate the declarative nature of ob ject comprehensions as a query

notation.

Each query ~ resen ted in the following format:

1 Query #. The text of a query 1

OCL version of a query

Method Calling =d Dynarnic Binding.

Encapsulation protects attributes of an object from being accessed directly. An access

is to be made via a method. In Q1 s.salary represents the calling of method salary on

a staff member object s drawn from StafFhIembers. -4 method could be overloaded

Page 19: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

as it as the case with tutor whose salary is calculated in a different way.

1 Q1. Return staff rnembers earning more than $1000 a rnonth. 1 Set [ s <- StaffMembers; s-salary > 1000 i s 1

Cornplex Objects and Path Expressions.

Support of complex objects implies that a method call may return an object which

can, in turn, receive another method call and so on. Such a sequence of method calls

is usually referred to as a path expression.

1 Q2. Return tutors living in Glasgow. 1

Set C t <- Tutors; t.address.city = "Glasgow" 1 t 1

Object Identity.

In object-oriented data models, objects are represented by object identifiers which are

essential for ob ject sharing and representing cyclic relat ionships. Equality between

objects is defined by the equality between their object identifiers.

- - - - 1 ~ 3 . Return tutors working and studying in the sarne department. 1 - - - - -- -. .

Set [ t <- Tutors; t .department = t .major 1 t 1

CIass Hierarchy.

Stafflbfembers contains only members of the faculty. The only collection in the

database that contains al1 visiting staff members is Persons. The elements of Persons

can be of class Persons or its subclasses. In Q4 hastype returns true if person object

p is an instance of class VisitingStafl

1 ~ 4 . Return al1 visiting staff members in the university. 1 Set [ p <- Persons; p HASTYPE VisitingStaff 1 p 1

In the following query the method salary is defined for visiting staff members but not

for persons in general. The filter is applied only if the object is of specified class.

1 Q5. Return visiting staff members earning more than 1000 a month. 1 11

Page 20: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Set [ p <- Persons; p HASTYPE VisitingStaff WITH p . salary > 1000 1 p 1

Local Definitions.

Local definitions simplify queries by providing syrnbolic narnes to expressions. They

are particularly useful when a path expression is used in more than one place.

1 Q6. Return students whose major departments are in either Hill st. or U ave. 1 Set [ s <- Students ; a AS s .major . address. street; a == " H i l l s t "

OR a == "Uave" 1 s 1

The Result Expression.

Operation that create new objects should be allowed in the result expression. Method

new takes to parameters and creates a new object of class AClass for each object in

Students. In the next query the result is obtained by creating new objects using the

student objects and the sets of courses.

147. Return students and courses taken by them. 1 Set [ s <- Students 1 ACLASS.NEW(s, S. takes) 1

Nested Queries.

The result is obtained by creating new objects using the student objects and the sets

of courses. Nested queries enable richer data structures to be returned and comples

selection conditions to be expressed. An inner query above is a parameter to the

method cal1 in the result expression of the outer query.

1 QS. Return students and courses taken by them with a credit rating over one. / Set [ s <- Students 1 ACLASS .NEW(s, Set [cc-S. t a k e s ; ~ . creditsX 1 cl ) l

Mult iple Generators.

Multiple generators allow relationships that are not explicitly defined in the database

schema to be reconstructed. Two variables con range over the same set independently.

[QS. Return students studying in the same department as SteveJ. 1 Set [ x <- Students; y <- Students; x.name == "SteveJ";

x.major == y.major I y]

Page 21: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Dependent Generators.

Dependent generator is used to facilitate querying over the elements in a nested col-

lect ion.

- - - -

1 ~ 1 0 . Return courses taken by the students. 1 Set [ s <- Students; c <- s.takes 1 c ]

Literal Generators.

Collection literals can simplify queries by making them more concise and clearer.

1411. Return those courses among C1,C2,C3 which have a credit rating over one. 1 Set [ c <- Courses; x C- Set ["C1ll ,"c211, " ~ 3 ~ 1 ; c . code == x ;

c . c r e d i t s > 1 1 c 1

Existential Quantifiers.

A restricted form of existential quantification is provided by some, which can appear

on either side of an operator. In Q12, the filter succeeds if course code is one of the

mernberslisted. In Q13, t he filter returns true if there is a common element between

the two sets: i.e. an non-empty intersection.

r~1.2. Return those courses among Cl,C2,C3 which have a credit rating over one. 1 Set Courses ; c . cred i t s

SOME S e t

IQ13. Return students taking a course given by Steve Johnson.]

Set [ j <- StaffMembers; j .name = lfSteveJohnson";

s C- Students ; SOME S. takes = SOME j . teaches 1 s]

Universal Quantifiers.

In the following query the keyword EVERY is the universal quantifier. The filter

succeeds if al1 the course elements in s.takes are also in the set j.teaches; i.e. subset.

Q14. Return students taking only courses given by Steve Johnson.

13

Page 22: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Set [ j <- StaffMembers; j .name = "SteveJohnson";

s <- Students; EVERY s .talces = SOME j . teaches 1 s]

Numerical Quantif iers .

In the following queries the keywords ATL EAST, JuST and ATMOST are the nu-

merical quantifiers. Numerical quantifiers are very useful in dealing with duplicate

elements in collections and the number of elements that are common between two

collections, i.e. the size of intersection. In Q15, the filter turns true if there are two

or more elements that are common between specified sets. In Q16, the filter succeeds

if there are exactly two comrnon elements. In Q 17, the size of intersection must be

less than or equal to two.

( ~ 1 5 . Return students taking twvo or more courses given by Steve Johnson. 1 Set [ j <- S t affMembers ; j .name = "SteveJohnson" ;

s <- Students ; SOME S. takes = ATLEAST 2 j . teaches 1 SI

1 Q16. Return students taking eractly t ~ v o courses given by Steve Johnson. 1 - -

Set [ j <- StaffMembers; j .nane = "SteveJohnson";

s <- Students; SOME s.takes = JUST 2 jeteaches 1 s ]

lQ17. Return students taking no more than two courses given by Steve Johnson.

Set [ j <- StaffMembers; j .nane = "SteveJohnson";

s <- Students; SOME s .takes = ATMOST 2 j . teaches 1 s]

Aggregate Functions. The aggregate function sire returns the number of elements in a collection. It is de-

fined for al1 collection classes. For bags and lists duplicate elements are included in

the counting. Some aggregate functions are possibly defined only for certain collec-

tion classes.

1 418. Return courses with less than two assessments. 1 -- -

Set [ c <- Courses; c. assessments. size < 2 1 c 1

Page 23: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Equality.

It is quite a necessity to have an ability to compare two collections based on the

elements, occurences and their order. Thus two bags are equal if for each element

drawn frorn either collection there is equal number of occurences in both bags. For

the lists, number of occurences and the positions rnust be the same.

1 Q19. Return courses requiring no prerequisite courses. 1 S e t [ c <- Courses ; c.prerequisites == S e t [ c ]

Occurrences and Counting.

Bags and lists allow duplicates. The following two queries are to show how the oc-

curences of elements could be used.

1 Q20. Return courses with four 25% assessrnents. 1

S e t [ c <- Courses; JUST 4 c.assessments = 25 1 c 1

1 Q21. Return the number of assessments counted 25% in the course "db4". 1

Set [ i <- L i s t ( 0 . .db4. assessments . size );

JUST i db4.assessments = 25 1 il

Positioning and Ordering.

A list allows duplicates and keeps track of the order of the elements. In 422 , the first

two elements of the list are returned and used in a generator. In 423, a sublist whose

first element is Steve and whose last element is Bob is returned. It returns an empty

list if Steve does not corne before Bob in a supervisor list.

1 Q22. Return the first and the second supervisors of Steve Johnson. 1 Set [ s <- Students; s.name = "SteveJohnson";

p <- S . supervisedBy . Cl. .2] I p 1

1Q23. Return students having Steve before Bob in their supervisor lists. 1

S e t [ s c- Students; S . supervisedBy. [Steve : ~ o b ] -== List [ 1 1 s]

Page 24: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Union.

The union operator combines two collections to form a new collection of the sarne class

but having al1 the elements. The union of bags contains al1 the elements including the

duplicates. The union of a list to another one appends the latter one to the former one.

/ Q24. Return students in the CSX~ EE departments. 1 Set Cs <- Students; s.major.name = "CS" 1 s 1

UNION Set [s <- Students; s.major.name = "EE" 1 s 1

Differ.

For the ciiffer. the class of the result elements is determined in the same wax as in

union. The number of occurences for an element in the result collection is the differ-

ence of that in the operand collections. For lists, differ will remove the last match.

1 Q25. Return cities where students, but no staff, live. 1 Set [s <- Students 1 s.address.city ]

DIFFER Set [s <- Staf fMembers 1 S . address . city 1

Converting Collections.

There might be a need to convert a bag, a list or a set one to another. Bag to set

conversion would diminate duplicates while converting to a list would involve an ad-

ditional effect of assigning an arbitrary order over the result elements.

1 Q26. ~ & r n the salary of tutors and keep the possible dupl%ate values. 1 Bag [ t <- T u t o r s 1 t . salary 1

Mixing Collections. Object-oriented data mode1 supports more than one kind of collection. Hence the

corresponding query notation should support not only different collection classes but

also the mix of them in the same query. In the following query, s.supervisedBy returns

a list and is mixed with two generators drawing from sets. It should be mentioned

that swapping of generators will not be allowable if the result collection is to be a

list .

1 Q27. Return courses taught by the supervisors of Steve Johnson. (

Page 25: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Set [ s <- Students; s .name = l'SteveJohnson";

sup <- s.supervisedBy; c <- sup.teaches 1 c ]

Query Functions and Recursion.

It is natural to find the cyclic relationships in object-oriented data models. This im-

plies recursion support. The recursive queries can be expressed in object comprehen-

sions via query functions. In the folloiving query the result is generated by retrieving

elements from a collection returned by a recursive function, f(c.prerequisites). This

function takes a set of courses and returns a set of courses. For each element drawn

from the input collection, f is applied recursively on the prerequisite courses, and the

result is then used as a part of the input. The recursion terminates when f is passed

an empty set.

1 Q ~ S . Ret urn al1 direct and indirect prerequisite courses for t h e "DBI* course. 1 let f (CS : Set of Course ) be

CS UNION Set Lx <- C S ; y <- f (x.prerequisites) 1 y]

in s e t Cc <- Courses; c . code = "DB4"; p <- f (c . prerequisites) 1 p]

Page 26: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Chapter 3

Interpret er

This chapter discusses the implementation of the interpreter, the interpreter code is

provided in appendix A (3 files) and appendix B ('.C files), and the grammar is in

appendix D. The interpreter takes as input a program wri t ten in OCL, analyzes i t to

identify tokens then carries out the actual evaluation on the database.

The issues of translater, interpreter and compiler design are well addressed in [l, 31.

3.1 The Phases of Interpretation

The implementation of the interpreter is divided into phases with the output of each

phase passed as input to the next phase.

3.1.1 Lexical Analyzer

The first phase of the interpreter is scanning each statement of the source language and

recognizing the tokens specified by the regular expression. This process of specifying

token patterns is done by the lexical analyzer. FLEX is used to produce a lexical

analyrer that can be used with BISON. The FLEX library 11 will provide a driver

program named yylex(), the name required by BISON for its [exical analyrer.

Based on the grammar shown in chapter 1, a token is one of the following:

Valid operators such as , ; + * == , etc.

Valid keywords such as union, differ, atleast, etc.

Constant token consisting of digits; its value is stored in yylval.innumb.

Page 27: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

0 Identifier token consisting of strings: its value is stored in yylval-instring.

0 Literal token consisting of characters in quotes; its value is stored in yyl-

vaLinstring as well.

These specifications are stored in tokendef.1 file. FLEX then produces a stream of

tokens and passes them as input to the next phase, the syntax analyzer or parser.

The following exampie is used to elaborate the definition of different types of tokens.

Example 1

Input:

Output:

t oken

token

token

token

token

token

token

token

t oken

token

t oken

t oken

t oken

t oken

t oken

t oken

token

token

t oken

t oken

< Set > < LFSQBKTK > < identifier s >

< LIMPLTK > < identifier Students > < SEMICOLONTK > < identifier a > < ASTK > < identifier s > < DOTTK > < identifier major > < DOTTK >

< identifier address > < DOTTK > < identifier street > < SEMICOLONTK > < identifier a > < EQTK > < l i t e r a l " H i l l s t " > < SEMICOLONTK >

Page 28: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

token

token

t oken

t O ken

token

t oken

3.1.2

< identifier a > < EQTK > < l i te ra l "Uave" > C BARTK > < i d e n t i f i e r s >

< RSQBKTK >

Parser

BISON is responsible for generating the parser. The Parser takes as input the stream

of tokens produced by the Lexical analyser which is mentioned in the previous phase.

The grammar that will be processed by the parser-generator BISOiV to produce a

parser is contained in the file grammar.y. File grammar-y is shown in Appendix D

and has three main sections:

A list of tokens or terminal symbols. In the following example, IDENTIFIERTIi

and CONSTANTTK are terminal symbols. and the rest are tokens.

?Gtoken +instring+

% token +instring+

%token +instring*

%token +instring+

%token +instring+

%token +instring+

%token +innumb+

COMMATK

SEMICOLONTK

PLUSTE;

MINUSTK

DIVTK

IDENTIFIERTK

CONSTANTTK

A list of variables, subprogram headers, the name of the start symbol, and the

declaration of the precedence and associativity to resolve the ambiguity of the

grammar. A sample of this section with the list of variables and the precedence

and associativity relationship between tokens is presented below:

char

int

inst ring[64] ;

innumb;

Page 29: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

int

Prog

DListiExpr*

Expr

Qualifier

DList +Qualifier+

Generator

Localdef

Hasclassqual

Hasclasswit hqual

%nonassoc

%left

% left

%nonassoc

% left

CollectionType; * prog-ptr;

"exprlist-ptr;

*expr-p t r;

*qual,p tr;

*qua1 Jist -ptr;

'generator-pt r;

*locaIdef-ptr;

THREEDOTTK

MINUSTK PLUSTK

MULTTK DIVTK

UMINUS

DOTTK

A produ.ctions section to define the grammar. Productions are of the form

A:BI ... Bn, where A is the left hand side of the production, and BI ... B n are

zero or more terminal or non-terminal symbols. Example 2 below will illustrate

t his concept.

Example 2

exprlist :

expr

{ $$ = new DList 4 Expr +; $8 + Insert(ê1);

1 I expr COMMATK exprlist

{

Page 30: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

In the above production, expr-lisi can be parsed in two ways: it can either become

an expr or become an " ezpr COMMASI\' ezpr-list". As we can see, the left hand side

contains one non-terminal symbol expr-list; the right hand sjde contains one non-

terminal symbol expr for the first option of the production, and two non-terminal

symbols: expr and expr-list and one terminal symbol COMMATK for the second op-

tion of the production.

To generate code for each of the productions, a semantic routine, written in Cf+,

is inserted on the right hand side. These semantic routines are treated as action

symbols for BISOiV. and may access and update the semantic stacks of BISOAT. As

in Example 2 above,

$5 = new DList 4 Expr + ; $3 + Insert(â1);

are semantic routines written in C++, incorporated with BISON notation, to parse

expr-list into expr. Similarly, the semantic routines used to parse expr-list into " ezpr

COMMA TI\' expr-list" are:

As can be seen from the grarnmar in Appendix D, different types of expressions are

created on different production rules depending on the terminal symbol called op-

code which can be found on the right hand side. When a query statement is read,

the Expr-query object of type expression is created. It consists of a token SETTK,

LISTTK or BAGTK, a iist of qualifiers, a token BARTK and a return object of type

expression. As we can see, the list of qualifier is the heart of the query statement.

Please see the complete declarations of qualifiers and expressions in expr-h and qua1.h

in Appendix A for details.

Page 31: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

There are three main types of qualifier: generator, local definition, and ~ x p r ~ s s i o n .

BISON is responsible for handling the differentiation among the qualifiers and creates

them accordingly.

The output of a parser is a Parse Tree, which is a syrtactic structure that incor-

porates al1 recognized structures. The complete hierarchy of a qualifier is shown in

Figure 3. Let us continue the previous example, assuming that the stream of tokens

was fed into the parser. Thus the input is the output shown in the Example 1. Figure

4 presents the object mode1 of the query in Example 1 that the parser produces.

3.1.3 Interpreter

Once the qualifier is properly recognized, the interpretation process takes place. It

is implemented in C++ to take the full advantage of the class hierarchy and poly-

morphism characteristic of C++. The main interpretation process is handled b y the

virtual method evaluatef). An OCLVALUE class hierarchy is created to support dif-

ferent kinds of intermediate results during the evaluation process of the parse tree.

The final result of the query statement is stored in an OCLVALUE object as well.

Another important function in the interpretation process is to ensure that the left

and the right band side of the expression have the same type. This is handled by the

virtual met hod t ypecheckingg0, which is also res~onsible for storing the informat ion

read from the parser in the proper bookeeping table depending on the expression type.

Details of the two principal functions typechecking() and eualuat e () for each particular

expression type will be discussed below.

Expression

Here we discuss the expression of type Expr. Expr is a basic structure or a smallest

unit that the user can employ in a query statement to express the criteria and con-

straints to search the database. Thus, it will be discussed in more detail than any

other type. Figure 5 presents the basic components of an Expr object.

An Expr object has a pointer to Leftoperand, a pointer to Rightoperand, and an

op. Lefloperand and Rightoperand are again of type Ezpr. Any pointer can be null: as

in the case of an Unary Ezpr , in which case the pointer to Lefioperand is null. O p is a

short name for operator. It defines the relationship between the Lefioperand and the

Page 32: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Figure 3: Qualifier Hierarchy.

Page 33: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Figure 4: Example 3: The Object Mode1 for Example 1 after Parsing.

Page 34: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Figure 5: The Object Diagram of Expr

Righ toperand . It is of type Opcode which is an enumerated type. Figure 6 describes

the main methods of class Expr. The first three methods get-lefiop(): get-rightop() ,

and getop() are the basic operations to access the three components Lefioperand.

Rightoperand. and o p of a particular E x p r object. The two methods typechecking()

and evaluate() are defined virtual. They are the two most important methods that are

redefined nt any subclass of qualifier. The functionality of typechecking() is to ensure

that the type of Lef toperand matches the type of Rightoperand, and evaluate() does

nothing other than evaluating the Expr . Both typechecking0 and eaaluate() rnethods

are done in a bottom up fashion in the Expr parse tree. Each starts a t the leaf level

of the parse tree, where its left child is checked and evaluated before its right child.

Type check the expression t ypech ecking() is responsible for:

Ensuring the type of Lefloperand matches the type of Rightoperand. It also

validates that type against the types aliowed by op;

Returning the type of E z p r if the above condition is true, otherwise it returns

NUL L.

Page 35: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Expr

Expr 'get-leftopo;

Expr pet-righttopo;

Opcode getopo;

virtual char *typecheckingo;

virhral OCLValue 'evaluateo;

Figure 6: The Methods of Expr

Evaluate the expression The actual operation of the opcode is carried on at this

stage. Exp is evaluated in a bottom up fashion as mentioned above. The result

of eoaluate() is an OCLVAL UE object. The description of the OCLVALUE class is

discussed in section 3.1.5.

Generator

Genera tor is a means to introduce a new variable and its type to be used in a query

staternent.

Q p e check the generator expression Typechecking() ensures that the identifier

on the left hand side does not already exist. If it exists, typechecking() will print out

an error message and return NULL. If it does not, t y p e c h e c k i n g 0 adds a new record

in the variable bookeeping table. This record contains the variable narne, which is the

identifier itself, type of the variable, which can be found on the right hand side of

the Generator , and a pointer to the database storage which contains such objects.

TypecheckingO returns the type of the identifier read on the left hand side of the

G e n e r a t o r or NULL if it's invalid.

Evaluate the generator expression Evaluate a g e n e r a t o r will return an object

from the database. On each activation of evaluate(), an object of the proper type

Page 36: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

is fetched from the database and the pointer is updated to the next object until t he

database is exhausted.

Local Definition

Local Definition is also a means to introduce a new variable in a query statement.

The type and the value of the new variable is determined by expanding the expression

following the keyword AS.

Type check the local definition expression Typechecking() at first ensures that

the new variable introduced, the identifier preceding AS, has not been defined else-

where in the query statement. It then stores the new variable in a rnacro bookeeping

table, with the same type as the expression following AS, and a pointer to that ex-

pression as well.

Evalua te the local definition expression For the local dejînition ezpression.

evaluate() always returns an intermediate OCLBOOL with true value. The reason

for this is the expression following AS gets expanded or evaluated only when the

variable preceding AS is referred again in the query statement.

3.1.4 Table-Management and Error Handling

Al1 of the above phases of the interpreter are involved with the bookkeeping or table-

management activity to keep track of the variable names used by the query statement

and to record their type information. In this section, only the tables created at the

interpretation process will be discussed in details. Others at the lexical analyzer and

parser phases are created and handled by FLEX and BISON respectively.

The interpreter has two main tables: one to maintain the necessary information of

the variable or identifier read from the query statement, such as name, type and its

current object. The other table is to store name and the rnacro to be expanded for

the local deJnition ezpression. They are both organized into hash tables, since this is

generally the preferred and accepted method of handling symbol tables as stated in

[l] due to the efficiency reasons. An object of class hashTable handles the bookeep-

ing functionali ty for regular variables, and an ob ject of class func Table handles the

bookeeping functionality for rnacro variables. Hash coding is used to organize both

Page 37: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

tables. It uses some cornputable function of the numeric representation of the name

to determine at which point in the list the name should be entered. This is accom-

plished by the method hash of both classes hash Table and funcTable. Files tab1e.h and

table. C contain the code. Error Handling is another activity of al1 phases. The error

handler is to be invoked whenever a flaw in the source is detected. Then a warning

error message is to be issued. There is no error handler in our interpreter at this time.

Error handling is done by printing a message by the typecheck() routine that discov-

ers a flaw. Again, both table-management and error handling interact with al1 phases.

3.1-5 Intermediate Values - OCLVALUE

The OCLVALUE class is created t o handle the intermediate values as welI as the

final result of the evaluate() phase of the interpreter. It has four main subclasses:

OCLiVumber, OCLBoolean, OCLStn'ng, and OCLC'ollection. As the name suggests,

OCLNumber handles the arithmetic operations, OCLBoolean handles the logical op-

erations' OCLStnng handles the string operations, and OCLCollect ion handles the

coliection operations. Again, the result of each of t.he above operations is stored in

an object which belcngs to one of the above classes depending to the nature of the

result.

3.1-6 Passes

There are multi-pass and single-pass interpreters. A pass reads the source, which can

be the output of the previous p a s , makes the transformations specified by its phases

and writes the output to an intermediary file. This file is to be read by the next pass.

Each method: multi-pass or single-pass has its own advantages and disadvantages.

Our interpreter is a single pass interpreter.

3.2 Class Dictionary

This interpreter is implemented in C++ language. Hence Cf+ objects are used to

represent the O CL query notation. Some classes were mentioned previously while

explaining the interpretation phases. The hierarchy of nodes classes is displayed in

Page 38: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

figure 3. This section provides a brief overview of al1 created classes. In the following

dictionary. a class name is followed by the description of a class.

class Expr

Defined in expr-h file. An abstract class. Inherits from Qualifier class. Base class

for the follorving classes: Expr-string, Ezpr-num, Ezpr-subrange and Expr-rnethodcall.

class Exprmetho dcall

Defined in expr.h file. Inherits from Ezpr class. Used to represent method or

function cal1 expressions.

class Exprnum

Defined in expr.h file. Inherits from Expr class. Used to represent number

expressions.

class Expr-query

Defined in expr.h file. Inherits from Expr-subrange class. Used to represent

query expressions.

class Exprspecial

Defined in expr.h file. Used to represent "constant" collections? e g . S e t

class Exprstring

Defined in expr.h file. Inherits frcm Expr class. Used to represent string expres-

sions.

class Exprsubrange

Defined in expr-h file. Inhents from Expr class. Base class for Expr-query and

Expr-special classes. Used to represent range expressions.

class Generator

Defined in qua1.h file. Inherits from Qualifier class. Used to represent a gener-

ator expression, which is a particular form of a Qualifier.

class Hasclassqual

Defined in qua1.h file. Inherits from Qualifier class.

Page 39: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

class Hasclasswithqual

Defined in qua1.h file. Inherits from Qualifier class.

class Localdef

Defined in qua1.h file. Inherits from Qualifier class. Used to represent a localdef

expression, which is a particular form of a Qualifier.

0 class OCLBag

Defined in oc2value.h file. Inherits from OCLCollection class. Used to represent

bag7 a particular type of coilection.

class OCLBoolean Defined in oclva1ue.h file. Inherits from OCLl,'alue class. Used to represent a

boolean value, e-g. true or false.

class OCLCollection Defined in oc1value.h file. Inherits from OCL Value class. Base claçs for OCLSet.

OCLList and OCLBag classes. Used to represent collections of OCLValue ob-

jects.

class OCLList Defined in oclvalue .h file. Inherits frorn OCLColl~ction class. Used t O represent

list, a particular type of collection.

class OCLNumber

Defined in oc1value.h file. Inherits from OCLValue class. Used to represent

nurnbers.

class OCLSet

Defined in oclva1ue.h file. Inheri t s from OCLCollection class. Used to represent

set, a particular type of collection.

class OCLString

Defined in oclvalue-h file. Inherits frorn OCLValue class. Used to represent

strings.

class OCLValue

Defined in oc2value.h file. An abstract class. Base class for OCLXumber,

OCLBoolean, OCLStnng and OCLCollection classes.

Page 40: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

class Qualifier

Defined in qual-h file. A n abstract class. Base class for Expr, Cenerator? LocaldcJ

and Hasclassqual classes.

Page 41: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Chapter 4

Conclusion

The motivation behind this project is t o studÿ and irnplement OCL, Object Compre-

hension Language, the new powerful query notation.

The project focusses on the implementation of the interpreter of the OCL query lan-

guage. The database used here is the in-memory database. The interpreter of the

OCL query language is implemented in Cf+. It takes the advantage of the object-

oriented characteristics of C++ to ease the creation of the objects and the use of

t heir methods.

The in-memory database used for the interpreter reflects a Universit.y model. a schema

of interrelated objects of classes such as Department, Staff, Student, Course, etc. The

issues of error handling, user interface, and query optimization are outside the scope

of this project.

Out of 28 originally suggested OCL queries, the interpreter can evaluate al1 but the

following ones:

0 Queries that require the creation of the new objects specified in a result expres-

sion (47).

Nested queries (Q8).

0 Queries with list elements positioning (422).

Recursive queries (Q3S).

These queries are left for future work. They require either recursion, and or the

creation of "user-defined functions" that would also have to be interpreted.

Page 42: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Through the process of understanding the OCL query notation and implementing

of the interpreter, valuable experience has been gained. Besides get ting acquaint ed

to the parser and scanner tools BISON and FLEX, I have to learn how to reflect

properly the various types oiexpressions of the OCL in C++. Keeping the interpreter

implementation complete, compact but flexible for any future modification as the

OCL query notation evolves is also a very important principle that 1 have in rnind. I realize that the implementation presented in this paper is not the perfect one. The

C++ classes and objects have been organized into different categories according to

the information they represent:

Parse category reflects the expressions, queries and other information that are

collected in the parsing process;

Value category reflects the results of evaluating the queries and expressions and

Database category reflects the database.

The Parse category could be done better with one class for each terminal and non-

terminal in the abstract gramrnar.

It would also be desirable to have the OCL queries evaluated on an Ode-based

database, and to have a GUI interface to allow the user to enter more than one

OCL query staternent at a time.

Page 43: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Bibliography

Ravi Sethi -4lfred V. Aho and JefFrey D. Ullman. Compilers, principles, tech-

niques, and tools. Addison- Wesley, 1988.

F. Bancilhon. Query languages for ob ject -0riented dat abase systems: Analysis

and proposal. In Proceedings of the GI Conference on Database Systema for

Ofice. Engineering. and Scient ific Applications. pages 1-1 S . Springler-L7erlag.

1989.

Lynn Robert Carter and William M. Waite. .4n introduction to compiler con-

struction. Harper-Collins, 1993.

Daniel K. C. Chan and Philip W. Trinder. Object comprehensions: X query no-

tation for ob ject-oriented databases. In Proceedings of the 1 ,"th British ?Va tionaï

Conference on Databases, Guildford, Springler-Verlag, July 1991.

Servio Logic Developrnent Corporation. Programming in opal, version 1.3. 1987.

D. J. Harper, D. K. C. Chan, and P. W. Trinder. A case study of object-

oriented query languages. In Proceedings of the International Co nference on

Information Systerns and Management of Data, pages 63-86, Indian National

Scientific Documentation Centre (INSD OC), 1993.

G. Pelagatti, E. Bertino, M. Nagri, and L. Sanella. Object-oriented que- lan-

pages: The notion and the issues. In IEEE Transactions on Knowledge and

Data Engineering, pages 223-237, June 1992.

P. Hudak and P. Walder. Report on the functional programming laquage

Haskell. In Technical Report 89/R5, University of Glasgow, U. K., 1990.

Ontologie Inc. Ontos sql guide. USA, 1991.

Page 44: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

[l O] S. Peyton- Jones. The implementation of functional programming languages.

Prentice-Hall. 1987.

[Il] R. Corbett, R. Stallman, and W. Hansen. The Bison reference manual version

1-23. GKU SoftkVare, 1997.

[12] R.M. Burstall, D.B. MacQueen, and D.T. Sanella. Hope: an experimental ap-

plicative language. In In Proceedings of the 1st A C M Lisp Conference, pages

136-143, X C M Press, 1980.

[13] D. A. Turner. Recursion equation as a programming language. In Functional

Programrning and its Application, Cambridge University Press, l9Sl.

[14] D. A. Turner. Miranda: a non-strict functional language with polymorphic types.

In Proceedings of the 2nd Conference on Functional Programming Languages and

Comput er Architectures, pages 1-16, Springer-Verlag, 1983.

[1 51 V. Paxson. The Flex reference manual version 2.5. GNU Soft Ware, 1995.

Page 45: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Appendix A

Header files: *.h

/ /expr . h

#ifndef EXPR-H #def i n e EXPR-H

#include < s t d i o . h > # i n d u d e "ent i t y . h" #include "DList . h" # i n d u d e "oclva1ue.h"

enum Opcode { Noopcode, PlusOpcode, MinusOpcode, MultOpcode, DivOpcode, Andopcode, Orûpcode, DifferOpcode, Unionopcode, SizeOpcode, SomeOpcode, EveryOpcode, NotOpcode, A t l eas t Opcode, J u s t Opcode, AtmostOpcode, EqOpcode, NotEqOpcode, LtOpcode, LtEqOpcode, GtOpcode, GtEqOpcode, Dotopcode, DotSBKOpcode, ThreedotOpcode, MethodcallOpcode, QueryOpcode, SpecialOpcode,

>;

enum CollectionType C NoColType, SetType, ListType,

BagTy pe

Page 46: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient
Page 47: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

v i r t u a l v i r t u a l

v o i d void

p r i n t -item() () P r i n t S t ruc t ( i n t l e v e l = 0) ;

c lass Expr,string:public Expr ( protected :

char *string,expr; public :

Expr,string(char *c) ; OCLValue *evaluate () {return neu OCLString (string-expr) ; ) char *GetTypeO <

char *c = new ch arc^^^]; s t rcpy(c , "Str ing") ; r e t u rn c ;

3 char *typechecking() ( re turn GetType () ;)

c l a s s Expr-num :pub l ic Expr ( protected:

long num; public :

Expr-num(1ong i) < n u m = i;

1 OCLValue *evaluate 0 Creturn neu 0cLNumber (num) ; ) char * ~ e t T y p e ( ) (

char *c = new char[MAX]; s t r cpy(c , " In teger" ) ; r e t u rn c ;

1 char *typechecking() {return GetType() ;)

c l a s s Expr,subrange:public Expr( //format: col lec t ion-kind LCBKTK expr iHREEDOTTK expr RCBKTK protec t ed:

i n t co l l ec t - type ; public :

Expr-subrange(int in=NoColType,Expr *l=NULL,Expr *r=NULL,

Page 48: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient
Page 49: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

p r i v a t e : D L i s t <Expr> *expr , l i s t ; char * i d e n t i f i e r ;

public : Expr-rnethodcall (DList<Expr> t e , char *in, Opcode opl=NoOpcode,

Expr *l=NULL , Expr *r=NULL) ; OCLValue *evaluat e C) ()

1;

#if ndef OCLVALUE-H #def i n e OCLVALUE-H

# i n d u d e <stdio.h> ginclude " e n t i t y - h " # i n d u d e "DList .h"

enum CompType ( Noreltype, Equaltype , NotEqualtype, LessThantype, LessThanEqtype , Great'ïhantype, GreatThanEqtype

3;

enum puant i f ierType C NoQuanType, SomeType , A t leastType , AtmostType, EveryType, JustType

Page 50: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

c l a s s OCLNumber ; c l a s s OCL-Boolean; c l a s s OCLString; c l a s s OCLCollect ion;

c l a s s OCLSet Quant ; / / c l a s s OCLValue;

c l a s s OCLValue( / /publ ic Expr { p r o t e c t e d :

cha r *va r id ; pub l i c :

OCLValue (char *c=NULL) ; cha r *Ge tva r id ( ) ; void put ,var id(char *c) ; v i r t u a l c h a r *GetType () ; v i r t u a l OCLValue *eva lua t e (1 ; v i r t u a l OCLValue *plus ( ~ ~ L V a l u e * ) ;

v i r t u a l OCLValue *minus (~CLValue*) ; v i r t u a l OCLValue *mult iply (OCLValue*) ; v i r t u a l OCLValue *divide(OCLValue*); v i r t u a l i n t Getquant () ; v i r t u a l i n t GetSetnum() ; v i r t u a l long Getnumb () ; v i r t u a l bool Getbool() ;

v i r t u a l char* G e t s t r ( ) ; v i r t u a l char* Get i d e n t () ; c o l l e c t ion<OCLValue> *ge t -co l ( ) <)

v i r t u a l i n t Size() ; v i r t u a l OCL-Boolean *not () ; v i r t u a l OCLValue *compare (OCLValue* , CompType) ; v i r t u a l OCLValue *~omparenum(OCLNumber*,~ornpType); v i r t u a l OCLValue *~om~arebool(OCL~Boolean*,~om~Type); v i r t u a l OCLValue *Compareset (OCLCollect ion*, ~ompType) ; v i r t u a l OCLValue *comparequantset ( O C L ~ e t ~ u a n t * ,CompType) ; v i r t u a l OCLValue * ~ o m ~ a r e ~ t r i n g ( O ~ ~ ~ t r i n ~ * , ~ o m ~ ~ y p e ) ; v i r t u a l c o l l e c t i o n < a n e n t i t y > *Ce t se t co l ( ) ;

v i r t u a l a n e n t i t y *ge t -ob jec t () ; v i r t u a l OCLValue *dot (OCLValue*) ; v i r t u a l vo id pr in t - i t em() ;

Page 51: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

class 0CLNumber:public OCLValue{ pr ivat e :

long numb-val ; public :

OCLNumber(1ong n=O,char *c=NULL); char *GetType() (

char *c = new char[^^^] ; strcpy(c,"OCLOCLNumber"); return c;

> long Getnumb () (return this->numb,val; OCLValue *evaluat e () ; OCLValue *Compare ( ~ ~ ~ ~ a l u e * , ~ompType) ; OCLValue *~ornparenum(~~~Number*,CompType); OCLValue *plus(~~~~alue*); /* plus ==> ADDITION*/ OCLValue *minus(~~~~alue*); /* minus ==> SUBSTRACT*/ OCLValue *multiply(OCLValue*); /* multiply ==> MULTIPLICATION*/ OCLValue *divide(OCLValue*); void print-it em () ; void PrintStruct(int level=O);

3;

class OCL,Boolean:public OCLValue( private :

bool bool-val ; public:

OCL,Boolean(bool b=false,char *c=NULL); OCLValue *evaluat e () ; char *GetType() <

char *c = new char [MAX] ; strcpy(c, "0~LBool") ; return c;

> bool ~etbool() (return bool-val;) OCL-Boolean *not () ; OCLValue *~ompare(~CLValue*,~ornpType); OCLValue *~omparebool(~CL~Boolean*,CompType); OCLValue *plus(OCLValue*); /* plus ==> OR */ OCLValue *multiply(OCLValue*); /* multiply ==> AND */ void print-item() ;

3;

Page 52: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

class 0CLString:public value( private :

int len; char *str ;

public : OCLString() ;

OCLString(char* , char *c=NULL) ; char* Getstro (return str;) char *GetType() (

char *c = new char[MAX] ;

strcpy(c, "OCLString") ; return c;

> OCLValue *evaluate () ; OCLValue *dot (OCLValue *e= NULL) ; OCLValue *~ompare(~~~~alue*,CompType); OCLValue *~ompare~tring(OCLString*, CompType) ; void print-item(); void PrintStruct(int level = 0);

class 0CLCollection:public OCLValue( protected :

collection<anentity> *OCLSet,val; iter-list<anentity> *set,iter ;

public : OCL~ollection(collect iori<anentity> *C=NULL , char *c=NULL) ; collection<anentity> *GetSetCol() (return this->O~LSet,val;) virtual char *GetType() {

char *c = new char [MAX] ; strcpy(c,"OCLSet"); return c;

char e et settype () {return set-it er->curent () - > ~ e t T y p e ( ) ; ) virtual int Size () (return (this->OCLSet-val) ->size () ; )

//cal1 sizeo function of George OCLValue *evaluat e () ; virtual OCLValue *Compare (OCLValue* , CompType) ; OCLValue *Compareset (OCLSet* , CompType) ; //OCLValue *callmethod(char* c); OCLValue *dot (OCLValue*) ; //verif y if st il1 need this f unct ion

Page 53: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

OCLValue *plus (~c~~hlue*) ; /* plus ==> UNION */ OCLValue *minus value*) ; /* minus ==> DIFFER */ bool equal (OCLSet*) ; bool lessthan(OCL~et*); void print-item() ;

class OCLSet :public OCLCollect ion( privat e :

set<OCLValue> *setval ; public:

OCLSet(set<~~LValue> *s = NULL) (setval = s;) set<OCLValue> *get-setval() (return setval ;) collection<OCLValue> *get-col() (this->get-setval();)

class OCLList :public OCLCollect ion{ privat e :

list<OCLValue> *listval; public :

OCLList(listcOCLValue> *1 = NULL) (listval = 1;) list<OCLValue> *get,listval() {return listval; 3 collect ion<OCLValue> *get -col () (this->get-listval() ; )

class OCLBag :public OCLCollect ion( private :

bag<OCLValue> *bagval ; public :

OCLBag(bag<OCLValue> *b = NULL) (bagval = b; 3 bag<OCLValue> *get-bagval() {return bagval;) collection<OCLValue> *get-col() (this->get-bagvalo ; )

class 0CLSetQuant:public OCLCollection( privat e :

Quantif ierType Qt ; int n u ;

public : OCLSetQuant(QuantifierType Q=NoQuanType,int n=O,

Page 54: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

co l lec t ion<anen t i ty> *C=NULL,char *c=NULL); OCLValue *evaluat e () ; char *GetType() (

char *c = new char[M~X] ; s t rcpy(c , "OCLSetQuant") ; r e t u r n c;

3 in t Getquant () ( re turn Qt ;) i n t GetSetnum() ( re turn a m ; ) OCLValue *Compare (Onvalue*, CompType) ; OCLValue *Comparequant s e t (OCLSet Quant * , CompType) ; void print,item()()

c l a s s 0CLEntity:public OCL~alue( p r i v a t e :

anen t i t y *objinstance; pub l i c :

OCLEntity(anentity *i = NULL,char *c = NULL); -0CLEnt i t y () {) char *GetType() {

char *c = new char[MAX] ; s t r cpy (c , "OCLEntType") ; r e t u r n c ;

3 OCLValue *evaluat e () ;

m e n t i t y *get-ob j ac t () ( re tu rn ob j ins tance; ) OCLValue *dot (OCLValue*) ;

Page 55: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

. . A O

II

rl al 3 al rl

+' d

s r 4

w 4J

I k Ci tn C, d

.ri k CL

'id ~ r l

;

. .) n u a, C, td =r rl id 3 a * 'id rl

1

w al 'id ri id

* * U U O

rn .d rn r( cd P rl 9 0 Pc

+' O

.rl 9.4 .rt d

5 u U

.rt r-l

-s O( . . . ..) 4 nI x 5 al rn Ci

Z W al ri rl U * * * rn 'id cd Lt x s a

o r 3 0 r l k O Pc

Page 56: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

public : Hasclassqual(Ekpr *l,Expr *r=NULL,char *id=NULL,char *typ="Hasclass"); -Hasclassqual () {) Expr *get Jexpr () {return lef t expr ; ) void put-lexpr(Expr * e ) {leftexpr = e; 3 OCLValue *evaluat e () ; char *typecheckingo; void Hasclassqual: : calculate(collection<anentity>*

iter-list~anentity>*,char*);

class Hasclasswithqual:public Hasclassqual{ privat e :

Expr *thirdexpr ; public :

~asclasswithqual(Expr *e,Expr *l,Expr *r=NULL,char *~~=NuLL); 'Hasclasswithqual() ()

OCLValue *evaluat e () (3 char *typecheckingo;

3;

#ifndef STRING-E #def ine STRING-H // string.h : strings of characters // essentially C++ book p248 et seq

class string { struct srep C

char* s; // pointer to data int lth; // length of string int rcnt; // reference count

Page 57: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

s r e p *p;

p u b l i c : s t r i n g ( const cha r * ) ; / / s t r i n g x = "abc"

s t r i n g ( ) ; // s t r i n g x; s t r i n g ( const s t r i n g & ) ; / / s t r i n g x = s t r i n g . . . char* ge t - s 0 Creturn p->s ; > s t r i n g & operator=( cons t char * ) ;

s t r i n g & operator=( cons t s t r i n g & ) ;

- s t r i n g ( ) ;

char& operator[] ( i n t i ) ; cons t c h a r t operator[] ( i n t i ) c o n s t ;

f r i e n d ostream& opera tor<< ( ostreamk, const s t r i n g & ) ; f r i e n d istream& opera tor>> ( istreamâ, s t r i n g & ) ;

f r i e n d i n t operator==( c o n s t s t r i n g Px, const cha r *s ) { r e t u r n strcmp( x.p->s, s ) == 0; )

f r i e n d i n t operator==( c o n s t s t r i n g &x, const s t r i n g &y ) { r e t u r n (x .p->l th == y.p->l th) && (strcmp( x .p->s , y .p->s ) == 0) ; 1

f r i e n d i n t opera tor !=( c o n s t s t r i n g &x, const cha r *s ) ( r e t u r n strcmp( x.p->s, s ) != 0; 3

f r i e n d i n t ope ra to r != ( c o n s t s t r i n g &x, const s t r i n g &y ) { r e t u r n (x .p ->l th ! = y . p - H t h ) 1 1 (strcmp( x . p ->s , y.p->s ) ! = 0) ; )

f r i e n d s t r i n g concat ( c o n s t s t r i n g & , const s t r i n g & ) ; f r i e n d i n t hash( cons t s t r i n g & , i n t s i z e ) ;

//hash a s t r i n g rnodulo s i z e

// tab1e.h: declaration of v a r i o u s types of table // t a b l e : conta ins schema of the d a t a b a s e // hashTable : conta ins v a r i a b l e s / i d s r ead f rom query

Page 58: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

// f uncTable : contains func t iondmacros read f rom query // dbtable: contains r e a l database obj ec t s

#if ndef TABLE-H #def i ne TABLE-H

# i n c h d e <iostream.h> t inc lude <s t r i ng . h> # i n c h d e c s t d l i b . h> # i n c h d e "en t i ty . htl # i n c h d e "s t r ing.hN # i n c h d e "dbase-h"

enum id-type <

TYPE, CLASS , METHOD , DATABASE

3 ;

enum collection-type

SET, BAG , LIST,

c l a s s Expr; c l a s s namenode ;

c l a s s name ( f r i end c lass table; friend c lass namenode;

publ ic : name ( const s t r ing& p, name* nxt ) ;

-name () ;

void se t s t r i ng ( const string& s ) < str = s ; > void setIdType( const id-type& s ) ( id-kind = s; )

Page 59: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

void setCollectionType( const collect ion-type& s ) C coin = s; 3 void setBaseT-ype( name* s ) { type-kind = s; 3 void addsuper( name* n ) ;

s t r i n g g e t - s t r ( ) (return str;) id-type ge t ,idkind() ( re tu rn id-kind ; 3 col lec t ion- type get,coln() ( r e tu rn co ln ; ) name* get- typekindo {return type-kind; 3 namenode* get-super() {re turn super ; ) name* ge t -next () (return next ; )

void p r i n t ( ostream& os ) ;

p r i v a t e : s t r i n g str; / / textual repn of i d e n t i f i e r id-type id-kind; //grammar kind of ident i f i e r

// type information about i d e n t i f i e r col lec t ion- type coln; // kind of c o l l e c t i o n type, i f any name* type-kind; // poin te r t o e n t r y f o r base type namenode* super; // poin te r t o e n t r y f o r super c l a s s

name* next ; / /pointer t o next e n t r y i n bucket

c l a s s namenode ( pub l i c :

namenode( name* n , n -namenode() ( de le te

amenode* nx t ) ( i n fo = n; next = n x t ; ) next ; )

name* get - info() {return i n fo ; ) namenode* get-next 0 Creturn next ; 3

void p r i n t ( ostream& os ) ;

p r i v a t e : name* in fo ; namenode* next ;

c l a s s t a b l e ( name** t b l ; i n t s i z e ;

Page 60: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

p u b l i c : t a b l e ( i n t sz = 15 ) ;

' table () ;

name* look( cons t s t r i n g & p );

name* i n s e r t ( cons t s t r i n g & s ) ;

void p r i n t ( ostreamâ os ) ;

/ / ex te rn t a b l e symt able ;

class record {//IDENTIFIER ( v a r read from inpu t ) s t r u c t u r e char* name; char* type ; / / i t e r - l i s t t a n e n t i t y > * o b j i t e r ; iteratorCOCLValue*> it 1 ;

i terator<DBEntity*> i t 2 ; bool i ter-over-db; / / i f i ter-over-db i s t r u e t h e n f i e l d i t 3 i s v a l i d

p u b l i c : record( ) : name(0) , t y p e (0) , it 1 (O) , i t 2 (0) , i ter-over-db (f alse) {) record (char *n, cha r *t , iterator<OCLValue*> v a l i t e r = 0,

i terator<DBEnti ty*> d b i t e r = O , bool i t e r d b = true):name(n), t y p e ( t ) , itl ( v a l i t e r ) , i t 2 ( d b i t e r ) , i ter-over-db(i terdb)()

- record() () void putName(char *n) {name = n;) void putNameType(char *n) (type = n;) void init,ocl,iterator(iterator<OCLValue*> v a l i t e r ) (

itl = v a l i t e r ; i ter-over-db = f a l s e ;

> void i n i t - d b i t e r a t o r ( i t e ra to r~DBEnt i ty*> d b i t e r ) i

1 t 2 = d b i t e r ; i ter-over-db = true;

3 char* getName () {return name ; > char* getNameType 0 i r e t u r n type; ) OCLValue* get-cur0CL () Creturn *it 1 ;

/ / r e t u r n c u r . ob j , p t r t o OCLValue

Page 61: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Whatclass??? get-curobj () { / / kna t i s t h e re turned class ?

i f (it er-over-db) r e t u r n g e t -curDB (1 ; e l s e r e t u r n get-curOCL () ;

I void i te r -next -obj () (

i f ( i ter-over-db) i t 2 + + ; //Is it c o r r e c t vhat I'm doing here : move / / i t e r a t o r t o t h e next o b j e c t i n t h e l i s t ?

i terator<Whatclass???> g e t - i t e r a t o r o C//what c l a s s shou ld 1 use here?

if ( i ter-over-db) r e t u r n i t 2 ; e l s e r e t u r n i t l ;

1 i t e r - l i s t C a n e n t i t y > *get-obj i t e r o Creturn obj i t e r ; ) void i t e r - n e x t o b j () {obj i t e r ->nex t () ; 3 //move i t e r a t o r t o next objec t void r e s e t - i t e r ( ) {obj i ter->f irst () ;3 m e n t i t y* get-curob j () {re turn ob j i t e r - > c u r r e n t () ; 3

3;

s t r u c t s torageTable ( record* e n t r y ; storageTable* next ;

>;

c l a s s hashTable (

i n t s i z e ;

publ ic : h a s h ~ a b l e o ;

-hashTable () ; i n t hash(char*) ; char* look(char*) ; / / r e t u r n t y p e i t e r - l i s t < a n e n t itp* get-obj i t e r ( c h a r * ) ; / / r e tu rn i t e r a t o r void put-obj i t e r ( c h a r *str, i t e r - l i s t < a n e n t i t y > *ent) ; void i n s e r t (record*) ; / / i n s e r t nev record i n hash tab le

void i t e r -nex tob j (char*) ; //move i t e r a t o r of v a r t o next ob j ect void r e se t , i t e r (cha r* ) ; //reset i t e r a t o r of va r m e n t i t y * get-curob j (char *) ; / / r e t u r n cu r ren t ob j e c t of v a r void p r i n t () ; // p r i n t name and t y p e of v a r i a b l e

1;

Page 62: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

class funct-record {//f unct i o n s t r u c t u r e , used when read localdef ; / /expression; when read ing "a AS s .major. address . s t r e e t " , funct-record / / v i l 1 have name ' a ' , t y p e i s basetype of 'street ' method c a l l , and / /expr- t ree w i l l po in t t o s .major. address . s t r e e t .

char* name; char* type ; Expr *expr- tree ;

p u b l i c : funct-record() :name (O) , type(0) , expr- tree (O) {3 funct-record(char *n ,char *t,Expr * e = ~ ~ ~ ~ ) : n a m e ( n ) ,

void putlame (char *n) {name = n;)

void putNameType(char *n) {type = n ; ) void putexpr(Expr *e) {expr-tree = e ; ) char* getlame () { r e t u r n name ; ) char* getNameType() { re tu rn type ; ) Expr * g e t - e x p r t r e e o Cre turn expr- tree; )

s t r u c t functstorageC funct-record* e n t r y ; f unct s t orage* next ;

class functTable ( / / t a b l e store funct ion r e c o r d s func t s to rage **table ; i n t size;

p u b l i c : f unctTable () ; 'f unctTable () ; i n t hash(cDar*) ; char* look (char*) ; / / r e t u r n type Expr* ge t -expr t ree (char*) ; / / r e tu rn express ion t r e e void put-expr(char *str, Expr *ent ) ; void inser t ( funct , record*) ; / / i n s e r t new f u n c t i o n r e c in funct ion t a b l e void p r i n t () ; // p r i n t name and type of v a r i a b l e

Page 63: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

c l a s s dbtable- rec ( pr iva t e :

char *tblname; / / c l a s s name e . g, Course ,Department, Student ,Person. c o l l e c t ion<anent i ty> *tblobj ; // p o i n t e r t o l i s t of obj ect dbtable-rec *next ;

public : d b t a b l e - r e c o (tblname = NULL; t b l o b j = NULL;next = NULL;) dbtable-rec(char *c ,col lec t ion<anent i ty> *a = NULL,

dbtable-rec *n=NULL) ( tblname = c ; t b l o b j = a ; next = n;

1 char *get-tblname() ( re turn tblname ; ) co l l ec t ion<anen t i ty> *get-set () { r e t u r n t b l o b j ;) dbtable-rec *ge t -nex to {return n e x t ; ) void put,tblname(char *c) (tblname = c;) void add-obj (anenti ty* O) ( tb lobj ->add(o) ; ) void put,next(dbtable-rec * r ) (next = r;)

);

c l a s s dbtable( // c l a s s p r iva te :

dbtable-rec *head; // head p o i n t e r t o l i s t of t a b l e s public :

dbtable (dbtable-rec *t l=NULL) (head = t 1 ; ) *dbt ab le () () dbt able-rec *look(char*) ; void add-obj(anentity*, char*); void add-tbl (dbtable-rec*) ; dbtable-rec *get-head () ( re turn head; 3 c o l l e c t ion<anent i t y > *get-set (char*) ;

1 ;

Page 64: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Appendix B

Interpreter files:

/ /expr . C # i n d u d e <s td io .h> # inc lude < s t r i n g . h > #include < a s s e r t . h >

# inc lude "expr . h" # i n d u d e "oclva1ue.h" # i n d u d e " t a b l e . h W

ex te rn hashTable v a r t a b l e ; / / con ta ins v a r i a b l e read from i n p u t //along with i t s type

ex t e r n t a b l e symt a b l e ; / / con ta ins dat abase schema : class names , / /methods,etc .

Q u a l i f i e r : : Q u a l i f i e r (char *typ , cha r * id , Expr *rexpr) : anent i t y ()

< qual - t ype=new char Cl51 ;

ident=new char [ s t r l e n ( i d ) +1] ; s t r c p y ( ident , i d ) ;

3 e l s e

i d e n t = NULL; r ightexpr= rexpr;

Page 65: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

char *Qualifier::get-qualtype() r

char * Q u a l i f i e r : : get - ident ()

{ r e t u r n iden t ;

3

Expr * Q u a l i f i e r : : get-rexpr ()

{ r e t u r n r i g h t expr ;

void Qua1ifier::put-rexpr(Expr * e )

{ r igh texpr = e;

>

OCLValue * Q u a l i f i e r : : eva lua te ( )

0

OCLValue *Quaiif i e r : : reevaïuat e ()

0

char *Qualifier::typechecking() 0

void Q u a l i f i e r : : P r i n t S t n i c t ( i n t l eve l ) { p r i n t f ( ' l ~ u a l i f ie r Type:%s, I d e n t i f i e r : %s\nW ,quai-type, ident) ; p r i n t f ("Expression: "1 ; r ightexpr->print- i tem() ; p r i n t f ;

>

~ x p r : : Expr(Expr *1, Expr *r , Opcode o p l ) : ~ u a l i f i e r ("Expr")

<

Page 66: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

bool Expr::Isidentical(const Expr *e) // identical when both expr // have same addresses

€ if (this == e)

return tme; else return false;

1

void Expr : : PrintStruct (int level)

< if ( ! IsEmpty() )

< for(int i=O;i<level;i++)

printf ("\t ") ; printf("0pcode:%d\nW,op);

for (int i=0 ; i<level; i++) printf ("\t ") ;

printf ("Left Expression : \nu) ; Lef toperand->PrintStruct (level+i) ;

if (RightOperand)€ // unary expr does not have rightop for(int i=O;i<level;i++)

printf ("\tll) ; printf ( " ~ i g h t Expression : \nt') ; Right Operand->PrintStruct (level+l) ;

1 >

char *Expr : : typecheckingo <//Recursice typecheckingtill the leaf level of the Expr tree, and //ensure that type of leftop is the same as type of rightop

Expr *left , *right ;

char *t = new char [MAx+I] ;

char *tr = new char CMAX+I] ;

char *typ = new char[~~~+i] ;

Page 67: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

i f (Lef t Operand) l e f t = LeftOperand;

if (RightOperand) r i g h t = Right Operand;

switch(op) { case NoOpcode : r e t u r n GetType () ; case Plusopcode: c a s e Minusopcode: case MultOpcode: case DivOpcode: case EqOpcode: c a s e NotEqOpcode: case LtOpcode: case LtEqOpcode: c a s e GtOpcode: case GtEqOpcode :

s t rcpy ( t , lef t ->typechecking() ) ; s t r c p y ( t r , right->typechecking() ) ; i f ( ! strcmp(t , t r ) 1 1

( ! strcmp(t , " s t r i n g w ) && ( ! s t rcmp( t r , "OCLStringl'))) 1 1 ( ! s t rcmp( t r ,"Str ing") && ( ! strcmp ( t , "OCLString1') ) ) I I ( ! strcmp (t , "Integerl1) && ( ! strcmp ( t r , "OCLNumberW) ) ) I I ( ! s t rcmp( t r , "Integer") && ( ! s t rcmp( t , "OCLNumberl'))))

r e t u r n t r ; break;

/ / l e f t should be a v a l i d i d i n v a r t a b l e , r i g h t should be a v a l i d //method of l e f t . Type returned i s t h e base type o f t h e method a t

/ / r igh t i f l e f t i s type S t r ing then it should e x i s t i n v a r t a b l e , / / r e tu rn t y p e recorded i n va r t ab le . If l e f t i s any base type / / ( r e s u l t e d from a recurs ive dot express ion) , then v e r i f y if r i g h t //is a v a l i d method of type o f l e f t . / / ~ r o b l e m : f o r expr such as: s . a d d r e s s . c i t y , s -address r e t u r n s type / / ~ d d r e s s , t h u s c i t y is a va l id method. of Address, it r e t u r n s type / /S t r ing . For ex.: expr such a s : c .assessment . s ize , c-assessment / / r e tu rns t y p e I n t e g e r , and s i z e is n o t a v a l i d method of I n t e g e r , //it thus r e t u r n s NULL, when i n f a c t s i z e is a method a p p l i e s on BAG

//of INTEGER n o t on INTEGER i t s e l f . case Dotopcode:

t = right->typechecking(); i f ( ! strcmp(t ,"OCLStringW) 1 1 ! s t rcmp(t , "String1')){

/ / r i g h t should always be a s t r i n g t = lef t ->typechecking() ; if ( ! strcmp (t , "OCLStringH) 1 1 ! s t rcmp(t ,"Str ingn)) {

t y p = v a r t a b l e . look(1eft-)evaluate()->Getstr()) ;

Page 68: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

t y p = t ; i f ( typ) ( //NON NULL t y p e

s t r i n g s = string(right->evaluate() ->Getstr ()) ; name *valid,method = symtable . look(s) ; if ((valid-rnethod) && (valid-method->get-idkind()==METH~~))(

namenode *method-class = valid-method->get-super(); v h i l e (method-class) (

i f ( ! st rcmp(typ ,methoci-class->get-inf O ()

- > g e t - s t d ) .pe t - s O 1) / / r e t u r n base t y p e r e t u r n valid-method->get-typekindo

- > g e t - s t r 0 .get-s() ; e l s e method-class = method-class->get-next () ;

3

3 break;

c a s e AtleastOpcode: ca se AtmostOpcode: case JustOpcode: // l e f t e x p r should be number, r e t u r n type of r i g h t e x p r t = lef t ->typechecking() ; i f ( ! s t r cmp( t ,"~~LNumber") 1 1 ! s t r cmp( t , " In teger" ) )

r e t u r n r igh t -> typecheck ingo ; break;

c a s e EveryOpcode: case SomeOpcode: c a s e SizeOpcode: //unary express ion , r e t u r n t y p e of l e f t e x p r r e t u r n l e f t - > t y p e c h e c k i n g o ;

c a s e NotOpcode: / / f o r Bo01 t y p e only - unary expres s ion t = lef t ->typechecking() ; if ( ! s t rcmp( t ,"0CLBool"))

r e t u r n t ; break;

3 //end swi t ch op

p r i n t f ( "\nINVALID EXPRESSIONS\nI1) ; r e t u r n NULL;

Page 69: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

< int t,tS,typ; OCL-Boolean *b; OCLNumber *n ; OCLValue *vl = ~ e f t operand->evaluat e () ; OCLValue *vr = ~i~hto~erand->evaluateo; OCLValue *tempval;

switch(op) { case NoOpcode : return NULL ; case Plusopcode: // plus, union, or operations

return (vl->plus (vr) ) ; case Minusopcode: // minus, differ operations

return (vl->minus(vr)); case MultOpcode: // multiply, and operations

return (vl->multiply(vr)); case DivOpcode :

return (vl->divide (vr) ) ; case EqOpcode :

tempval = vl->Compare (vr ,Equaltype) ; return tempval;

case NotEqOpcode : return (vl->~ompare(vr,NotEqualtype));

case Lt Opcode : return (vl->cornpare(vr, LessThantype) ) ;

case LtEqOpcode : return (vl->compare(vr,LessThan~~t~pe));

case Gt Opcode : return (vl->~ompare(vr,Great~hantype));

case GtEqOpcode: return (vl->compare (vr , Great~han~qtype) ) ;

case AtleastOpcode : return new OCLSetQuant (Atleast~~~e ,vl->~etnumb() ,

vr->GetSetCol()) ;

case Atmostopcode : return new OCLSetQuant (Atmost~~pe, vl->~etnumb () ,

vr->GetSetCol() ) ;

case Justopcode : return new ~ ~ ~ S e t Q u a n t (JustType, vl->Getnumb ,

vr->GetSetCol () ) ;

case EveryOpcode:

Page 70: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

return new O C L S ~ ~ Q U ~ ~ ( ~ v e r ~ ~ ~ p e , O ,vl->~et~et~ol() ) ;

case SomeOpcode: return (new ~~~~et~uant(~ome~ype,~,vl->GetSetColo));

case Dot Opcode : return vl->dot (vr) ;

case SizeOpcode: return new QCLNumber (vl->Size () ) ;

case Notapcode : return (vl->not () ) ;

>

Expr-string: :~xpr-string(char *c)

< int len = strlen(c) ; string-expr = new char [len+l] ; assert (string-expr ! = 0) ; strcpy(string-expr , c) ;

//expr-der.C #include<stdio.h> #indude "expr . h" #include "oclva1ue.h" #indude Itstring.h" #indude "table. h" sinclude "DList . h"

extexn hashTable vartable; // contains variable read from input //along with its type

Expr-subrange::Expr-subrange(int in,Expr *l,Expr *r,Opcode opl) : Expr (1, r , opl)

C collect-type = in;

char *Expr-subrange::typechecking()

62

Page 71: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

{ //format:collection-kind LCBKTK expr THREEDOTTK expr RCBKTK //both left & right operands should be number type and left //value should be smaller than right value

Expr *left , *right ;

if (Lef taperand) left = LeftOpermd;

if (RightOperand) right = RightOperand;

char *t ;

if (!strcmp((t = left->typechecking()),right->typechecking())) if ( ! strcmp (t , "OCLNumber") ) {

printf("\nEXPE~T NUMBER IN BOTH LEFT AND RIGHT EXPRESSION\n1'); return NULL;

3 if (((OCLValue *) left) ->Getnumb() > ((OCLValue *) right) ->Getnumb ()) {

~rintf("\nLEF~ EXPR SEOULD BE SMALLER OR EqUAL TO RIGHT EXPR\nW); return NULL ;

3

return t ; 3

OCLValue *Expr,subrange : : evaluate () {// format: collection-kind LCBKTK expr THREEDQTTK expr RCBKTK

collection<int> *mycol = new collection<int>(); set<int> *myset ; listeint> *mylist ; bag<int> *mybag ; OCLValue *vl = get-lef top () ->evaluate() ; OCLValue *vr = get-rightop () ->evaluate () ;

switch(collect-type) ( case 1:

myset = new set<int>() ; mycol = myset; break;

Page 72: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

case 2: mylist= new list<int> () ; mycol = rnylist; break;

case 3: mybag= new bag< int > (1 ; mycol = mybag; break;

3 return new OC LE^^ ity(myco1) ;

Expr-query::Expr-query(DList<Qualifier> *q,int in,Expr *1, Expr *r ,Opcode o p i ) :~xpt-subrange(in,l ,r, opl)

(

char *Expr-query : : typechecking () (//format: collection-kind LSQBKTK qualifier-list BARTK expr RSQBKTK

if (EmptyList () ) i printf ("\nINVALID EMPTY EXPRESS ION\nt ' ) ; return NULL;

// The 1st qualifier in the qualifier-list must be of type generator qual-list->Reset(); // Reset to the beginning of the list Qualifier *current = qual-list->GetCur() ; if (strcmp (current +get -qualtype () , "~enerat or") ) {

// if not type Generator print error message printf ("\nEXPECT GENERATOR AS FIRST QUALIFIER IN QUALIFIER LIST\nfl) ; return NULL;

3

//typecheck each qualifier of qualifier-list while(current=qual-list->GetCur()){

if ( ! current->typechecking() ) { //MJLL type printf ("\nINVALID EXPRESSION\nl') ;

Page 73: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

r e t u r n NULL;

3 c u r r e n t = q u a l - l i s t - > ~ o N e x t ~ ) ;

3 / / typecheck the re turned express ion cha r * t = ge t - l e f top () ->typechecking() ; i f ( ! t ) (

p r i n t f ('%INVALID RETüRNED EXPRESSION\nU) ; r e t u r n NULL;

3

r e t u r n t ;

OCLValue *Expr,query : : evalua te () {//format: col lect ion-kind LSQBKTK q u a l i f i e r - l i s t BARTK expr RSQBKTK

/ / eva lua te each member of q u a l - l i s t ; i f it re tu rns t r u e , con t inue / / eva lua t ing next member ; i f it r e t u r n s f a l s e , f o r Generator : backup / / t o t h e previous Generator t o e v a l u a t e t h e previous Generator again / / ( f e t c h next ob jec t ) ; f o r f i l t e r : backup t o t h e previous Genera tor / / t h a t matches t h e i d , e v a l u a t e t h e Generator again, then e v a l u a t e t h e //f i l t e r ; cont inue t h i s process u n t i l f i l t e r r e tu rns t r u e ; when f i n i s h //one round, if t r u e f o r a l 1 f i l t e r s , add objec t t o t h e s e t ;

/ / A Generator r e t u r n s an OCLEnt i t y which contains ob j ec t /db ins tance / / A f i l t e r r e t u r n s OCLBoolean which conta ins boolean va lue and a v a r i d

Q u a l i f i e r *current , *tmpqual ; co l l ec t ion<anen t i ty> * r e s u l t = new col lac t ion<anent i t y > ( ) ; OCLValue *gen,val , *f i l t e r - v a l ; int done, f inished = 0;

cha r * re t type ;

qual - l i s t ->Reset ( ) ; // Reset t o t h e beginning of t h e q u a l - l i s t while ( ! f in i shed) (

done = 0 ; while(current=qual-list->GetCur()) {

i f ( ! strcmp (curent ->get -qual type () , "Generat or") ) { / / i s a Generator gen-val = c u r r e n t ->evaluat e () ;

Page 74: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

i f ( ! gen-val->get-ob j e c t () ) C//Generator r e t u r n s NULL ob j done = 0 ;

cu r r en t -> reeva lua t e ( ) ; //reset t h e i t e r a t o r of t h e / / c u r r e n t Gen.

tmpqual = qual-l ist->GoPrev() ; //backup t o t h e p rev ious / /Generator

v h i l e (tmpqual && strcmp (tmpqual->get-qualtype() , "Generator") ) / / no t a Gen .

tmpqual = qual - l i s t ->Prev( ) ; i f ( ! tmpqual){ / / lst g e n e r a t o r of t h e l i s t r e t u r n s NULL

f i n i s h e d = 1; / /ge t ou t of t h e loop b reak ;

> > e l s e { / /Generator r e t u r n s val id obj

doiie = 1;

c u r r e n t = q u a l - l i s t - > ~ o N e x t ( ) ;

1 e l s e { //is a f i l t e r

f i l t e r - v a l = c u r e n t - > e v a l u a t e ( ) ; if ( ! f i l t e r -va l ->Getbool ( ) ) ( //f i l t e r r e t u r n s f a l s e

done = 0 ; tmpqual = q u a l - l i s t - > ~ o P r e v ( ) ; //backup if (!filter-val- etva va ri do) //NULL i d : backup t o t h e

/ /prev Gen while(tmpqua1 && strcmp(tmpqua1->get-qualtype () ,

l' Generat or") ) tmpqual = qual - l i s t ->GoPrev( ) ;

e l s e //No NULL i d : backup t o t h e prev Gen t h a t matches i d

w h i l e (tmpqual &&

strcmp (tmpqual->get-qualtype () , "Generat or") &&

strcmp (tmpqual->get-ident () , f i l t e r -va l ->Ge tva r id ( ) ) )

tmpqual = qual- l is t ->GoPrev() ; i f (tmpqual->evaluate () ->get-ob j e c t () ) / / eva lua te gene ra t o r

//node w h i l e (qual-list->GoNext () ! = cu r ren t )

#

e l s e ( done = 0;

Page 75: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

break; 3

3 e l s e ( / / f i l t e r r e t u r n s t rue

done = 1;

cu r ren t = qua l - l i s t -XoNex t (1 ; 1

3 ) / /end cu r r en t i f (done) (

/ / eva lua t e t h e r e t u r n e d e x p r e s s i o n OCLValue *va l - re t = g e t - l e f t o p o ->evaluate() ; i f (val-ret- etva var id() ) / / r e t u r n e d expr is n o t a s imple c h a r a c t e r

r e t t y p e = v a l - r e t - X e t T y p e (1 ; else (

result->add(gen-val->get-obj e c t () ) ; r e t t y p e = v a r t a b l e . l o o k ( v a 1 - r e t - > ~ e t s t r () ) ;

> qual - l i s t ->Rese t () ; //start over f rom t h e 1st g e n e r a t o r t o

//f e t ch new obj e c t

l- ) //end f i n i s h e d

r e t u r n new OCLEntity(gather-result(get-coltype(),result,rettype));

a n e n t i t y *Expr-query::gather-result(int c o l t y p e , c o l l e c t i o n < a n e n t i t y > *mycol, char +re turn type)

se t<person> *mysp = new se t<pe r son>( ) ; se t<cour se> *mysc = new se t<cour se> (> ;

l i s t < p e r s o n > *mylp = new l i s t < p e r s o n > () ; l i s t < c o u r s e > *mylc = new l i s t < c o u r s e > () ; bag<person> *mybp = new bag<person>(>; bag<course> *mybc = new bag<course> () ; i t e r - l i s t < a n e n t i t y > *myiter = neu i t e r - l i s t < a n e n t i t y > (mycol) ;

if ( ! strcmp ( re turn type , "Person") ) swi tch(co l type) {

Page 76: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient
Page 77: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

return mylc;

case 3: //Bag //move instance from mycol list to myf inal list myiter->f irst () ; /* reset to the beginning of the list */ while (myiter->POS() != NULL){ /* current is not nul1 */

mybc->add((course*) (void *)myiter->current()); myit er-hext () ;

1 return mybc;

Expr *r):Expr-subrange(in,l,r,opl) {

expr-list = e; >

char *Expr-special::typechecking() {//f o n n a t : collection-kind LCBKTK expr-list RCBKTK //ensure each expression in the expr-list has the same type //and return its type.

char *typel, *type2; Expr *current ; expr-list->Reset () ; current = expr-list->GetCur () ; typel = current->typechecking() ; current = expx-list ->GoNext () ; while(current = expr-list->GetCur()) {

if ((type2 = current->typechecking()) && !strcmp(typel,type2)) current = expr-list->GoNext();

else ( printf ("Expressions are not of the same type\nI1) ; return N n L ;

3 j

return typel ;

Page 78: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

OCLValue *Expr-special : : eva lua te () {//format: co l lec t ion-kind LCBKTK e x p r - l i s t RCBKTK

/ / r e tu rn OCLSet

Expr *current ; set<OCLValue> *myset = new set<OCLValue>(); list<OCLValue> *mylist = new l i s t < O C L ~ a l u e > ( ) ; bag<OCLValue> *mybag = new bag<OCLValue> () ;

switch(get-coltype() ) {

case 1: //Set expr- l is t ->Reset () ; while(current = expr-list->GetCur()) {

myset ->add (current - > @ v a h a t e () ) ; cur ren t = expr- l is t -XoNext () ;

> r e t u r n new O C L S ~ ~ (myset) ; / /should have OCLSet with set<OCLValue> a s member

case 2: / / L i s t expr- l is t ->Reset () ; while (current = expr - l i s t -Xe tCur () ) {

mylis t ->add(curïent-)evaluat e () ) ; current = expr-list->GoNext () ;

return new OCLList(rny1ist); / /should have O C L L i s t case 3: //Bag

expr-Est->Reset () ; vh i l e (cur ren t = e x p r - l i s t - > G e t ~ u r ( ) )

mybag->add (current ->evaluate () ) ; cur ren t = expr- l is t -XoNext () ;

3 r e t u r n new OCLBag(mybag); //should have OCLBag //end switch

1

Page 79: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Opcode op1 , Expr *1, Expr *r) : Expr (1, r , op l )

< i den t i f ier=new c h a r [ s t r l e n ( i n ) +II ; s t r c p y ( i d e n t i f i e r , i n ) ;

3

//main. C #include Ciostream. h> # i n c h d e C f stream . h> # i n c h d e < s t r i n g . h > Xinclude " s t r i n g . h" # i n c h d e " t o k e n - h W #include " e r r o r . h" # i n c h d e " t a b l e . h"

t a b l e symtable (50) ; //schema of d a t a b a s e hashTable v a r t a b l e ; / / va r i ab le s / id s r e a d from query functTable macrotable; //macre read from query dbtab le da t abase ;

# i n c h d e "1ex.h" t i nc lude "syn .hW # i n c h d e "prog . h" t i nc lude "expr . h"

t inc lude " e n t i t y - h "

ex tern FILE *yyin; ex t e rn Prog *program ;

int yyparse (void) ;

i n t main( int argc, cha r **argv)

yyin = NULL;

if (a rgc != 3)C p r i n t f ("\nusage : t h e t e s t eschema f i l e n m e > <query f i l e n m e > \n") ;

Page 80: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

exit (1) ;

>

//read schema first if stream f -in(argv Cl] ) ;

if (!f,in)( printf ("\nFile %s cannot be opened\nW , argv Cl] ) ; exit (1) ;

3

//read query last if ( (yyin=f open(argv C2J , "r") ) ==NULL) {

printf ("\nFile %s can not be opened\nW , argvC21 ) ; exit (1) ;

> //parse schema curr-tok = get,token(f,in) ;

schema-def (f -in) ; //return no-of-errors;

//create dbtable database with sample objects person *pl = new per~on(~~~ob~~,"lll Y~yo",~~~lorida") ;

person *p2 = new person("~ohn","l23 Palm","Texas"); collection<anentity> *setperson = new collection<anentity>(); setperson->add(pl) ; setperson->add(p2) ; dbtable-rec *d= new dbtable-rec("Person4', setperson) ; //database ob j ect s dat abase . add-tbl (d) ;

Page 81: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

#indude <stdio.h> tinclude "prog . h" tinclude "DList.hV tinclude "expr.hU

void Prog : : Print Struct (int level)

< for(int i=O;i<level;i++)

printf ("\tu) ; printf ("PROGRAM : ") ; if (! EmptyList ())

Expr *anexPr ; lstexpr->Reset () ; int j=i; while (anexpr=lstexpr->~ext () )

< printf ("\nl') ; for(int i=O;i<level+l;i++)

printf ('\t ") ;

printf ("Expression #%d: \dl, j++) ; anexpr->PrintStruct (level+2) ;

l- l- printf ("\nl') ;

void *Prog : : evaluat e () <

Expr *curexpr ; if (!EmptyList())(

this->lstexpr->Reset () ; while (curexpr=lstexpr->Next () ) (

char *type = curexpr->typecheckingo;

Page 82: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

//qua1 . C

# inc lude<std io .h> # i n c l u d e < s t l . h> / / f o r b u i l t - i n i t e r a t o r #include "qua1 .hW ainc lude "expr . h" # i n d u d e "oc lva lue .hlt # i n d u d e " t a b l e . hlf

ext e rn hashTable va r t ab le ; // c o n t a i n s va r i ab le read f rom input along //with i t s t y p e

extern t a b l e symtable; // c o n t a i n s database schema: c l a s s names, methods . . . extern d b t a b l e da tabase ; // con ta ins t h e r e a l da tabase extern functTable macrotable ; / /cont a i n s macro name and expression t r e e

/********+****************************************************************/ Generator : : Generator(char * id , Expr *in-expr)

: Qualif ier(llGenerator'l , i d , in-expr) {)

char *Generator::typechecking() C / / f ormat : IDENTIFIER LIMPLTK express ion (LIMPLTK : <- )

//IDENTIFIER should not e x i s t i n va r t ab le . //if r i g h t e x p r i s of type STRING EXPRESSION, t h e n it should / / e x i s t i n db tab le database; r e t u r n type of r i g h t expression / / I n a d d i t i o n t o re turn t h e t y p e , typechecking a l s o s e t up t h e //IDENTIFIER and i t s type i n v a r t a b l e .

name *dbname; char * i d = get , ident() ; i f ( v a r t a b l e . look(id) ) {

p r i n t f IDENTIFIER %s ALREADY DEFINED EARLIER\nW , i d ) ;

return NüLL;

/ / typecheck char * typ =

if ( ! typ)C

r i g h t expression g e t -rexpr() ->typechecking () ;

Page 83: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

p r i n t f ("\nINVALID EXPRESSION %s\nU , t y p ) ; r e t u r n NULL;

3 / / r i g h t expression can be a s i n g l e S t r i n g (e.g Departments, / /S tuden t s , e t c . ) , o r a c o l l e c t i o n of S t r i n g , o r type r e s u l t e d //from a dot expression (e .g . c <- s - t a k e s , r i g h t expression / / r e tu rns type Course). If i t ' s a s i n g l e s t r i n g , then verify / / i f it e x i s t s i n symtable, database schema.

i f ( ! s t rcmp(typ,"St r ingU)) { i f ( ! strcmp("String" ,get-rexpr()->GetType() )) {//s ingle S t r i n g

s t r i n g s = s t r ing(ge t - rexpr () ->evaluate() ->Getstr() ) ; if ((dbname = symtable . look(s) ) &&

(dbname->get - idkind () ==DATABASE) ) t y p = dbname->get-typekindc) ->ge t - s t r 0 .get-s () ;

e l s e ( p r i n t f ("\nINVALID EXPRESSION %s\nl ' , get-rexpr (1->evaluate() - > ~ e t s t r ( ) ) ; r e t u r n NULL;

3 3

>

record *newrec = new r e c o r d ( i d , t y p ) ; v a r t a b l e . i n s e r t (newrec) ; r e t u r n t y p ;

OCLValue *Generator : : eva lua te (1 {//format : IDENTIFIERTK LIMPLTK expr

//IDENTIFIER e x i s t s i n v a r t a b l e , if i t s i t e r a t o r i s NULL, / /get i t s type and se tup i t s i t e r a t o r . I f i t s i t e r a t o r is / h o t NULL, move i t e r a t o r t o next o b j e c t . Return current //abject of i t e r a t o r a f t e r se tup o r after moved.

char * i d = ge t - iden t ( ) ; s t r i n g s = s t r ing(var tab1e . look( id) ) ; / / r e t u r n type of i d then

/ /conver t it t o s t r i n g if (!symtable.look(s)){ //if type of i d does no t e x i s t i n symtable

Page 84: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

i f ( ! vartable.get-objiter(id)) { / / i t e r a t o r i s NULL OCLValue *v = ge t -rexpr () ->evalua t e () ; OCLValue : : i t e r a t o r it = v->get-col ()->begin() ; v a r t a b l e . pu t -ob j i t e r ( id , i t ) ; r e t u r n new OCLEntity(*it); //*it r e t u r n s c u r r e n t o b j e c t of it

> e l s e { / / i t e r a t o r i s not NULL, move it t o next o b j e c t

i t + + ; //??net su re about t h i s r e t u r n new OCLEntity(*it) ;

3 e l s e { / / t y p e of i d e x i s t i n symtable

if ( ! v a r t a b l e . ge t -ob j i t e r ( id ) ) { / / i t e r a t o r i s NULL i t e r - l i s t < a n e n t i t y > *set i t e r = new i t e r - l i s t < a n e n t i t y >

(da tabase .get-set ( v a r t a b l e . l o o k ( i d ) ) ) ; / / c r e a t e i t e r a t o r v a r t a b l e . pu t -ob j i t e r ( id , s e t i t e r ) ; / / s e t up i t e r a t o r f o r i d

/ / i n va r t ab le r e t u r n new OCLEnt i t y ( s e t it e r ->cur ren t () ) ;

3 e l s e ( / / i t e r a t o r i s not NULL

v a r t a b l e . i t e r -nextobj ( i d ) ; //rnove it t o next ob j r e t u r n new OCLEntity(vartab1e. get-curob j ( id) ) ;

>

OCLValue *Generator : : reeva lua te () { / / r e se t t h e i t e r a t o r of t h e va r i ab le i n t h e v a r t a b l e t o t h e beginning

char * id = g e t - i d e n t () ; i f ( v a r t a b l e . g e t - o b j i t e r ( i d ) ) { / / f o r c a u t i o n only: i t e r a t o r i s n o t NULL

v a r t a b l e . r e s e t , i t e r ( i d ) ; r e t u r n new OCLEnt i t y (va r t ab1e . ge t -curobj ( id ) ) ;

3 r e t u r n NULL ;

3

char *Localdef : : typechecking ()

Page 85: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

{//format: IDENTIFIERTK ASTK expr //IDENTIFIER should not exist in vartable, insert IDENTIFIER in rnacrotable //along with the type returned from expr->typechecking() ; and a pointer to //expression tree

char *id = get-ident(); if (vartable.look(id)) (

printf("\nIDE~~1~1~~ % s ALREADY DEFINED EARLIER\nU,id); return NULL ;

//typecheck right expression char *typ = get -rexpr () ->typechecking () ;

if ( ! typ) ( printf ("\nINVALID EXPRESSION %s\n" ,typ) ; return NULL;

>

funct-record *newrec = new funct-record(id,typ,get-rexpro); macrotable . insert (newrec) ; return t y p ;

OCLValue *Localdef : : evaluate () {//f omat : IDENTIFIERTK ASTK expr //DonJt know what to do here, since 'exprJ is evaluated only when //IDENTIFIER is encountered in a normal expression

return new OCL,Boolean(true);

Hasclassqual: :Hasclassqual(Expr *l,Expr *r,char *id, char *typ="Hasclass") : Qualifier (typ, id, r)

< leftexpr = 1;

3

char *Hasclassqual::typechecking()

77

Page 86: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

C // Hasclassqual format : expr HASCLASSTK e x p r ; // l e f t e x p r should e x i s t i n va r t ab le with r e t u r n e d t y p e T // Verify if type r eques ted i n query ( r i g h t e x p r ) is indeed a derived // c l a s s of T; look f o r r igh texpr in symtable, if found, compare it wi th // type T r e tu rned from searching f o r l e f t e x p r i n v a r t a b l e , i f T i s indeed // a superc lass of r i g h t expr , then modif y l e f t e x p r and r i g h t e x p r p o i n t e r s // t o t h e eva lua ted va lues ( v l and v r below)

OCLValue *vl = g e t Jexpr () ->evaluate () ; OCLValue *vr = get - rexpr () ->evaluat e ( ) ; namenode *c; name* n; char * id , * t y p l , *typ2; i n t done = 0 ; if ( ! strcmp (vl->GetType() , "OCLString") &&

! strcmp(vr->GetType() , "OCLStringU)) ( i d = v l ->Get s t r ( ) ; typ2 = vr ->Get s t r ( ) ; // t y p e r e q u e s t e d from quer ies i f ( ( t y p l = v a r t a b l e . look( id) ) &O (n = symtable . l ook(s t r ing ( typ2) ) ))

while((c=n->get-super()) 88 !done) / /n has supe rc la s s if ( ! strcmp(typ1,c->get-info()->get-stro . ge t - s ( ) ) )

// i f l e f t i s s u p e r c l a s s of r i g h t r e t u r n typ2;

else n = c->get- info() ; //move n one l e v e l up i n t h e a n c e s t o r / / h i e ra rchy

/ / t ype of l e f t e x p r i s not a super type of r i g h t e x p r p r i n t f ( " \ n INVALID EXPRESSIONS: %s \nf l , typ2); r e t u r n NULL;

3 p r in t f ( " \n HASCLASS ACCEPTS STRING EXPRESSIONS ONLY\nn); r e t u r n NULL ;

3

OCLValue *Hasclas squa l : : evalua t e () C // Hasclasçqual format : expr HASCLASSTK e x p r

// l o c a t e type of l e f t e x p r i n database t o get t o t h e s e t of da tabase // t r a v e r s e t h e set and c o l l e c t member t h a t i s t h e ob jec t of r i g h t e x p r

char * id = g e t - l e x p r ( ) ->evaluate () - > ~ e t s t r ( ) ; char * typl = v a r t a b l e . l o o k ( i d ) ; // t y p e recorded i n v a r t a b l e f o r

Page 87: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

//lef t expr char *typ2 = get -rexpr () ->evaluate () ->Getstr() ; // type request ed f rom

//queries iter-list<anentity> *iterat=new iter-list<anentity>

(database .get-set (typl) ) ; collection<anent ity> *mycollection = new collect ioncanent ity> () ; calculate (mycollect ion, iterat , typ2) ; if (!(mycollection->is-empty()))

return new OCLSet(mycollection); return O;

1

void Hasclassqual::calculate(collection<~entity> *rnycol, iter,list<anent i t y ) *iter , char *c)

C // traverse each member of the iterator 'iterJ, if it has type c // then add it to mycol

char *t ; iter->f irst () ; // reset to the beginning of the list while (iter->PoS() != NULL){ //invoke 'GetType' method on each member

t = iter->current () ->~etType () ;

if (!strcmp(c,t)) mycol->add(iter->current () ) ;

iter->next () ; 1

/************************************************************************/ Hasclasswithqual : :Hasclasswithqual (Expr *e ,Expr *1, Expr *r,

char *id) :~asclassqual(l, r, id, "~asclasswith")

thirdexpr = e;

1

char *Hasclasswithqual::typechecking() {// f omat : expr HASCLASSTK expr WITHTK expr

return (~asclassqual : : typecheckingo ) ;

3

Page 88: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

//string. c // string.^ : strings of characters / / essentially C++ book pl84 et seq

lt include ltinclude # include

cstream. h> "error .hl' ''string .hW

string::string(

€ p = new

const

srep ;

char* s )

p->lth = strlen(s) ; p->s = new charcp->lth+l] ; strcpy( p+s, s ) ;

p->rcnt = 1;

string: :string() €

p = new srep; p->lth = O; p+s = O; p->rcnt = 1;

string::string( const string& x )

string: :operator=(

p->rcnt > 1 ) p->rat--; p = new srep;

const char* 1

self

Page 89: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

p->l th = s t r l e n ( s ) ; p->s = nev cha r Cp->lth+i] ; s t r c p y ( p->s, s ) ;

p->rcnt = 1;

r e t u r n * t h i s ;

s t r i n g & s t r i n g : : opera t or=( cons t s t r i n g & x )

< x.p->rcnt++;/ /protect a g a i n s t "st = st" if ( --p->rcnt == O ) {

d e l e t e [] p->s; delete p ;

3 p = x.p;

r e t u r n * t h i s ;

s t r i n g : : - s t r i n g ( ) <

i f ( p->rcnt == O )

e r r o r ( ' ldes t ruc t ing s t r i n g wi th z e r o re f e rence count" ) ; / / cout << I1<destruct ing s t r i n g : " << * t h i s << I l > " << end l ; if ( --p->rcnt == O ) {

// cout << " r e a l l y " << e n d l ; d e l e t e C] p->s ; d e l e t e p ;

char& s t r i n g : : opera to r 11 ( i n t i )

C i f ( i < O 1 1 p->lth < i ) e r r o r ( "index out of range" ) ;

r e t u r n p->s [il ;

const char& s t r i n g : : operator [] ( i n t i ) cons t <

i f ( i < O I I p->l th < i ) e r r o r ( "index out of range" ) ;

r e t u r n p->s [il ;

Page 90: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

ostream8r opera tor<<( o s t r e d s, const s t r i n g & x )

< r e t u r n ( s << x.p->s ) ;

>

istreama opera tor>>( i s t r e a m â s, s t r i n g & x )

< char buf (2563 ;

s >> buf; x = buf ; / /us ing s t r i n g assignment r e t u r n s ;

s t r i n g concat ( cons t s t r i n g & s l , const s t r i n g & s 2 ) <

i n t I t h = s 1 . p - > l t h + s2 .p -> l th ; char* s = new c h a r [ l t h + l l ; s t r c p y ( s , sl .p->s ) ; s t r c p y ( s + sl . p - > l t h , s 2 .p->s ) ; r e t u r n s t r i n g ( s ) ;

i n t hash( const s t r i n g & x , i n t s i z e ) <

i n t ii = 0 ;

char* pp = x.p->s;

while( *pp ) ii = ii << 1 *pp++; i f ( ii < O ) ii = -11; return ii % s i z e ;

/ / t a b l e . C

// t a b l e . c : symbol t a b l e d e c l a r a t i o n s // C++ book page 155 and 156

// rnodif ied t o use s t r i n g c l a s s

Page 91: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

# i n c h d e Cstdl ib.h> # i n c h d e Cstr ing.h> # i n d u d e "e r ro r . hl1

# i n d u d e " s t r i n g . h"

# i n d u d e "tab1e.h" # i n d u d e "expr-h"

#def i n e HASHSIZE 21

t a b l e : : t a b l e ( i n t sz )

i f ( s z C O ) e r r o r ( "negative table size" ) ;

t b l = new name* [ size = sz 1 ; f o r ( i n t i = O ; i < s z ; i++ ) t b l c i l = 0 ;

>

t a b l e : : - t ab le ( ) €

f o r ( i n t i = O ; i < size; i++ )( name* nx; f o r ( name* n = t b l c i ] ; n ; a = nx) (

nx = n -> next; d e l e t e n ;

3 delete t b l ;

name* t a b l e : : look( const s t r ing& p )

i n t ii = hash ( p , s i z e ) ;

f o r ( name* n = tbl [ii] ; n; n = n->next ) / /search i f ( p == n->st r ) return n;

/ h o t found, s o re tu rn nul1 po in t e r r e t u r n O ;

name* t a b l e : : i n s e r t ( const s t r i ng& p )

Page 92: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

i n t ii = hash( p , size ) ;

for( name* n = t b l [ii] ; n; n = n->next ) / / s ea rch if ( p == n - > s t r ) r e t u r n n ;

nane* nn = new nune( p , t b l [ i i ] ) ;

t b l c i i ] = nn; r e t u r n nn;

void namenode : : p r i n t ( ostream& o s )

if ( nex t )

€ OS << ",";

name::name( cons t s t r i n g & nxt

s t r = p; id-kind = CLASS;

type-kind = 0 ; super = 0; next = n x t ;

d e l e t e super ;

void name : : addsuper( name* n )

< super = new namenode ( n, super ) ;

> void name: : p r i n t ( ostreamk os )

Page 93: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

"

9 0) k P . " - - a O X Li

v v II] O

. . Ci

E P a,

3 O

. " - - C, 0 +' / . . - .. v v k Ci II]

v v tn

Page 94: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

for (int i = O; i < size; i++) €

for (t = tableCi] ; t; t = tt)

<

delete table;

3

int hashTable : : hash(char *str)

unsigned i;// to ensure that the hash value is non-negative

for (i = O; *str; str++) i = *str + 22 * i;

return i % size; 3

char* hashTable::look(char *str)

< for (storageTable* t = table[hash(str)] ; t; t = t->next)

if (!strcmp(str, t->entry->getName())) '

return t->entry->get~ameType() ; return O;

3

iter,list<anentity>* hashTable : :get-ob j iter(char *str)

for (storageTable* t = table[hash(str)] ; t; t = t->next) if ( ! strcmp(str, t->entry->getName() ) )

return t->entry->get-obj iter() ;

return O;

Page 95: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

void hashTable: :put-ob j i t e r ( c h a r * s t r , i t e r - l i s t c a n e n t i t y > *ent)

< f o r ( s t o r a g e ~ a b l e * t = t a b l e [hash(s t r ) ] ; t ; t = t ->next)

i f ( ! strcmp ( s t r , t->entry->getName () ) ) t->entry->putObj e c t (ent) ;

>

void hashTable : : i te r -nextob j (char *str)

f o r ( s t o r a g e ~ a b l e * t = t a b l e [ h a s h ( s t r ) ] ; t ; t = t ->next ) i f ( ! strcmp ( s t r , t->entry->getlame() ) )

void hashTab1e::reset-iter(char * s t r )

i f o r (storageTable* t = t ab le [hash( s t r ) ] ; t ; t = t ->next)

i f ( ! strcrnp(str , t->entry->getName () ) )

t ->en t ry ->rese t , i t e r ( ) ;

> m e n t i t y * hashTable : : get-curob j (char *c)

f o r ( s t o r a g e ~ a b l e * t = t a b l e [hash(c)] ; t ; t = t ->next) i f ( ! strcmp(c, t ->entry->get lame()))

r e t u r n t ->ent ry->get -curob j () ; re turn O;

>

void hashTable : : i n s e r t ( record *rec)

if(look(rec->getName())) r e t u r n ; / /don ' t i n s e r t - i t ' s a l r eady i n i n t i; / / i n s e r t otherwise st orageTable* t = new s t orageTable ; t ->ent ry = rec; t ->next = t a b l e [i = hash (rec->getName () ) 1 ; t a b l e c i ] = t ;

>

Page 96: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

void hashTable : : p r i n t ()

i n t i; f o r (i = O ; i <= size; i++)

f o r (storageTable* t = t ab le [il ; t ; t = t->next) cout << "Id ( "<<t->entry->getName()<< '' )

of Type : Il<< t->entry->getNameType() <<endl ;

3 //************************************************************************

functTable : : functTable ()

table = new functstorage* [size = HASHSIZE] ; f o r ( i n t i = O ; i < size; i++)

tableci] = 0 ;

for ( i n t i = O; i < size; i++)

functstorage* t ; f unct st orage* tt ; f o r ( t = tableCi]; t ; t = tt)

<

delete table;

i n t functTable : : hash(char *str)

unsigned i; // t o ensure that t h e hash value is non-negative f o r ( i = O ; * s t r ; str++)

i = * s t r + 22 * i ; return i % size;

3

Page 97: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

char* functTable : : look(char *str)

{ for (functstorage* t = table[hash(str)l ; t; t = t->next)

if ( ! strcmp (str , t->entry->get~ame 0 ) ) return t->entry->getNameType() ;

return O;

Expr* functTable : :get-eaprtree (char *str) <

for (functstorage* t = table[hash(str)l; t; t = t->next)

return t->entry->get-exprtree () ; return O;

void functTable: :put-expr(char *str, Expr *e)

< for (functstorage* t = table[hash(str)j ; t; t = t->next)

if ( ! strcmp (str, t->entr~->~et#ame () 1) t ->entry->put expr (e) ;

void functTable: : insert (f unct-record *rec)

if(look(rec->getNameo)) return; //donJt insert - itJs already in int i; //insert otherwise functstorage* t = new functstorage ; t->entry = rec; t->next = table Ci = hash (rec->getName() ) 1 ; tableci] = t;

void functTable: :print ()

int i;

for (i = O; i <= size; i++) for (functstorage* t = table [il ; t ; t = t->next) (

Page 98: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

cout << "Id ( " <<t->entry->getMame() << " ) of Type : " <<t->entry->getNameType() <<endl;

dbtable- rec *dbtable: : look(char *c)

for (dbtab1e-rec *db = head; db; db = db->get-next()){

char *t = db->get-tblname () ;

if ( ! strcmp (t , c) ) r e t u r n db ;

3 r e t u r n O ;

3

void d b t a b l e : : add-obj (anent i ty * O , c h a r *c) //add o b j e c t ' O ' t o t h e t a b l e named 'c'

C if (dbtable- rec *d = look(c) )

d->add,obj ( O ) ;

e l s e p r i n t f (" INVALID TABLE NAME\nl') ;

>

void d b t a b l e : : add-tbl (dbtable-rec *t) //add new t a b l e

i n t found = 0 ;

dbt ab le - rec *tmp ; i f (!head) / / t a b l e is empty

head = t ;

else ( f o r (tmp = head ; tmp ; trnp = tmp->get -next () ) {

c h a r *tl = tmp->get-tblname() ; char * t 2 = t->get-tblname() ;

if ( ! strcmp(t1 , t 2 ) ) ( //search, i f found do n o t add

found = 1 ; break;

3 3 if (!found)( // i f not found, add t o t h e end o f t h e l i s t

Page 99: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

c o l l e c t i o n ~ a n e n t i t y > *db tab le : :ge t - se t ( cha r *c) //get l i s t of o b j e c t of t a b l e ' c J

if (db tab le - rec *d = l o o k ( c ) ) r e t u r n d->get -set () ;

r e t u r n NULL;

1

/ /va lue . C # inc lude<s td io .h> # inc lude<asse r t . h> # i n d u d e "expr . h" # i n c h d e "oc lva lue # inc lude " t a b l e . hl1

e x t e r n hashTable v a r t a b l e ; / / con ta ins v a r i a b l e r e a d from input / / a long wi th i t s type

e x t e r n func tTable mac ro tab le ; / / conta ins macro name and expression tree

c h a r *OCLValue : : et var id()

r e t u r n varid; 3

void 0CL~alue::put-varid(char *c)

< varid = c;

3

Page 100: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

char *OCLValue : : Get Type () €3

OCLValue *OCLValue : : evaluat e () ()

OCLValue *OCLValue::plus(OCLValue *TT) (3

OCLValue *OCLValue::minus(OCLValue *v) ()

OCLValue *OCLValue::multiply(OCLValue *v) (3

OCLValue *OCLValue::divide(OCLVaLue *v) {)

int OCLValue : : Getquant () ()

int OCLValue::GetSetnum() ()

long OCLValue : : Getnumb () €3

bool OCLValue::Getbool() (3

char* OCLValue : : Get str () (3

char* OCLValue : : Get ident () ()

int 0CLValue::SizeO 0

OCL-Boolean* OCLValue::not() ()

OCLValue *OCLValue::Compare(OCLValue *e, CompType t) {)

OCLValue *OCLValue::Comparenum(~~~~umber *n, CompType t) {)

OCLValue *OCLValue::Comparebool(OCL_Boolean *b, CompType t){)

OCLValue *OCLValue : : Compareset (OCLcollect ion * , CompType t) {>

OCLValue *OCLValue::Comparequantset(OCLSetQuant * s , CompType t) ()

OCLValue *OCLValue::CompareString(OCLString *s , CompType t) {)

92

Page 101: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

ment ity *OCLValue: :get-obj ect (1 {>

OCLValue *OCLValue::dot(OCLVafue *v) 0

void 0CLValue::print-item() ( 3

OCLNumber : : OCLNumber (long n , char *cl : 0CLValue (c)

OCLValue *OCLNumber::evaluate()

OCLNumber *n = new OCLNumber(this->numb-val); return n;

OCLValue +OCLNumber::Compare(OCLValue *e,CompType C) {// e: Rightoperand ; this : Leftoperand

return (e->Comparenum(this , C) ) ; 3

OCLValue *OCLNumber::~omparenum(OCLNumber *num,CornpType C) {// n u : Leftoperand ; this: Rightoperand

bool result = 0; switch(C) { case Equaltype :

if (this->numb,val == num->numb-val) result = 1 ; break;

case GreatThantype: if (num->numb,val > this->numb-val) result = 1; break;

case LessThantype : if (num->numb-val < this->numb-val) result = 1; break;

case LessThanEqtype: if ((nu->numb-val < this->numb-val) I I

Page 102: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

(this->numb-val == nu->nuab-val) )

result = 1; break;

case GreatThanEqtype :

if ( (nu->numb-val > this->numb-val) 1 1 (this->numb-val == num->numb-val))

result = 1; break;

> if ( ! this->Getvarid() )

return new OCL,Boolean(result,num->Getvarid()); else

return new OCL,Boolean(result);

OCLValue *OCLNumber : :plus (OCLValue *num)

return this;

3

OCLValue *OCLNumber::minus(OCLValue *numl

this->numb,val -= nu->~etnumb (1 ; return this ;

3

OCLValue *OCLNumber : : mult iply (0CLValue *nu)

€ this->numb,val *= nu->Getnumb () ; return this ;

3

OCLValue *OCLNumber::divide(OCLValue *num)

€ if (nu->Getnumb() != O)(

this->numb-val /= num->Getnumb () ; return this ;

Page 103: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

void OCLNumber::print,item()

C cout "OCLNumber: " << numb-val << "\nW;

>

void OCLNumber: :PrintStruct(int level = 0)

C //Expr : : PrintStruct (level) ; for(int i=O;i<level;i++)

printf ('\tW) ;

printf("0CLNumber ~xpression:"); print-item() ;

3 /************************************************************************/

OCL-Boolean: : OCL,Boolean(bool b, char *c) : 0~LValue (c) / C

bool-val = b;

3

OCLValue *OCL,Boolean : : evaluat e ()

return new OCL-Boolean(this->bool-val);

1

OCL-Boolean *OCL-Boolean::not()

C this->bool,val = ! (this->bool,val) ;

return this ;

3

OCLValue *EL-Boolean::Compare(OCLValue *e,CompType C) ( / / e : Rightoperand ; this : Lef toperand

if (C == Equaltype) return(e->~omparebool(this,C));

return new OCL-Boolean(f alse) ;

3

Page 104: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient
Page 105: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

l e n = s t r l e n ( s ) ; str = new char [ len+l] ; a s s e r t ( s t r ! = 0) ;

s t r c p y ( s t r , s ) ;

3

OCLValue *OCLString : : e v a l u a t e o

r e t u r n new ~ ~ ~ ~ t r i n g ( t h i s - > s t r ) ;

3

OCLValue *OCLString::~ompare(OCLValue *e,CompType C) {//e: Rightoperand ; t h i s : Leftoperand

returnce->Compare~tring(this,C)) ;

3

OCLValue *OCLString : :Comparestring (OCLString *s , CompType C) {//s: Leftoperand

i n t t ; boo l r e s u l t = f a l se ; / / f o r t h e case when s t r i n g r ep resen t s a macro if (macrotable. i ook( s ->s t r ) ){ / / e x i s t s i n macrotable

OCLValue * t r eeva l= macrotable .ge t -expr t ree ( s - > s t r ) ->evaluate () ; i n t t = s t r c m p ( t r e e v a 1 - X e t s t r ( ) , ~ e t s t r ( ) ) ;

> e l s e / /no t a macro i d e n t i f i e r

t = s t r c m p ( s - X e t s t r () , G e t s t r ( ) ) ; s w i t c h (c)(

case Equaltype : i f (t==O) r e s u l t = t r u e ; break;

c a s e LessThantype: if ( t < O ) r e s u l t = t r u e ; break;

case GreatThantype: i f (t>O) r e s u l t = t r u e ; break;

3 if ( ! th i s ->Getvar id( ) )

Page 106: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

r e t u r n new O~~,~oolean(result,s->Getvarid()); e l s e

r e t u r n new ~ ~ ~ , B o o l e a n ( r e s u l t ) ;

OCLValue +OCLString : :dot (OCLValue * s t )

€ // ' t h i s J p t r i s an OCLString con ta ins i d e n t i f i e r read from i n p u t . / / i f OCLString i s a r e s u l t of a p rev ious d o t , t hen ge t i d from i t s / /var id , else get i d f r o m i t s s t r of ' t h i s ' p t r , look f o r it i n v a r t a b l e , / /get t h e i t e r a t o r of t h e i d and g e t t h e c u r r e n t object , apply t h e method //on t h i s o b j e c t , t h e n add i d g o t from ' t h i s J p t r t o re turned OCLValue* //f rom method c a l 1 .

char *c ; if ( ! ( c = t h i s ->Getva r id ( ) ) )

c = t h i s - > G e t s t r ( ) ; OCLValue *v = v a r t a b l e .get,curobj (c) ->callrnefhod(st-v et str()) ; v->put,varid(c); r e t u r n v ;

void OCLString : : pr in t - i t em()

if ( s t r ) p r i n t f ( "S t r ing : %s\nEt , s t r ) ;

void OCLString: : PrintStruct ( i n t l e v e l = 0)

/ / ~ x p r : : ~ r i n t s t r u c t ( leve l ) ; f o r ( i n t i=O; i< leve l ; i++)

~ r i n t f ("\t") ; p r i n t f ( "S t r ing Expression-") ; print- i tem() ;

Page 107: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

OCLCollection::OCLCollection(collection~anentity~ *E,char *c):O~~~alue(c)

{ OCLSet-val->intersection(NULL);//ensure CLSet-val is a NULL collection OCLSet-val->union-col (E) ; //then have OCLSet-val points to E set-iter = new iter-list<anentity>(OCLSet-val) ; //iterator on OCLSet-val

>

OCLValue *OCLCollect ion : : evaluate ()

{ return new OCL~ollection(this->OCLSet-val);

>

OCLValue *OCLCollection::Compare(0CLVa1ue *e,CompType C) {//e: Rightoperand ; this : Leftoperand

returde->Compareset(this,C));

3

DCLValue +OCLCollection::Compareset(OCLCollection *s,CompType C) s : Leftoperand

bool result = false;

switch(C)( case Equaltype :

if (s->equal (this) ) result = true;

break; case LessThantype:

if (s->lessthan (this) ) result = trie;

break; case GreatThantype :

if ( ! (s->lessthan (this) ) ) result = true;

break; def ault : break;

1 if (!this->Getvarid())

return new OCL-Boolean(result,s->(;etvarid()); else

Page 108: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

return new OCL,Boolean(result) ;

OCLValue *~~L~ollection::plus(OCLValue *s) /* UNION operation */ €

(this->OC~set-val)->union-col(s->~etSet~ol());

return this ;

OCLValue *~~~~ollection::minus(OCLValue *s) /* DIFFER operation */ €

(this->~c~set-val) ->dif f er(s->Get~etCol() ) ; return this ;

>

bool OCLCollect ion: : equd (OCLCoIlect ion *s) <

if ((this->OCLS~~-val)->every(s->~et~etcol()) &Br

(this->~ize() == s->Size() ) )

return true ; else return f alse;

bool OCLCollection::lessthan(0CLCollection *s)

< if ((this->OCLSet-val) ->every(s->OCLSet-val) && (this->~ize() < s->Size () ))

return true; else return false;

void OCLCollection: : print-item()

< while (set-iter->POS() != NULL) < //current is not nul1

set-iter-kurrent () ->print-item() ;

set-iter->ne= () ;

3

Page 109: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

OCLSetQuant::OCLSetQuant(Qua.ntifierType Q,int n,collection<anentity> *C, char *c) : ~ ~ ~ C o l l e c t ion(C, c)

< Qt = 9; num = n;

OCLValue *OCLSetQuant::evaluate()

return new OCLSetQuant(this->Qt,this->num,this-)GetSetCol());

1

OCLValue *OCLSetQuant::Compare(OCLValue *e,CompType C) // Rightoperand is the ar (1

return(e->Comparequantset(this,C)); //Leftoperand is the arg. = this

3

OCLValue *OCLSetQuant : : Comparequantset (OCLSetQuant *s , CompType C) // Lef toperand

OCLValue *neuset = s->evaluate() ; bool result = false;

switch(C) (1

case Equaltype: switch(Qt) ( case SomeType :

if (newset->Cetquant (1 == ~omeType) C (newset->~et~et~ol())->intersection(this-~~et~et~ol()) ;

if ( ! (newset->~et~et~ol() ->is-empty () ) ) result = true;

break; 3 if (newset->Getquant (1 == EveryType) C

if (nevset->Get~etCol() +every(this->GetSetcoI () ) )

result = true; break;

3 if (nevset->Getquant() == ~t1eastType)C

if (newset->GetSetCol() ->a% least (newset->~et~etnum() , this->GetSetCol())) result = true;

Page 110: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

break;

3 if (newset->Getquant () == AtmostType) {

if (newset->GetSetCol() ->atmost (newset->~etsetnum() , this->GetSetCol() ) )

result = true; break;

3 if (newset->Getquant() == JustType) {

if (newset->GetSet~ol() -> just (neuset->Get~etnum() , this->GetSetCol())) result = true;

break;

3 case AtleastType:

if (newset->GetSetCol() ->atleast (newset->Get~etnum(), this->GetSetCol()) ) result = true;

break;

> def ault : break ;

3

return new O~L,Boolean(result,newset- etva var id()); else

return new O~L,Boolean(result);

OCLEntity : : 0CLE.t ity (anentity *i , char *c) : 0CLVaiue (c) <

objinstance = i; 3

OCLValue *OCLEnt ity : : evaluat e () <

OCLEnt ity *oc1 = new OCLEnt ity(obj instance) ; return ocl;

Page 111: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

OCLValue *OCLEntity::dot(OCLValue *st)

//'thisl ptr is an OCLEntity resulted from a dot expression. //'anentityJ ptr of OCLEntity actually points to a real o b j e c t , //apply the method on the current object, then add id got from 'this) //ptr to returned OCLValue* from method call.

OCLValue *v = get-ob j ect () ->callmethod(st->~etstr () ) ; v->put -varid(this->Getvarid() ) ;

return v;

Page 112: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Appendix C

Utility Code

/ / D L i s t . h /*************************************************************** ** Header File: DList ** Purpose: Template class for Doubly Linked lists ** Uses: NONE ** Inheritance: NONE *****************************************************************/ #include <stdio.h>

#if ndef D-LIST #define D-LIST

template C c l a s s T> class DLink ( public : DLink<T> *prev ; DLink<T> *next ; T *elemp;

~ ~ i n k ( T *inelemp = NULL) { prev-NULL; next=NULL; elemp = inelemp; -~Link() { if (elemp != NULL) delete elemp;)

template cclass T> class DList (

p r i v a t e : DLink<T>* f irst ;

Page 113: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

DLink<T>* last ; DLink<T>* cur ; DLink<T>* c u r 2 ; DLink<T>* cur3 ;

public :

DList() < first = NULL;last = NULL;cur = NULL; cur2 = NULL; > 'DList() {

DLink<T>* t emp ; for(; first!=NULL; first-temp) {

temp = first->next; delet e f irst ;

3

Insert (T *elemp) {

DLink<T> *node = new DLink<T>(elemp);

if (f irst==NULL) ( first = node; last = node; cur = node;

3 else (

node->next=f irst ; first->prev=node; f irstsnode;

Append(T* elemp) { DLink<T>* node = new ~~ink<~>(elemp);

if (f irst==NULL) ( first = node; last = node; cur = node;

3 else (

last->next = node; node->prev = last;

Page 114: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

las t = node;

Append(DList<~>* l i s t p ) { l i s tp ->Rese t () ; T* elem; whilecelem = l is tp->Next () )

this->Append(elem) ;

DelCur(> ( i f (cur != NULL) (

/* Only one element on DList */ i f ( f i r s t ->nex t == NULL) (

d e l e t e f irst ; f i r s t = NULL; last = NULL; c u r = NULL;

> /* More than one element on D L i s t

cur-eiem p o i n t s t o t h e f i r s t element on D L i s t */ e l s e i f (cur == f i r s t ) (

f i r s t = f i r s t - > n e x t ; f i r s t - > p r e v = NULL; d e l e t e c u r ; c u r = f i r s t ;

/* More than one element on D L i s t cur-elem p o i n t s t o t h e l a s t element on D L i s t */

e l s e i f (cur == l as t ) ( l a s t = l a s t - > p r e v ; las t ->next = NULL; d e l e t e cu r ; cur = NULL;

/* More t h a n one element on D L i s t cur-elem p o i n t s t o t h e middle element on D L i s t */

e l s e ( DLink<T>* t emp ; temp = cur ;

Page 115: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

d e l e t e temp ;

3 3

>

T* Prev() ( i f (cur == NULL)

r e t u r n NULL; DLink<T>* temp = c u r ; cur = cur->prev; r e t u r n ( t emp->elemp) ;

T* Next () ( i f (cur == NULL)

r e t u r n NULL; DLink<T>* temp = cur ; cur = cur->next; r e t u r n (temp->elemp) ;

>

T* Next2 () ( i f (cur2 == NULL)

r e t u r n NULL; DLink<T>* temp = cur2 ; cur2 = cur2->next; retudternp->elemp) ;

3

T* Next3() ( i f (cur3 == NULL)

r e t u r n NULL; DLink<T>* temp = cur3;

cur3 = cur3->next; return(temp->elemp) ;

3

Page 116: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

c u r = cur->prev ; i f ( cu r == NULL)

r e t u r n NULL ; DLinkCT>* temp = cur ; r e t u r n (temp->elemp) ;

3

Ti: GoNext () { cur = cur->next; i f (cur == NULL)

r e t u r n NULL; DLink<T>* temp = cur ; r e t u r n (temp->elemp) ;

3

R e s e t O k u r = f i r s t ; ) Eteset2 () k u r 2 = f i r s t ;) Reset3 () (cur3 = f irst ;) SetDoubleO <

i f ( c u r != NULL) r e t u r n cur->elemp;

r e t u r n NULL;

3 i n t Emptyo C r e t u r n ( f i r s t == NULL) ; )

1;

/ /ent i t y . h

#ifndef UTILITY-H #define UTILITI-H

#def ine MAX 20 # i n d u d e < s t d i o . h >

Page 117: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

c l a s s Value;

c l a s s m e n t i t y ( p u b l i c :

anent i t y () ( 3 " a n e n t i t y 0 1) v i r t u a l i n t m a t ch (anent i ty*) 1) v i r t u a l c h a r * ~ e t T y p e ( ) {) v i r t u a l c h a r *get-name() <) / / f o r t e s t i n g only v i r t u a l c h a r *get-f u l l a d d r ( ) O / / f o r t e s t i n g purpose o n l y f r i e n d i n t o p e r a t or== (const anent i t y & , cons t m e n t i t y â ) {) v i r t u a l Value *callmethod(char *c) (3 v i r t u a l vo id pr in t , i t em() C )

1;

t empla t e<c la s s Type> c l a s s node(

p r i v a t e : Type * i n f o ; node<Type> *next ;

p u b l i c : node<Type> (Type* v , node<Type>* n=NULL) : i n f O (v) , nex t (n) {) / / d e f a u l t v a l u e NULL is added void put-next(node<Type>* n) {next = n;) node<Typa> *get-next () {re tu rn n e x t ; i n t search(Type* t) ; Type* g e t - i n f O 0 ( r e t u r n in f O ; )

i n t match (Type* v) Creturn (*inf O == *v) ; 3 // ( inf o . i s e q u a l (&v) ) ; ) // t h i 3;

templa te c c l a s s Type>

Page 118: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

class c o l l e c t i o n : pub l i c a n e n t i t y {

p r o t e c t e d : nodecType> *head; i n t t o t a l ;

p u b l i c : c o l l e c t i o n ( ) ( t o t a l = O ; h ead = 0 ; )

- c o l l e c t i o n ( ) {dest roy () ; 3 int sizeo (return t o t a l ; ) node<Type> *ret-haad() { r e t u r n (node<Type>*)(void*) head ; ) v i r t u a l boo l is-ernpty() { r e t u r n t o t a l == O ? true : false;)

v i r t u a l boo l member(Type*) ; v i r t u a l vo id remove (Type*) ; v i r t u a l boo l intersects(collection<Type>*); v i r t u a l vo id intersection(collection<Type>*); v i r t u a l boo l every(co l1ec t ion<Type>*) ; v i r t u a l v o i d union-col(collection<Type>*); v i r t u a l boo l atleast(int,collection<Type>*); v i r t u a l boo l atmost ( i n t , col lec t ion<Type>*) ; v i r t u a l boo l j u s t ( i n t , c o l l e c t ion<Type>*) ; v i r t u a l v o i d d i f f e r ( c o l l e c t ion<Type>*) ;

v i r t u a l vo id add(Type* t) ; v i r t u a l vo id d e s t r o y ( ) ; // remove al1 i tems // i n t F ind (cons t Type& t ) C r e t u r n head->search( t ) ; 3

v o i d d i s p l a y ( ) ; //----- v i r t u a l f u n c t i o n s added t o accomodate derived classes ---- v i r t u a l i n t f requency(Type*) {)

t e m p l a t e Kclass Type> class iter,list(

p r i v a t e : nodeCType> *en t ry ; nodeCType> *pos ;

Page 119: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

pub l i c : iter,list(collection<Type> *Is~=NULL){

e n t r y = 1st->ret,head() ; pos = e n t r y ;

>;

nodeCType> *POS () {re turn pos ; 3 void f irst () {pos = e n t r y ; 3 void next 0 {if (pas) pos=POS () ->get-next () ; Type * c u r e n t () {

Type* t= NULL; i f (pos) t= POS 0 +get -inf O () ; r e t u r n t ;

template c c l a s s Type> c l a s s list : p u b l i c collection<Type>{

pub l i c :

l is t () : c o l l e c t ion<Type> () {) ; bool is-empty() ; void remove (Type* v) {del (f indnb (v) ) ; 3 void d e l ( i n t ) ; i n t findnb(Type*); vo id i n s e r t (Type*, i n t ) ; void append(ïype* v) { inse r t (v, t o t a l + i ) ; 3 void add(Type* v) { i n s e r t (v, t o t a l + l ) ; 3 //should have "add" uni f ormly def ined i n der ived c l a s s e s // void modify(const Type&, i n t ) ; i n t frequency(Type*); Type show ( in t ) ; l is t<Type>+ i s u b l i s t ( i n t , i n t ) ; l ist<Type>* s u b l i s t (Type* j, Type* k) {

r e t u r n i s u b l i s t (f indnb(j) , f indnb (k)) ;

Page 120: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

t e m p l a t e <class Type> c l a s s bag : p u b l i c c o l l e c t ion<Type>C

p u b l i c : bag() : c o l l e c t ion<Type> () {) ; v o i d add(Type*) ; int f requency (Type*) ;

p u b l i c :

set () : c o l l e c t ion<Type> () {) vo id add(Type* v l ) ; vo id union-set (set<Type>*) ;

/* ==================================================================== */ t e r n p l a t e < c l a s s Type> i n t node<Type>: :search(Type* t )

< node<Type>* cursor = t h i s ; whi l e ( c u r s o r ) (

i f (cursor->match( t ) )

return 1;

else cursor = c u r s o r - > g e t - n e x t o ;

re turn O;

Page 121: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

template<class Type> bool collection<Type>::member(Type* val)

€ if (!head)

return false; node<Type> *cursor = head; if (cursor->search (val) )

return true ; return false;

template cclass Type> void collection<Type>::add(Type *info)

< node<Type> *cursor = head, *crs = head;

node<Type> *ternp = new node<ïype>(info); if (!head) (

head = ternp;

else

while (cursor->get-next () ) ( cursor = cursor->get-next () ;

> cursor->put-next (temp) ;

t emplat ecclass Type> void collect ion<Type> : : destroy ()

€ node<Type>* tmp ;

Page 122: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

node<Type>* cursor;

iter-list<Type> iter(this); iter-firsto ; cursor = iter . POS () ; while (cursor) (

tmp = iter.POS(); iter . next () ; cursor = iter. POS () ; delete tmp;

> tout << "SET DESTROYED ! !" << endl; head = 0; total = O;

template cclass Type> voicl collection<Type>::intersection(collection~Type> *Ist; <

node<Type> *cm1 = head, *temp, +prev = heîd; // curent one node<Type> *crs2 = 1st->head; int flag = 1; while(crs1) (

if (crs2->search(crsl->get-info())) flag = 0;

if (fia&€ prev->put-next (crs 1->get -next (1 ) ; temp = crsl; crsl = crsl->get-next() ;

if (temp == head) head = crsl ;

delete temp; total--; if (total == 0)

head = 0;

prev = crsl;

Page 123: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient
Page 124: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient
Page 125: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient
Page 126: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient
Page 127: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

if (cnt == js) return true ;

else return false;

ternplat e <class Type> void collection<Type>::display()

{ iter-listCType> iter (this) ; iter.first(); Type* t ;

f o r (; t=iter.current();iter.next()) { tout << "*"; t->print () ; cout << endl;

3.

/*template <class Type> void collectionCType>: :displayint ()

< node<Type> *cursor = head;

while (cursor) { cout CC "*" << cursor->get-infoc) << endl; cursor = cursor->get-nexto;

> >;

*/

Page 128: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

template <class Type> void collection<Type>::remove(Type* info)

(

node<Type> *prev = head, *cursor = head, *temp; int f l a g = 1;

while (cursor && flag) { if ( ! (cursor->search(inf O))) (

prev = cursor; cursor = cursor->get-next();

3 else

prev->put-next (cursor->get-next () ) ; temp = cursor; cursor = cursor->get-next () ; if (temp == head && cursor)

head = cursor; delet e temp ; total--; if (total == 0)

head = 0; f l a g = 0;

3

bool listCType> : : is,empty()

< return total == O ? true : false;

templatecclass Type> void list<Type>: :del ( in t pos) <

node<Type> *prev, *cursor = head;

Page 129: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

if (pos == 1) {

head = cursor->get-next () ; delete cursor; total--;

if (total == 0) head = 0;

3 else

if (pos > 1 && pos <= total)

( for(int i = 1; (i C pos) ; i++) {

prev = cursor; cursor = cursor->get-next() ;

> prev->put-next(cursor->get-next());

delete cursor; total--;

1

t emplat ecclass Type> void list<Type>::insert(Type* val, int pos)

( node<Type> *prev, *cursor = head, *temp = new nodecType>(val); int i ; if (!head) (

head = temp; total++;

> else

if (pos == 1) ( // insert at head temp->put-next(head); head = temp; total++ ;

> else

if (pos > 1)

Page 130: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

f or(i = 1 ; (i < pos) && cursor->get-next () ; i++) {

prev = cursor; cursor = cursor->get-next () ;

> if ( ! cursor->get-next () &à (i < pos))

cursor->put-next (temp) ; else (

temp->put,next (cursor) ;

prev->put-next (temp) ;

3 total++;

3

template<class Type> int list <Type> : : f indnb (Typo+ val)

int cnt = 0; if ( ! head)

return cnt; node<Type> *cursor = head; while(cursor) (

cnt++ ; if (cursor->mat ch (val) )

return cnt ; cursor = cursor->get-next () ;

> return 0;

1;

template<class Type> int list<Type> : : f requency (Type* val) €

node<Type> *cursor = head; int count = 0; if ( ! head)

cout << "List is empty!" << endl;

Page 131: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

else { while (cursor) (

if (cursor->match(val) ) count ++ ;

cursor = cursor->get-next();

return count;

Type list<Type>::show(int pos)

C node<Type> *cursor = head; if ((pos <= total) && (cursor))

{ for (ict i=l; i < pos;i++)

cursor = cursor->get,next 0 ;

return O;

>;

template<class Type> list<Type>* list~Type>::isublist(int min, int max)

{ list<Type> *lst ; 1st = new list<Type>; node<Type> *cursor = head; if ((!head) I I (min > max))

return 1st;

for (int i=l; (i <= max) && cursor; i++)( if ((i >= min) && (i <= max))

1st->append(cursor->get-info());

cursor = cursor->get-next () ;

3

Page 132: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

return 1st;

template cclass Type> void set<Type> : :union-set (set~~ype> *st)

node<Type> *cursorl = head, *prev = head; node<Type> *crs2 = st->head; int flag = 1;

while (crs2) ( while(cursor1 && flag) {

if (cursorl->match(crs2->get-inf O())) flag = 0;

else prev = cursorl;

cursorl = cursorl->get -next () ;

3 if (flag) {

prev->put_next(crs2); total++;

> cursorl = head; prev = head; crs2 = crs2->get,next () ;

flag = 1;

3

template <class Type> void bag<Type> : : add(Type *inf O )

C node<Type> *cursor = head, *crs = head; node<Type> *temp = new node<Type>(info);

Page 133: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

head = temp;

3 e l s e

while (cursor->get-next 0 ) C cursor = cursor->get -nexto ;

1 cursor->put -next (t ernp) ;

> t o t a l + + ;

3;

template <class Type> i n t bag<Type>::frequency(Type* i n f o )

node<Type> *cursor = head; i n t count = 0;

if ( ! head) cout << " L i s t i s empty! " << end l ;

e l s e

while (cursor)

< i f (cursor->match(inf O ) )

cursor = cursor->get-next 0 ; 3

3 return count ;

template <class Type> void s e t <Type> : : add(Type* vl) C

node<Type>* cursor = head;

Page 134: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

head = new node<Type>(vl,head); t o t a l + + ;

3

Page 135: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

Appendix D

Grarnrnar

%( # i n d u d e < s t d i o . h> # i n d u d e "prog . h" # i n c h d e "expr . h" Sinclude "qua1 .hW # i n d u d e " D L i s t . h W

#define YYERROR-VERBOSE #def ine YYDEBUG 1

char error-message C2561; i n t char-count ; i n t l ine-count ; Prog *program;

i n t ~ ~ l e x ( v o i d ) ;

i n t yyerror (char*) ;

char i n t i n t Prog DList<Expr>

i n s t r i n g [64] ; innumb; Col lec t ionType ;

*prog-ptr ; *expr-list-ptr ;

Page 136: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

%t oken %token

%token

%t oken %t oken %token %token

%token

%token %token %token

%t oken

%token %token

%token %token

%token

%token %t oken

Expr

Q u a l i f i e r D L i s t < Q u a l i f i e r > Generat o r

Localdef Hasclassqual

Hasclasswithqual

program e x p r - l i s t

expr q u a l i f ier-list qua l s q u a l i f i e r genera t o r local-def hasclass,qual hasclasswith,qual

c o l l e c t ion-kind

COMMATK SEMICOLONTK PLUSTK MINUSTK MULTTK DIVTK NOTTK LIMPLTK IDENTIFIERTK CONSTANTTK SIZETK SETTK LISTTK BAGTK SOMETK ATLEASTTK JUSTTK ATMOSTTK EVERYTK

Page 137: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

%token

%token %token %token %token %token %token %token %token %token %t oken %token %t oken %t oken %t oken %t oken %token %token %token %t oken %token %token %token %token %token %token

OFTK ASTK L ITERALTK HASCLASSTK WITHTK ANDTK ORTK EQTK GTTK LTTK NOTEQTK GTOREQTK LTOREQTK DEQTK NOTDEQTK THREED OTTK DOTTK DIFFERTK UNIONTK LSQBKTK RSQBKTK LCBKTK RCBKTK LBKTK RBKTK BARTK

HASCLASSTK WITHTK ANDTK ORTK UNOT EqTK GTTK LTTK NOTEQTK GTOREQTK LTOREQTK DEQTK NOTDEQTK

%nonassoc THREEDOTTK %lef t MIMJSTK PLUSTK %lef t MULTTK DIVTK %nonassoc UMIIJUS %left DOTTK

%nonassoc UQUANT

Page 138: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

% l e f t DIFFERTK % l e f t UNI ONTK

/* Gramnar follows */

program : expr-list

yydebug = 1;

$$ = neï Prog($l) ; program = $$;

$ $ - > ~ r i n t S t r u c t 0 ; 3

expr

$$->Insert ($1) ;

3 I expr COMMATK e x p r - l i s t

{ $$ = $3; $$->Insert ($1) ;

expr : expr MULTTK expr

{ $$ = new ~xpr($1,$3,MultOpcode);

3 I expr DIVTK expr

$$ = new Expr ($1, $3, DivOpcode) ;

3 I expr PLUSTK expr

Page 139: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

. n n al 'd O U Pc O Cr' W n

Cr) w

. I) n

a" O U Pc O w' W

2 ri)

Page 140: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

3 I expr NOTEQTK expr

{ $$ = new Expr($l,$3,NotEqOpcode);

3! expr WIONTK expr /* PlusOpcode is+, union, or operations */ €

$$ = new Expr ($1, $3, PlusOpcode) ; 3 I expr DIFFERTK expr /* Minusopcode is -, differ operations */ <

$$ = new Expr($1,$3,MinusOpcode);

) I SOMETK OFTK expr %prec UQUANT {

$$ = new ~ x p r ($3, NULL, SomeOpcode) ;

> I EVERYTK OFTK expr %prec UQUANT {

$$ = new ~xpr($3,NULL,EveryOpcode); 1 f ATLEASTTK expr OFTK expr %prec UQUANT {

$$ = new Expr($2,$4,AtleastOpcode); 3 I JUSTTK expr OFTK expr %prec UQUANT

$$ = new Expr($2,$4,Just0pcode); 1 I ATMDSTTK expr OFTK expr %prec UQUANT

$$ = neu Expr($2,$4,AtmostOpcode); 1 I expr DOTTK expr <

$$ = nev Expr ($1, $3, Dotopcode) ; 3 I expr DOTTK LSQBKTK expr RSQBKTK i

$$ = new Expr ($1 ,$4,DotSBKOpcode) ; 3 I

Page 141: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

LBKTK expr RBKTK {

$$ = $2; 3 I IDENTIFI ERTK

> I LITERALTK

IDENTIFIERTK

{

$$ =

new

new

new

LBKTK expr-list RBKTK

new Expr,methodcall($3,$1);

) I collection-kind LSQBKTK qualifier-list BARTK expr RSQBKTK

{

$$ = nev Expr_query($3,$1,$5); > I collection-kind LCBKTK expr-list RCBKTK

{ $$ = new Expr_special($3. $1) ;

3 1 collection-kind LCBKTK expr THREEDOTTK expr RCBKTK

{ $$ = neu Expr_subrange($1,$3,$5);

1

collection-kind: SETTK <

LISTTK

Page 142: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

$$ = 2; ) 1 BAGTK <

$$ = 3; 3

qualif ier-list : /* empty */ <

$$ = NULL; 3 I quals

< $$ = $1;

3

quals :

qualifier

C $$ = new DList<Qualifier>; $$->Insert ($1) ;

3 I qualifier SEMICULONTK quals i

$$ = $3; $$->Insert ($1) ;

3

qualifier:

generator

< $$ = $1;

3 I local-def

< $$ = $1;

3 I hasclass-qua1

Page 143: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

1 $$ = $1;

1 I hasclasswith-qual

i $$ = $1;

> I expr

generator : IDENTIFIERTK LIMPLTK expr {

$$ = new Generator($l,$3);

>

local-def :

IDENTIFIERTK ASTK expr

{ $$ = new Localdef($l,$3);

3

hasclass,qual :

expr HASCLASSTK expr

< $$ = new Hasclassqual($l , $3) ;

>

expr HASCLASSTK expr WITHTK expr

$$ = new ~asclasswithqual($5,$1,$3);

3

Page 144: AN INTERPRETER FOR OBJECT COMPREHENSION QUERY · PDF fileAN INTERPRETER FOR OBJECT COMPREHENSION QUERY LANGUAGE ... in existing object-oriented query languages such as support of object-orient

int yyerror (char* message)

p r i n t f ("%s\n(%d ,%d) l J ,message, line-count , char-count) ; e x i t (O) ;