Docsity

Object Oriented Extensions - Compilers - Slides | CS 414, Study notes of Computer Science

Partial preview of the text

Download Object Oriented Extensions - Compilers - Slides | CS 414 and more Study notes Computer Science in PDF only on Docsity!

Compilers

CS414-2008S-

Object Oriented Extensions

David Galles

Department of Computer Science

University of San Francisco

Classes

simpleJava classes are equivalent to C structs class myclass {

struct mystruct {

int x;

int x;

int y;

int y;

boolean z;

int z;

What do we need to add to simpleJava classes tomake them true objects?

Adding Methods to Classes

class Point {

int xpos;int ypos;Point(int x, int y) {

xpos = x;ypos = y; } int getX() {

return xpos; } int getY() {

return ypos; } void setX(int x) {

xpos = x; } void setY(int y) {

ypos = y; } }

Adding Methods to Classes

class Rectangle {Point lowerleftpt;Point upperrightpt;Rectangle(Point lowerleft, Point upperright) {

lowerleftpt = lowerleft;upperrightpt = upperright; } int length() {

return upperrightpt.getX() - lowerleftpt.getX(); } int height() {

return upperrightpt.getY() - lowerleftpt.getY(); } int area() {

return length() * height(); } }

Compiler Changes for Methods

Modify Abstract Syntax Tree Modify Semantic Analyzer

Classes will need function environments โ€œThisโ€ pointer defined for methods

Modify Abstract Assembly Generator

Maintain the โ€œthisโ€ pointer

Modifications to AST

What changes are necessary to the AST to addmethods to classes?

Which tree nodes need to be changed? How should they be modified?

Changes to .jj file

void classdef() :{}{

classElems() } void classElems() :{} {

(classElem())* } void

classElem() :

{} {

((( )* ) |

( formals() ) ( | statements() )

Modifications to AST

Change AST to allow method calls x.y.foo()z[3].y[4].bar(x.foo())

Modifications to AST

x.foo(3,4)

MethodCall(foo)

Integer_Literal(4)

Integer_Literal(3)

BaseVaridentifier(x)

Modifications to AST

A[3].foo()

Modifications to AST

B[4].x.foo(5)

Modifications to AST

B[4].x.foo(5)

MethodCall(bar)

Integer_Literal(5)

identifier(B)

ClassVar

identifier(x)

ArrayVar

Integer_Literal(4)

BaseVar

Modifications to AST

For the constructor Integer(int value) {

data = value;

} Create the abstract syntax Integer Integer(int value) {

data = value;return this;

Modifications to AST

Integer(int value) {

data = value;

Create the abstract syntax Integer Integer(int value) {

data = value;return this;

} When will this not work?