Home CPSC 401

Sloth Lexer


Due: February 5



This is the first phase of a multi-part assignment in which you will write an interpreter for a simple, but complete programming language called Sloth (Simple Language of Tiny Heft). In this part of the assignment you will build a lexical analyser (lexer) which is responsible for breaking the program into tokens. We will use the ANTLR system for this.



Sloth has the following features:


Test Programs

hello.slPrints hello world
simple.slPrints 1 + 1.
area.slInputs the radius of a circle and computes its area.
fact.slInputs a number and computes the factorial of that number.
fibs.slInputs a number N and displays the first N Fibonacci numbers.
minmax.slInputs a number N, then inputs N numbers, then displays the ones with the least and greatest values.
guess.slA guess the number game
table.slPrints a 2D multiplication table
acid.slA program that tests out most aspects of the language, and simply outputs 42.


Lexical Analysis

For this portion of the assignment, you will write a lexer for Sloth. The goal of the lexer is to break code up into individual tokens as discussed in class. The lexical details of the language are described here, and you will write a lexer using ANTLR.


Building the Lexer

You should name the lexer file as "SlothLexer.g4". Include the following line at the top of your lexer file:

grammar SlothLexer;

Include all of the needed lexer rules described above. Remember that lexer rules need to use names in all capitals.

In order to test our lexer, we do need to provide ANTLR with at least one grammar rule. To accomplish this, include the following "dummy rule" after the lexer rules:


You can use the following build and clean scripts to build and clean (remove generated files) the lexer. These rely on having completed the ANTLR setup instructions.



We can test the lexer using the ANTLR test rig, which we aliased as "grun". The -tokens flag can be passed to simply print the tokens recogized by your lexer from the input program. For instance, to test your lexer on the fact.sl program, you could use the following:

grun SlothLexer program -tokens < fact.sl

This should produce output like the following:

[@2,53:77='"Please enter a number: "',<STRINGVAL>,4:6]
[@42,243:248='"! = "',<STRINGVAL>,17:12]



Submit your SlothLexer.g4 file to Canvas for this assignment.

Copyright © 2024 Ian Finlayson | Licensed under a Attribution-NonCommercial 4.0 International License.