Compiler


The Compiler

The compiler takes the tokens produced by the lexical analyzer and compiles the code. The compiler has:
  • A lexical analyzer to separate the input in tokens
  • A token called lookahead to store the current token while compiling

Compiler operation

The compiler:
  1. Receives text with the code to be compiled
  2. Uses the lexical analyzer to separate the code in tokens
  3. Produces a vector of instructions: vector<Cpl::Compiler::Instruction> to store the compiled code
  4. Handles compiling errors and variable names

Compiling

The figure below illustrates how the Wintempla compiler works. First, the lexical analyzer creates a list of tokens. Second, the compiler uses the list of tokens to create a list of instructions. Third, the virtual-machine takes the list of instructions, and stores the values in its memory.

LexicalAndCompiler

Problem 1
Create a Wintempla dialog application called MyCompiler to test the compiler. Using Wintempla add two textboxes (tbxInput and tbxOutput) with the multi-line property, vertical scrollbars and horizontal scrollbar. Set the event of "Change" in the tbxInput textbox. Set also the "Want return" property in the tbxInput textbox.

tbxInputProperties

Scrollbars

ChangeEvent

MyCompiler.cpp
...
void MyCompiler::tbxInput_Change(Win::Event& e)
{
     wstring output;
     Cpl::Compiler compiler;
     vector<Cpl::Compiler::Instruction> machineCode;
     //_______________________________________________ Compile
     if (compiler.Compile(tbxInput.Text.c_str(), machineCode) == true)
     {
          compiler.ListCode(machineCode, output);     
     }
     else
     {
          const int count = machineCode.size();
          int line;
          for(int i = 0; i<count; i++)
          {
               if (machineCode[i].type == VM_ERROR)
               {
                    line = machineCode[i].line_number;
                    output += (wchar_t*)machineCode[i].name;
                    break;
               }
          }
     }
     //______________________________________________ Display
     tbxOutput.Text = output;
}


MyCompilerRun

Tip
When there are compilation errors, the Compile method of the class Cpl::Compiler returns false. You may inspect the vector of instructions looking for a instruction of type VM_ERROR as shown in the previous example.

© Copyright 2000-2019 Wintempla selo. All Rights Reserved. Sep 05 2019. Home