Logo

Cool Language Compiler Example – Compilers courses

Compiler COOL Lex Teaching Material Yacc

2 minutes

coolc is a limited class use COOL (Classroom Object Oriented Language) compiler written in C using LEX and YACC. coolc will perform an almost complete static type-check on the given file and generate the intermediate code in a three-address language for a limited subset of the COOL constructs. The three-address code will then be interpreted by the built-in interpreter and the output displayed to the user.

coolc doesn’t fully support all the COOL language constructs. coolc main features are centered around the developing of the dispatch construct of COOL:
ID.ID():void

Therefore, briefly, coolc is able to handle:

  • definition of classes without inheritance
  • definition of attributes of various types in classes
  • definition of methods in classes
  • definition of dispatching methods in methods body without parameters and without a return value

To make the output of the generated programs more readable and explicit an additional command “print” has been added to the COOL language. This command will simply display on screen a defined constant string (please refer to the next sections for a definition of this new language construct).
coolc will also generate and execute code for constant expressions (both integer and boolean). Execution of such code will just modify the internal status of the interpreter but won’t be used by further constructs, since the return values aren’t really handled.
coolc will additionally also construct a partial semantic tree of the code examined and perform some basic type-checking operations:

  • accordance between return value and method return type definition
  • compatibility of types in variable assignments
  • presence of a Bool expression for NOT/IF/WHILE arguments
  • redefinition of classes
  • redefinition of methods and attributes inside classes
  • use of undeclared variables and methods

Pay attention that just the dispatch code, the non-standard “print” and the constant expression will generate proper code to be executed by the interpreter. All the other constructs can be type-checked but will not be transformed into intermediate code (and later executed) if not maybe partially, generating unwanted execution code.
The basic Bool and Int COOL classes has been defined in coolc even if, being most of the expressions operators missing, they are quite simply managed.

You can download the full package here for the full source code, full documentation of this teaching project and code samples in the COOL language.