Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

History

102 Commits

Repository files navigation

🎄 Christmas Compiler

An educational compiler implementation featuring a festive, Christmas-themed programming language with complete front-end analysis and partial MIPS assembly code generation.

JavaGradleMIPS

📋 Table of Contents

🎯 Overview

This project implements a complete compiler pipeline from source code to MIPS assembly language. Developed as part of a Compilers course (Winter 2024/2025), it showcases the fundamental phases of compilation with a unique twist: all language keywords are Christmas-themed in Spanish!

Key Accomplishments:

  • ✅ Full lexical analysis with custom tokenization
  • ✅ Complete syntactic analysis with error recovery
  • ✅ Semantic analysis with symbol tables and type checking
  • ✅ Partial MIPS assembly code generation
  • ✅ Tested on MARS/SPIM simulators

✨ Features

Front-End (Complete Implementation)

🔤 Lexical Analysis

  • Tool: JFlex lexer generator
  • Features:
    • Tokenization of Christmas-themed keywords
    • Support for integers, floats, booleans, characters, and strings
    • Single-line and multi-line comment recognition
    • Comprehensive error reporting with line and column numbers

📐 Syntax Analysis

  • Tool: CUP (Constructor of Useful Parsers)
  • Features:
    • Context-free grammar for the Christmas language
    • Robust error recovery mechanisms
    • Support for nested structures
    • Detailed syntax error reporting

🔍 Semantic Analysis

  • Features:
    • Symbol Table Management: Multi-scope symbol tables with function and global scopes
    • Type Checking: Validation of type compatibility in expressions and assignments
    • Scope Validation: Proper handling of variable declarations and shadowing
    • Type Inference: Basic type resolution for expressions
    • Function Validation: Parameter count and type verification for function calls

Back-End (Partial Implementation)

⚙️ MIPS Code Generation

  • Implemented:

    • Arithmetic operations (+, -, *, /, %, ^)
    • Control flow structures (if-else, while loops, for loops)
    • Function declarations with prologue/epilogue
    • Stack frame management
    • Register allocation for temporary values
    • Basic I/O operations (print statements)
  • Tested On: MARS (MIPS Assembler and Runtime Simulator) and SPIM

🎅 Language Syntax

The Christmas language uses festive Spanish keywords. Here's a quick reference:

Data Types

KeywordStandard EquivalentType
rodolfointInteger
bromistafloatFloat
truenobooleanBoolean
cupidocharCharacter
cometastringString

Control Structures

KeywordStandard Equivalent
elfoif
hadaelse
envuelvewhile
duendefor
variosswitch
historiacase
ultimodefault

Operators

KeywordOperation
navidadAddition (+)
intercambioSubtraction (-)
nochebuenaMultiplication (*)
reyesDivision (/)
magosModulus (%)
advientoPower (^)
quienIncrement (++)
grinchDecrement (--)

Logical Operators

KeywordOperation
melchorAND (&&)
gasparOR (||)
baltazarNOT (!)
maryEquals (==)
openslaeNot equals (!=)
snowballLess than (<)
evergreenLess than or equal (<=)
minstixGreater than (>)
upatreeGreater than or equal (>=)

Delimiters

KeywordMeaning
abrecuentoOpen block ({ )
cierracuentoClose block (})
abreregaloOpen parenthesis (()
cierraregaloClose parenthesis ())
abreempaqueOpen bracket ([)
cierraempaqueClose bracket (])
finregaloSemicolon (;)
entregaAssignment (=)

I/O Operations

KeywordOperation
narraPrint
escuchaRead

Other Keywords

KeywordMeaning
enviaReturn
cortaBreak
sigueColon (:)

🏗️ Architecture

The compiler follows a traditional multi-phase architecture:

┌─────────────────┐
│ Source Code │
│ (.txt file) │
└────────┬────────┘
│
▼
┌─────────────────┐
│ Lexical Analysis│ ◄── JFlex (minijava.jflex)
│ (Lexer) │
└────────┬────────┘
│ Token Stream
▼
┌─────────────────┐
│Syntactic Analysis│ ◄── CUP (parser.cup)
│ (Parser) │
└────────┬────────┘
│ Abstract Syntax Tree
▼
┌─────────────────┐
│ Semantic Analysis│
│ - Symbol Table │
│ - Type Checking│
└────────┬────────┘
│ Annotated AST
▼
┌─────────────────┐
│ Code Generator │
│ (MIPS ASM) │
└────────┬────────┘
│
▼
┌─────────────────┐
│ Output (.asm) │
└─────────────────┘

Key Components

1. Lexer (minijava.jflex)

  • Pattern matching for tokens
  • Whitespace and comment handling
  • Token creation with position tracking

2. Parser (parser.cup)

  • Grammar rules definition
  • Error recovery strategies
  • AST construction
  • Integration with semantic analyzer

3. Symbol Table (SymbolTable.java)

  • Scope management (global and function-level)
  • Variable and function information storage
  • Type information tracking

4. Semantic Analyzer

  • Type checking for expressions and assignments
  • Function call validation
  • Variable declaration and usage verification
  • Scope resolution

5. Code Generator (CodeGenerator.java)

  • MIPS instruction emission
  • Register allocation
  • Stack frame management
  • Label generation for control flow

🛠️ Technologies

  • Language: Java
  • Build Tool: Gradle
  • Lexer Generator: JFlex 1.8.2
  • Parser Generator: CUP (Java Cup)
  • Target Architecture: MIPS32
  • Testing: MARS, SPIM simulators

📦 Installation

Prerequisites

  • Java Development Kit (JDK) 11 or higher
  • Gradle (included via wrapper)
  • MARS or SPIM simulator (for running generated assembly)

Build Instructions

  1. Clone the repository:
git clone <repository-url>cd Christmas-Compiler/Programa
  1. Build the project:
# On Windows
gradlew.bat build
# On Linux/Mac
./gradlew build
  1. Generate Lexer and Parser (if needed):
# Run the generator
./gradlew run

🚀 Usage

Compiling a Program

  1. Create a source file with Christmas language syntax (e.g., program.txt)

  2. Run the compiler:

// In your Java codeMaincompiler = newMain();
compiler.test("path/to/program.txt");
  1. Output: The compiler generates an .asm file with the same base name as the input

Example Workflow

# Input: test01.txt# Output: test01.asm# Run the generated assembly in MARS:# 1. Open MARS simulator# 2. Load test01.asm# 3. Assemble the program# 4. Run it

📁 Project Structure

Christmas-Compiler/
├── README.md
├── info.txt
├── Documentacion/
└── Programa/
├── build.gradle
├── gradlew
├── gradlew.bat
├── settings.gradle
├── gradle/
└── src/
├── lex/
│ ├── minijava.jflex # Lexer specification
│ ├── parser.cup # Parser grammar
│ └── salida.txt
├── main/java/
│ ├── compiler/
│ │ ├── Generator.java # Lexer/Parser generator
│ │ ├── Main.java # Entry point
│ │ └── Tester.java # Testing utilities
│ ├── destCodeGenerator/
│ │ ├── CodeGenerator.java # MIPS code generation
│ │ └── Operations.java
│ ├── organizer/
│ │ └── Organize.java
│ ├── parser/
│ │ ├── Lexer.java # Generated lexer
│ │ ├── parser.java # Generated parser
│ │ └── sym.java # Token symbols
│ ├── semanticalAnalysis/
│ │ ├── ControlStructureOperations.java
│ │ ├── Function.java
│ │ └── Variable.java
│ └── tables/
│ ├── FunctionInfo.java
│ ├── SymbolInfo.java
│ ├── SymbolTable.java
│ └── TokenInfo.java
└── tests/
├── test01.txt # Test programs
├── test01.asm # Generated assembly
├── testIF.txt
└── ...

📝 Examples

Example 1: Simple Arithmetic

Christmas Language:

rodolfo _suma_ abreregalo rodolfo _a_, rodolfo _b_ cierraregalo abrecuento
rodolfo _resultado_ entrega _a_ navidad _b_ finregalo
envia _resultado_ finregalo
cierracuento
rodolfo _verano_ abrecuento
rodolfo _x_ entrega 3 finregalo
rodolfo _y_ entrega 5 finregalo
rodolfo _total_ entrega _suma_ abreregalo _x_, _y_ cierraregalo finregalo
narra abreregalo "La suma es: ", _total_ cierraregalo finregalo
cierracuento

Equivalent in Standard Syntax:

intsum(inta, intb) {
intresult=a+b;
returnresult;
}
intmain() {
intx=3;
inty=5;
inttotal=sum(x, y);
print("La suma es: ", total);
}

Example 2: Control Flow

Christmas Language:

rodolfo _verano_ abrecuento
rodolfo _x_ entrega 10 finregalo
elfo abreregalo _x_ minstix 5 cierraregalo abrecuento
narra abreregalo "x es mayor que 5" cierraregalo finregalo
cierracuento
hada abrecuento
narra abreregalo "x es menor o igual a 5" cierraregalo finregalo
cierracuento
envuelve abreregalo _x_ minstix 0 cierraregalo abrecuento
narra abreregalo _x_ cierraregalo finregalo
_x_ grinch finregalo
cierracuento
cierracuento

Equivalent in Standard Syntax:

intmain() {
intx=10;
if (x>5) {
print("x es mayor que 5");
} else {
print("x es menor o igual a 5");
}
while (x>0) {
print(x);
x--;
}
}

Example 3: Arrays

Christmas Language:

rodolfo _verano_ abrecuento
rodolfo _arr_ abreempaque 5 cierraempaque entrega 0 finregalo
_arr_ abreempaque 0 cierraempaque entrega 10 finregalo
_arr_ abreempaque 1 cierraempaque entrega 20 finregalo
narra abreregalo "Primer elemento: ", _arr_ abreempaque 0 cierraempaque cierraregalo finregalo
cierracuento

⚠️ Limitations

Due to course time constraints, the MIPS code generator was partially implemented. The following features are NOT fully supported in the back-end:

❌ Not Implemented or Incomplete:

  • Advanced array operations: Dynamic allocation, multi-dimensional arrays
  • String operations: String concatenation, manipulation
  • Float arithmetic: Limited floating-point support
  • Switch statements: Code generation for switch-case structures
  • Nested function calls: Complex call chains
  • Memory management: No heap allocation
  • Standard library: No built-in functions beyond basic I/O
  • Optimization: No code optimization passes

✅ What Works:

  • Basic arithmetic operations (int)
  • Simple control flow (if-else, while, for)
  • Function calls with integer parameters
  • Basic print statements
  • Variable assignments
  • Simple expressions

Note: The front-end (lexical, syntactic, and semantic analysis) is fully functional and correctly validates all language constructs. Only the code generation phase has limitations.

🔮 Future Work

Potential enhancements for this project:

  1. Complete MIPS Code Generation:

    • Full array support
    • Complete floating-point operations
    • Switch statement implementation
  2. Optimizations:

    • Constant folding
    • Dead code elimination
    • Register allocation optimization
  3. Extended Features:

    • Structs/Records
    • Pointers
    • Dynamic memory allocation
    • Standard library functions
  4. Development Tools:

    • Interactive debugger
    • Visual AST representation
    • IDE plugin with syntax highlighting
  5. Testing:

    • Comprehensive test suite
    • Performance benchmarks
    • Fuzzing testing

👥 Authors

Adrián José Villalobos Peraza & Isaac Ramírez Rojas

  • Course: Compiladores e Intérpretes
  • Term: Winter 2024/2025
  • Institution: Instituto Tecnológico de Costa Rica

📄 License

This project was developed for educational purposes as part of a university course.


🎄 Made with festive spirit and lots of coffee ☕

About

Christmas Compiler is an educational compiler built in Java featuring a festive Spanish-themed programming language. It includes full lexical, syntactic, and semantic analysis with partial MIPS code generation, developed for a Compilers course at TEC.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages