// the current object. functioninvocation expression. identifier (expressionlist ) // call of an inner function

Save this PDF as:
 WORD  PNG  TXT  JPG

Size: px
Start display at page:

Download "// the current object. functioninvocation expression. identifier (expressionlist ) // call of an inner function"

Transcription

1 SFU CMPT 379 Compilers Spring 2015 Assignment 4 Assignment due Thursday, April 9, by 11:59pm. For this assignment, you are to expand your Bunting-3 compiler from assignment 3 to handle Bunting-4. Project submission format is the same as for assignment 3 (an archive of your src directory inside a folder named with your sfu username). Bunting-4 is backwards compatible with Bunting-3. All restrictions and specifications from Bunting-3 are still in force, unless specifically noted. I also omit unchanged productions in the Tokens and Grammar sections. If "..." is listed as a possibility for a production, it means "all possibilities for this production from Bunting-3". Language Bunting-4 Grammar: S globaldefinition globaldefinition* main body functiondefinition typedefinition classdefinition classdefinition class identifier ( parameterlist ) classbody classbody { innerdefinition* main body functiondefinition* innerdefinition typedefinition declaration statement break ; continue ; release expressionlist ; expression create user? identifier (expressionlist) // object creation. no immutability annotation create user? mutarraytype ( expression ) [ user? mutannotation? expressionlist ] user? mutannotation? stringconstant copy user? mutannotation? expression [+ user? mutannotation? expression, expression (, expression)* +] this // the current object functioninvocation expression. identifier (expressionlist ) // call of an inner function type identifier // identifier can be a class name 1. Classes Classes are a new type in Bunting Class definitions

2 Classes are limited-functionality objects (they can perform information hiding, but one cannot subclass them or use polymorphism on them). The identifier following the keyword class is the name of the class (i.e. the class name). Class names may not be overloaded (there may not be two classes with the same name, even if the number of parameters are different.) Class names are in the same namespace as all other names, so one cannot declare a class and a global function of the same name The parts of a class The body of the class (body child of classdeclaration) consists of three distinct parts: (1) innerdefinitions. These are definitions for the class variables (fields), and type that will be used inside the class. We sometimes call a field an inner variable and a type declared here as an inner type(def). (2) main block. This is the constructor, called whenever an object of this class is created. (3) functiondefinitions. We call these inner functions. The class definition s parameterlist lists the parameters to be used when a create is issued for this class. They are to be declared as immutable variables in a new scope placed on the class declaration node. That is, they may be overridden in the main body scope (or in any nested scopes). The record for the class should include all parameters and inner variables, but not local variables for the main block or any functions. To implement this, creation parameters should be passed on the frame stack to the constructor but then copied to the class s record at the start of that constructor Class visibility All classes (and inner functions) are visible throughout the program, even before their definition. Collect the names and creation code signatures in a separate pass as was done for function names. You may combine this pass with the function-name collector, or make a separate pass Variable and inner function visibility Inner variables and inner types are visible only within the class definition, and only to code that is past the point of declaration of these variables or types. This is like java private fields. All inner functions are visible throughout the program (like java public ), even before their definition. Variables and types declared in a scope nested anywhere inside the class body are visible only within that nested scope. This includes variables and parameters declared inside the inner functiondeclarations Class creation The only way to create a class instance is with a class creation expression: create user? identifier (expressionlist) The identifier must be a class name. The expressionlist must be type-compatible with the corresponding class definition s parameterlist. This creation expression allocates memory for the class s record and runs the class s main block with the given arguments. The values of all creation parameters and inner variables are kept in the record until the record is released. The visibility of inner variables is discussed above. We will simply use the class name (identifier in the creation expression) as the indicator for the type of object generated by the creation. For example, in imm chessie := create Cat(9);

3 the type of the variable chessie is Cat Class records A class creation expression results in the allocation of a new record (block of memory obtained from the memory manager). The record for a class type Name has the following format: Type identifier (4 bytes) Status (4 bytes) Variables for instance of Name (size of the scope on Name s definition) The type identifier for a class is an integer that identifies the class type (i.e. the class). Start allocating class type identifiers with the integer 128. That is, give the integer 128 to the first class declared in the program, give 129 to the next class declared, etc. The entire record takes 8 + size-of-name s-definition-scope bytes. Note that the definition scope size includes the sizes of any creation parameters and inner variables. The variables in the main block or in inner functions are only visible while that block or function is executing, so you should use a stack frame for them. Use a subscope for the scope attached to the class s body node; it will (as subscopes do) use its parent s allocator, which in this case is the allocator given to the class definition node s scope (which is where I said to place the creation parameters). Allocation of offsets for variables inside a class definition scope is done in a positive sense, starting with the offset 8. Thus, if a class has a parameter x and inner variables f and g, with x being an integer (4 bytes) and both f and g being floats (8 bytes apiece), x will get offset 8, f will get offset 12, and g will get offset 20. You may have to create a new type of scope (with the proper MemoryAccessMethod) to handle these class definition scopes. The status flags used in arrays are also defined for classes: bit 0 (mask 1) contains the immutability status of the class, which is currently unused, so set it to zero. This bit is unused because the class provides immutability designation separately for each variable it contains. Bit 1 (mask 2) contains the subtype-is-reference status, which is also not used for classes (so set it to zero). (As we shall see later, classes have a more complex method for handling subelements that are reference variables. Bit 2 (mask 4) contains the user-managed status, which is set to 1 if the creation expression contains the optional keyword user, and set to 0 otherwise Class variables If Name is the name of a class, then a variable of type Name is a pointer to a class record; it thus occupies 4 bytes. It does not occupy 8 + size-of-name s-body-scope bytes. In other words, class types are all reference (a.k.a. pointer) types. Class variables obey semantics much like java objects (which are themselves reference types): Class variables declared with imm do not change their pointer; however, the contents of the record they point at may change. Imagine that the setcolor call in the following sets a variable inside the Cow s record: imm bessie := create Cow(1); call bessie.setcolor(4); This is valid Bunting-4 and results in bessie pointing at a record that now has color 4. Assignment or initialization of classes with other classes is simply a pointer copy. imm bessie := create Cow(2); imm freddie := bessie; is valid Bunting-4 and results in bessie and freddie being two pointers to the same record. If this is followed by

4 call bessie.setcolor(7); then not only will bessie s color be 7, but freddie s color will, as well. Class variables declared with mut may change their pointer as well as the record contents. mut bessie := create Cow(3); call bessie.setcolor(2); imm nextcolor := 15; imm tempcow := create user Cow; call tempcow.setcolor(nextcolor); mutate bessie := tempcow; is valid Bunting-4. However, class variables may not be assigned a class of a different type. imm bessie := create Cow(4); imm jessie := create Unicorn(5); mut pet := bessie; mutate pet := jessie; is not valid Bunting-4. The mut declaration sets pet s type as Cow, and the mutate tries to update it with a Unicorn, so this should generate a typechecking error Class printing If an expression in a print statement is of class type, then Bunting-4 will print the name of the class. class main { imm buzz := create Bee; print a& buzz& c& nl&; print a, buzz, c& nl&; Will produce: abeec a Bee c 2. Class types Each class definition in a Bunting-4 program creates a new type, known as a class type. You will need to create a new subclass of Type to handle class types, as you did for array types. Each class definition you encounter will lead to the creation of a new instance of ClassType (or whatever you call it). Each class type has a name, which is the name given in the class definition. No two class types (or two class definitions) may have the same name. Like arrays, classes are reference types (a.k.a. pointer types): the value of a class variable is a pointer to the class record. The user can define types based on class types (just like every other type).

5 3. The expression this The lexeme this is now a keyword. When used as an expression, it denotes the instance of the class that contains the function (or creation code) that is currently running. Note that it can not be used explicitly by the Bunting programmer for accessing variables in a class, but it can be used as a function argument or as a qualifier in a functioninvocation. To implement this, we will use a technique known as lambda lifting. In this technique, the compiler adds a parameter to each function (including the constructor) and passes in the correct value of this as the argument. In Bunting, we will put this new parameter at the end of the parameter list. For example, in: class Sheep(int numbaas) { mut wool := 2; main { def int makenoise(int n) { imm scaledwool = 3 * wool; The inner function makenoise is treated as if it were declared: def int makenoise(int n, Sheep thisptr) { Then, in the following sequence: imm garry := create Sheep(21); imm x := garry.makenoise(14); The second statement is treated as: imm x := Sheep.makeNoise(14, garry); Here Sheep.makenoise is not legal Bunting, it just indicates which makenoise to call. In general, expression.functionname(args) is treated as (Type of expression).functionname(args, expression) The last argument to a function is always at offset 0 from the frame pointer, so we can rely on the this pointer being located at the frame pointer. If a inner function accesses any variables or creation parameters of the class, it uses the this pointer to access the correct instance s version of the variable. In the example above, the statement imm scaledwool = 3 * wool; uses the variable wool from the creation code of the class Sheep, and so this can be thought of as imm scaledwool = 3 * thisptr.wool; (but note that the syntax thisptr.wool is not legal Bunting-4.) No explicit conversion to this form is necessary, however. You can simply create a new memory access method that uses double indirection from the frame pointer to calculate the base address. The code for this looks like: PushD $FRAME_POINTER LoadI

6 LoadI (the two LoadI s give it double indirection). The first LoadI gets the value of the frame pointer, and the second LoadI get the value of thisptr. Use your new memory access method for variables declared in the class body scope, and in nested scopes that are not within functions. this is not a targetable expression. Translate the expression this as thisptr (i.e., the last argument); in other words, address code for this is the first four instructions of the sequence above, or: PushD $FRAME_POINTER LoadI PushI 4 Add The type for this is the class type for the class that encloses it. 4. Handling create, the constructor, and its parameters The main block in a class definition can be thought of as a function that modifies the class being created, but has no return statements. We can pass the record for the class being created to the creation code as its this pointer, if we allocate the record before the call. Then the call can return the this pointer using the usual return mechanism, providing the value that the creation expression expects (the pointer to the new class). So implement create for class instances as a modified function call. This can be done (for example, for create Horse(expr1, expr2) ) by: 1) calculating the argument expressions, in order, and pushing them on the frame stack, 2) allocating a record (of size 8+Horse s-scope-size) and pushing the pointer to that record on the frame stack, so that it becomes the this-pointer argument to the constructor function, 3) calling the constructor, which should return its this pointer 4) performing the usual caller s-exit handshaking Note that steps 1 to 3 are just a modified version of the caller s-function-call handshaking. The constructor is made by turning the main block of the class into a function. It should: 1) do the usual callee-enter handshake 2) copy the parameters (not including the thisptr) from the frame stack into the record (thisptr) at the proper parameter offsets. 3) execute the main block s body code. 4) return the this pointer, 5) do the usual callee-exit handshake. Since the creation parameters are available to all functions nested in the class, we do step 2) above to ensure that these arguments are stored in the record for the class. This means that during semantic analysis we must allocate space for them in both the parameter scope for the function call to the main body, and in the class scope that gets made into the class record. The parameter scope need not enclose the class body scope, as these named variables can be referenced as part of the class record. Thus, we may place the parameter scope at any convenient node in the AST, perhaps at a ParameterListNode or something similar. Then, you can start a class scope (whatever you decide to call it) at the ClassDeclaration node, and enter the parameter definitions into both the parameter scope and the class scope. The class body scope then can be a subscope placed on the class s Body node.

7 The above is only one method that works; you are free to use others if you so desire. For instance, you could essentially return void from the creation code and use a saved value of the allocated record as the value for the creation expression. Or maybe you could allocate the new class record inside the creation-code call, in the callee-entrance handshake. 5. Class attribute tables Bunting-4 requires us to have information about each class type available at runtime. The two pieces of information we need are (1) a string name for the class (to use when printing the class), and (2) a list of all offsets in the class that contain a reference variable. The easiest way to do this is to have either one combined table (each element being a string pointer followed by a list pointer), or to have one table for the string pointers, and one for the list pointers. Either way is fine, but the combined table requires an extra offset to access (say) the list pointers. I ll give a few details of the separate-table idea. First, somewhere in RunTime, we need to place labelled strings in data memory, one for each class type. Suppose your program has three class types: Cat, Dog, and Rabbit, which have been allocated the typecodes 128, 129, and 130, respectively. Then you might issue the following ASM instructions to allocate the strings: DLabel $class-cat-string DataS Cat DLabel $class-dog-string DataS Dog DLabel $class-rabbit-string DataS Rabbit This would be done from a loop that loops over the defined class types, issuing a DLabel and and DataS for each. To create the table, you would issue something like: DLabel $class-names-table DataD $class-cat-string DataD $class-dog-string DataD $class-rabbit-string Then, to get the pointer to the name of the type of a record, take the record s typecode, and calculate the address $class-names-table + (typecode-128)*4 Where the 4 is the size of an entry in the table. This address contains the desired pointer. The idea for the list pointers is similar, where each class s list could be a negative-number terminated array of integers. For example, if Cat s list were to contain the numbers 4, 12, and 20, you d want something like: DLabel $class-cat-referenceoffsets DataI 4 DataI 12 DataI 20 DataI -1 We use a negative number here rather than zero because zero is a valid element for the offset list. You can use any other method you please to store these lists; you could for instance prefix the list with the number of elements rather than having an end sentinel: DLabel $class-cat-referenceoffsets

8 DataI 3 DataI 4 DataI 12 DataI Function invocations In the function invocation expression. identifier (expressionlist ) the expression must have a class type SomeClass that is a defined class, and identifier must be a inner function in SomeClass, with the argument types in the invocation matching the parameter types in the inner function. As stated above, we lambda-lift this invocation, treating it as if it were identifier (expressionlist, expression ) in order to implement the this pointer. Any function invocation without a member operator identifier ( expressionlist ) is treated as if it was a call to a inner function on this, viz.: this.identifier ( expressionlist ) and then lambda-lifting is applied. 7. The release statement, the user annotation, and hard release We now can use the keyword user to annotate any expression that creates a record. Using this notation will set the user-managed status bit of the created record to 1; otherwise it will be set to 0. The only way to release a record with the user-managed bit set is by having that record as one of the expressions in the release statement: release expressionlist ; Any expression in this immediately subjected to hard release (or explicit release). This is exactly like soft release, except that the user-managed bit is not checked in hard release, and the recursive releasing is hard. The recursive release is a little harder to implement, though. It involves going through the class s list of offsets that contain reference variables, and releasing each. Pseudocode for the release operation (hard or soft) becomes: if(classid == 0) done; if(classid == 9) { if(subtype-is-reference) { loop through array elements, releasing each

9 assert classid >= 128; classindex = classid-128; offsettable = offsettables[classindex]; for each offset in offsettable { release the element at that offset Aside from this complication in the recursion, the release mechanism for class records is the same as they were for arrays. Most of the release code that you already have should work with class records. 8. Break and continue statements These statements are only allowed inside the body of a while or for loop. This includes nested inside statements in the loop body. A break statement immediately jumps to the code immediately after the closest (most deeply nested) loop that contains it. A continue immediately jumps to the code for checking the condition on the closest loop. 9. Operator precedence The precedence of operators is Highest precedence (prefix unary operators are right-associative) parentheses populated array creation empty array creation class creation function invocation concatenation inner function access, array indexing not, copy, length, stringprinting casting : multiplicative operators * / additive operators + ( ) [ ] create[ ]( ) create ( ) ( ) [+ +]. [ ]! copy length $ comparisons < > <= >= ==!= and && Lowest precedence or These are all left-associative operators, except as noted.

The Decaf Language. 1 Lexical considerations

The Decaf Language. 1 Lexical considerations The Decaf Language In this course, we will write a compiler for a simple object-oriented programming language called Decaf. Decaf is a strongly-typed, object-oriented language with support for inheritance

More information

Lexical Considerations

Lexical Considerations Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

More information

A Short Summary of Javali

A Short Summary of Javali A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler

More information

The Decaf language 1

The Decaf language 1 The Decaf language 1 In this course, we will write a compiler for a simple object-oriented programming language called Decaf. Decaf is a strongly-typed, object-oriented language with support for inheritance

More information

Semantic actions for declarations and expressions

Semantic actions for declarations and expressions Semantic actions for declarations and expressions Semantic actions Semantic actions are routines called as productions (or parts of productions) are recognized Actions work together to build up intermediate

More information

Programming Languages Third Edition. Chapter 7 Basic Semantics

Programming Languages Third Edition. Chapter 7 Basic Semantics Programming Languages Third Edition Chapter 7 Basic Semantics Objectives Understand attributes, binding, and semantic functions Understand declarations, blocks, and scope Learn how to construct a symbol

More information

CSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem:

CSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem: Expression evaluation CSE 504 Order of evaluation For the abstract syntax tree + + 5 Expression Evaluation, Runtime Environments + + x 3 2 4 the equivalent expression is (x + 3) + (2 + 4) + 5 1 2 (. Contd

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Today's Topics. CISC 458 Winter J.R. Cordy

Today's Topics. CISC 458 Winter J.R. Cordy Today's Topics Last Time Semantics - the meaning of program structures Stack model of expression evaluation, the Expression Stack (ES) Stack model of automatic storage, the Run Stack (RS) Today Managing

More information

Lecture 16: Static Semantics Overview 1

Lecture 16: Static Semantics Overview 1 Lecture 16: Static Semantics Overview 1 Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing Produces trees Detects & eliminates ill-formed parse trees Static semantic analysis

More information

Procedure and Object- Oriented Abstraction

Procedure and Object- Oriented Abstraction Procedure and Object- Oriented Abstraction Scope and storage management cs5363 1 Procedure abstractions Procedures are fundamental programming abstractions They are used to support dynamically nested blocks

More information

Java Primer 1: Types, Classes and Operators

Java Primer 1: Types, Classes and Operators Java Primer 1 3/18/14 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M. H. Goldwasser, Wiley, 2014 Java Primer 1: Types,

More information

Static Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1

Static Semantics. Lecture 15. (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1 Static Semantics Lecture 15 (Notes by P. N. Hilfinger and R. Bodik) 2/29/08 Prof. Hilfinger, CS164 Lecture 15 1 Current Status Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Object-Oriented Programming

Object-Oriented Programming Object-Oriented Programming 1. What is object-oriented programming (OOP)? OOP is a technique to develop logical modules, such as classes that contain properties, methods, fields, and events. An object

More information

CS143 Handout 03 Summer 2012 June 27, 2012 Decaf Specification

CS143 Handout 03 Summer 2012 June 27, 2012 Decaf Specification CS143 Handout 03 Summer 2012 June 27, 2012 Decaf Specification Written by Julie Zelenski and updated by Jerry Cain and Keith Schwarz. In this course, we will write a compiler for a simple object oriented

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Tokens, Expressions and Control Structures

Tokens, Expressions and Control Structures 3 Tokens, Expressions and Control Structures Tokens Keywords Identifiers Data types User-defined types Derived types Symbolic constants Declaration of variables Initialization Reference variables Type

More information

Decaf Language Reference

Decaf Language Reference Decaf Language Reference Mike Lam, James Madison University Fall 2016 1 Introduction Decaf is an imperative language similar to Java or C, but is greatly simplified compared to those languages. It will

More information

(Not Quite) Minijava

(Not Quite) Minijava (Not Quite) Minijava CMCS22620, Spring 2004 April 5, 2004 1 Syntax program mainclass classdecl mainclass class identifier { public static void main ( String [] identifier ) block } classdecl class identifier

More information

QUIZ. What are 3 differences between C and C++ const variables?

QUIZ. What are 3 differences between C and C++ const variables? QUIZ What are 3 differences between C and C++ const variables? Solution QUIZ Source: http://stackoverflow.com/questions/17349387/scope-of-macros-in-c Solution The C/C++ preprocessor substitutes mechanically,

More information

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include: Declarations Based on slides from K. N. King Declaration Syntax General form of a declaration: declaration-specifiers declarators ; Declaration specifiers describe the properties of the variables or functions

More information

Properties of an identifier (and the object it represents) may be set at

Properties of an identifier (and the object it represents) may be set at Properties of an identifier (and the object it represents) may be set at Compile-time These are static properties as they do not change during execution. Examples include the type of a variable, the value

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2

CS321 Languages and Compiler Design I. Winter 2012 Lecture 2 CS321 Languages and Compiler Design I Winter 2012 Lecture 2 1 A (RE-)INTRODUCTION TO JAVA FOR C++/C PROGRAMMERS Why Java? Developed by Sun Microsystems (now Oracle) beginning in 1995. Conceived as a better,

More information

SMURF Language Reference Manual Serial MUsic Represented as Functions

SMURF Language Reference Manual Serial MUsic Represented as Functions SMURF Language Reference Manual Serial MUsic Represented as Functions Richard Townsend, Lianne Lairmore, Lindsay Neubauer, Van Bui, Kuangya Zhai {rt2515, lel2143, lan2135, vb2363, kz2219}@columbia.edu

More information

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements Programming Languages Third Edition Chapter 9 Control I Expressions and Statements Objectives Understand expressions Understand conditional statements and guards Understand loops and variation on WHILE

More information

Run-time Environments - 2

Run-time Environments - 2 Run-time Environments - 2 Y.N. Srikant Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler Design Outline of the Lecture n What is run-time

More information

A declaration may appear wherever a statement or expression is allowed. Limited scopes enhance readability.

A declaration may appear wherever a statement or expression is allowed. Limited scopes enhance readability. Scope vs. Lifetime It is usually required that the lifetime of a run-time object at least cover the scope of the identifier. That is, whenever you can access an identifier, the run-time object it denotes

More information

CS Programming In C

CS Programming In C CS 24000 - Programming In C Week Two: Basic C Program Organization and Data Types Zhiyuan Li Department of Computer Science Purdue University, USA 2 int main() { } return 0; The Simplest C Program C programs

More information

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון Overriding עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Roadmap A method in a child class overrides a method in the parent class if it has the same name and type signature: Parent void method(int,float)

More information

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class. 1. What is C#? C# (pronounced "C sharp") is a simple, modern, object oriented, and type safe programming language. It will immediately be familiar to C and C++ programmers. C# combines the high productivity

More information

Table of Contents Preface Bare Necessities... 17

Table of Contents Preface Bare Necessities... 17 Table of Contents Preface... 13 What this book is about?... 13 Who is this book for?... 14 What to read next?... 14 Personages... 14 Style conventions... 15 More information... 15 Bare Necessities... 17

More information

Brief Summary of Java

Brief Summary of Java Brief Summary of Java Java programs are compiled into an intermediate format, known as bytecode, and then run through an interpreter that executes in a Java Virtual Machine (JVM). The basic syntax of Java

More information

Inheritance, Polymorphism and the Object Memory Model

Inheritance, Polymorphism and the Object Memory Model Inheritance, Polymorphism and the Object Memory Model 1 how objects are stored in memory at runtime? compiler - operations such as access to a member of an object are compiled runtime - implementation

More information

Scope, Functions, and Storage Management

Scope, Functions, and Storage Management Scope, Functions, and Storage Management Implementing Functions and Blocks cs3723 1 Simplified Machine Model (Compare To List Abstract Machine) Registers Code Data Program Counter (current instruction)

More information

Glossary. For Introduction to Programming Using Python By Y. Daniel Liang

Glossary. For Introduction to Programming Using Python By Y. Daniel Liang Chapter 1 Glossary For Introduction to Programming Using Python By Y. Daniel Liang.py Python script file extension name. assembler A software used to translate assemblylanguage programs into machine code.

More information

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

More information

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis?

Anatomy of a Compiler. Overview of Semantic Analysis. The Compiler So Far. Why a Separate Semantic Analysis? Anatomy of a Compiler Program (character stream) Lexical Analyzer (Scanner) Syntax Analyzer (Parser) Semantic Analysis Parse Tree Intermediate Code Generator Intermediate Code Optimizer Code Generator

More information

COMP 181. Agenda. Midterm topics. Today: type checking. Purpose of types. Type errors. Type checking

COMP 181. Agenda. Midterm topics. Today: type checking. Purpose of types. Type errors. Type checking Agenda COMP 181 Type checking October 21, 2009 Next week OOPSLA: Object-oriented Programming Systems Languages and Applications One of the top PL conferences Monday (Oct 26 th ) In-class midterm Review

More information

YOLOP Language Reference Manual

YOLOP Language Reference Manual YOLOP Language Reference Manual Sasha McIntosh, Jonathan Liu & Lisa Li sam2270, jl3516 and ll2768 1. Introduction YOLOP (Your Octothorpean Language for Optical Processing) is an image manipulation language

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

CS 321 Homework 4 due 1:30pm, Thursday, March 15, 2012 This homework specification is copyright by Andrew Tolmach. All rights reserved.

CS 321 Homework 4 due 1:30pm, Thursday, March 15, 2012 This homework specification is copyright by Andrew Tolmach. All rights reserved. CS 321 Homework 4 due 1:30pm, Thursday, March 15, 2012 This homework specification is copyright 2002-2012 by Andrew Tolmach. All rights reserved. Typechecking In this assignment, you will build a type-checker

More information

SOOL, a Simple Object-Oriented Language

SOOL, a Simple Object-Oriented Language 10 SOOL, a Simple Object-Oriented Language SOOL In the last two chapters we introduced the formal notation necessary in order to specify programming languages. Now we are ready to present the formal specification

More information

Type Checking and Type Equality

Type Checking and Type Equality Type Checking and Type Equality Type systems are the biggest point of variation across programming languages. Even languages that look similar are often greatly different when it comes to their type systems.

More information

CSCI312 Principles of Programming Languages!

CSCI312 Principles of Programming Languages! CSCI312 Principles of Programming Languages! Scope Xu Liu ! 4.1 Syntactic Issues! 4.2 Variables! 4.3 Scope! 4.4 Symbol Table! 4.5 Resolving References! 4.6 Dynamic Scoping! 4.7 Visibility! 4.8 Overloading!

More information

Generating Code for Assignment Statements back to work. Comp 412 COMP 412 FALL Chapters 4, 6 & 7 in EaC2e. source code. IR IR target.

Generating Code for Assignment Statements back to work. Comp 412 COMP 412 FALL Chapters 4, 6 & 7 in EaC2e. source code. IR IR target. COMP 412 FALL 2017 Generating Code for Assignment Statements back to work Comp 412 source code IR IR target Front End Optimizer Back End code Copyright 2017, Keith D. Cooper & Linda Torczon, all rights

More information

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Compiler Design

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Compiler Design i About the Tutorial A compiler translates the codes written in one language to some other language without changing the meaning of the program. It is also expected that a compiler should make the target

More information

by Pearson Education, Inc. All Rights Reserved.

by Pearson Education, Inc. All Rights Reserved. Let s improve the bubble sort program of Fig. 6.15 to use two functions bubblesort and swap. Function bubblesort sorts the array. It calls function swap (line 51) to exchange the array elements array[j]

More information

Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus

Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus Types Type checking What is a type? The notion varies from language to language Consensus A set of values A set of operations on those values Classes are one instantiation of the modern notion of type

More information

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object

More information

Run Time Environment. Procedure Abstraction. The Procedure as a Control Abstraction. The Procedure as a Control Abstraction

Run Time Environment. Procedure Abstraction. The Procedure as a Control Abstraction. The Procedure as a Control Abstraction Procedure Abstraction Run Time Environment Records Procedure Linkage Name Translation and Variable Access Copyright 2010, Pedro C. Diniz, all rights reserved. Students enrolled in the Compilers class at

More information

Parser Tools: lex and yacc-style Parsing

Parser Tools: lex and yacc-style Parsing Parser Tools: lex and yacc-style Parsing Version 6.11.0.6 Scott Owens January 6, 2018 This documentation assumes familiarity with lex and yacc style lexer and parser generators. 1 Contents 1 Lexers 3 1.1

More information

Procedure and Function Calls, Part II. Comp 412 COMP 412 FALL Chapter 6 in EaC2e. target code. source code Front End Optimizer Back End

Procedure and Function Calls, Part II. Comp 412 COMP 412 FALL Chapter 6 in EaC2e. target code. source code Front End Optimizer Back End COMP 412 FALL 2017 Procedure and Function Calls, Part II Comp 412 source code IR Front End Optimizer Back End IR target code Copyright 2017, Keith D. Cooper & Linda Torczon, all rights reserved. Students

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR) Object Oriented Programming Part II of II Steve Ryder Session 8352 JSR Systems (JSR) sryder@jsrsys.com New Terms in this Section API Access Modifier Package Constructor 2 Polymorphism Three steps of object

More information

Overloading, Type Classes, and Algebraic Datatypes

Overloading, Type Classes, and Algebraic Datatypes Overloading, Type Classes, and Algebraic Datatypes Delivered by Michael Pellauer Arvind Computer Science and Artificial Intelligence Laboratory M.I.T. September 28, 2006 September 28, 2006 http://www.csg.csail.mit.edu/6.827

More information

Project 6 Due 11:59:59pm Thu, Dec 10, 2015

Project 6 Due 11:59:59pm Thu, Dec 10, 2015 Project 6 Due 11:59:59pm Thu, Dec 10, 2015 Updates None yet. Introduction In this project, you will add a static type checking system to the Rube programming language. Recall the formal syntax for Rube

More information

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program: Welcome Back CSCI 262 Data Structures 2 - Review What you learned in CSCI 261 (or equivalent): Variables Types Arrays Expressions Conditionals Branches & Loops Functions Recursion Classes & Objects Streams

More information

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

More information

This section provides some reminders and some terminology with which you might not be familiar.

This section provides some reminders and some terminology with which you might not be familiar. Chapter 3: Functions 3.1 Introduction The previous chapter assumed that all of your Bali code would be written inside a sole main function. But, as you have learned from previous programming courses, modularizing

More information

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26 COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.

More information

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. OOPs Concepts 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8. Type Casting Let us discuss them in detail: 1. Data Hiding: Every

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

CS664 Compiler Theory and Design LIU 1 of 16 ANTLR. Christopher League* 17 February Figure 1: ANTLR plugin installer

CS664 Compiler Theory and Design LIU 1 of 16 ANTLR. Christopher League* 17 February Figure 1: ANTLR plugin installer CS664 Compiler Theory and Design LIU 1 of 16 ANTLR Christopher League* 17 February 2016 ANTLR is a parser generator. There are other similar tools, such as yacc, flex, bison, etc. We ll be using ANTLR

More information

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Topics Covered Thus Far CMSC 330: Organization of Programming Languages Topics Covered Thus Far CMSC 330: Organization of Programming Languages Names & Binding, Type Systems Programming languages Ruby Ocaml Lambda calculus Syntax specification Regular expressions Context free

More information

Informatica 3 Syntax and Semantics

Informatica 3 Syntax and Semantics Informatica 3 Syntax and Semantics Marcello Restelli 9/15/07 Laurea in Ingegneria Informatica Politecnico di Milano Introduction Introduction to the concepts of syntax and semantics Binding Variables Routines

More information

Compilers. 8. Run-time Support. Laszlo Böszörmenyi Compilers Run-time - 1

Compilers. 8. Run-time Support. Laszlo Böszörmenyi Compilers Run-time - 1 Compilers 8. Run-time Support Laszlo Böszörmenyi Compilers Run-time - 1 Run-Time Environment A compiler needs an abstract model of the runtime environment of the compiled code It must generate code for

More information

MUTABLE LISTS AND DICTIONARIES 4

MUTABLE LISTS AND DICTIONARIES 4 MUTABLE LISTS AND DICTIONARIES 4 COMPUTER SCIENCE 61A Sept. 24, 2012 1 Lists Lists are similar to tuples: the order of the data matters, their indices start at 0. The big difference is that lists are mutable

More information

WA1278 Introduction to Java Using Eclipse

WA1278 Introduction to Java Using Eclipse Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA1278 Introduction to Java Using Eclipse This course introduces the Java

More information

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018 Java + OOP CSC207 Winter 2018 1 Why OOP? Modularity: code can be written and maintained separately, and easily passed around the system Information-hiding: internal representation hidden from the outside

More information

Building Compilers with Phoenix

Building Compilers with Phoenix Building Compilers with Phoenix Parser Generators: ANTLR History of ANTLR ANother Tool for Language Recognition Terence Parr's dissertation: Obtaining Practical Variants of LL(k) and LR(k) for k > 1 PCCTS:

More information

FRAC: Language Reference Manual

FRAC: Language Reference Manual FRAC: Language Reference Manual Justin Chiang jc4127 Kunal Kamath kak2211 Calvin Li ctl2124 Anne Zhang az2350 1. Introduction FRAC is a domain-specific programming language that enables the programmer

More information

Summary: Direct Code Generation

Summary: Direct Code Generation Summary: Direct Code Generation 1 Direct Code Generation Code generation involves the generation of the target representation (object code) from the annotated parse tree (or Abstract Syntactic Tree, AST)

More information

Names and Types. standard hue names. Dr. Philip Cannata 1

Names and Types. standard hue names. Dr. Philip Cannata 1 Names and Types standard hue names Dr. Philip Cannata 1 10 High Level Languages This Course Jython in Java Java (Object Oriented) ACL2 (Propositional Induction) Relation Algorithmic Information Theory

More information

Variables. Data Types.

Variables. Data Types. Variables. Data Types. The usefulness of the "Hello World" programs shown in the previous section is quite questionable. We had to write several lines of code, compile them, and then execute the resulting

More information

L-System Fractal Generator: Language Reference Manual

L-System Fractal Generator: Language Reference Manual L-System Fractal Generator: Language Reference Manual Michael Eng, Jervis Muindi, Timothy Sun Contents 1 Program Definition 3 2 Lexical Conventions 3 2.1 Comments...............................................

More information

Chapter 4. Defining Classes I

Chapter 4. Defining Classes I Chapter 4 Defining Classes I Introduction Classes are the most important language feature that make object oriented programming (OOP) possible Programming in Java consists of dfii defining a number of

More information

Chapter 9. Subprograms

Chapter 9. Subprograms Chapter 9 Subprograms Chapter 9 Topics Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments Parameter-Passing Methods Parameters That Are Subprograms Calling

More information

Nested Classes in Java. Slides by: Alon Mishne Edited by: Eran Gilad, Eyal Moscovici April 2013

Nested Classes in Java. Slides by: Alon Mishne Edited by: Eran Gilad, Eyal Moscovici April 2013 Nested Classes in Java Slides by: Alon Mishne Edited by: Eran Gilad, Eyal Moscovici April 2013 1 In This Tutorial Explanation of the nested class concept. Access modifiers and nested classes. The types

More information

Compiler Passes. Semantic Analysis. Semantic Analysis/Checking. Symbol Tables. An Example

Compiler Passes. Semantic Analysis. Semantic Analysis/Checking. Symbol Tables. An Example Semantic Analysis Having figured out the program s structure, now figure out what it means Compiler Passes Analysis of input program (front-end) character stream Lexical Analysis token stream Syntactic

More information

Implementing Subprograms

Implementing Subprograms 1 Implementing Subprograms CS 315 Programming Languages Pinar Duygulu Bilkent University CS315 Programming Languages Pinar Duygulu The General Semantics of Calls and Returns 2 The subprogram call and return

More information

Run Time Environment. Activation Records Procedure Linkage Name Translation and Variable Access

Run Time Environment. Activation Records Procedure Linkage Name Translation and Variable Access Run Time Environment Activation Records Procedure Linkage Name Translation and Variable Access Copyright 2015, Pedro C. Diniz, all rights reserved. Students enrolled in the Compilers class at the University

More information

[0569] p 0318 garbage

[0569] p 0318 garbage A Pointer is a variable which contains the address of another variable. Declaration syntax: Pointer_type *pointer_name; This declaration will create a pointer of the pointer_name which will point to the

More information

Values and Variables 1 / 30

Values and Variables 1 / 30 Values and Variables 1 / 30 Values 2 / 30 Computing Computing is any purposeful activity that marries the representation of some dynamic domain with the representation of some dynamic machine that provides

More information

CSE 504: Compiler Design. Runtime Environments

CSE 504: Compiler Design. Runtime Environments Runtime Environments Pradipta De pradipta.de@sunykorea.ac.kr Current Topic Procedure Abstractions Mechanisms to manage procedures and procedure calls from compiler s perspective Runtime Environment Choices

More information

Object-oriented programming in...

Object-oriented programming in... Programming Languages Week 12 Object-oriented programming in... College of Information Science and Engineering Ritsumeikan University plan this week intro to Java advantages and disadvantages language

More information

7.1 Optional Parameters

7.1 Optional Parameters Chapter 7: C++ Bells and Whistles A number of C++ features are introduced in this chapter: default parameters, const class members, and operator extensions. 7.1 Optional Parameters Purpose and Rules. Default

More information

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018 Java + OOP CSC207 Winter 2018 1 Why OOP? Modularity: code can be written and maintained separately, and easily passed around the system Information-hiding: internal representation hidden from the outside

More information

HAWK Language Reference Manual

HAWK Language Reference Manual HAWK Language Reference Manual HTML is All We Know Created By: Graham Gobieski, George Yu, Ethan Benjamin, Justin Chang, Jon Adelson 0. Contents 1 Introduction 2 Lexical Convetions 2.1 Tokens 2.2 Comments

More information

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8 Epic Test Review 1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4 Write a line of code that outputs the phase Hello World to the console without creating a new line character. System.out.print(

More information