Docsity

Lexical Analysis: A Comprehensive Guide for Compiler Design, Assignments of Compiler Design

Partial preview of the text

Download Lexical Analysis: A Comprehensive Guide for Compiler Design and more Assignments Compiler Design in PDF only on Docsity!

ASSIGNMENT

Lexical Analysis

Compiler Design - CSC 4212

Contents

  • Contents
  • Table of figures
  • What is Lexical Analysis
  • Functionalities of Lexical Analyzer
  • Different tools used in Lexical Analysis
      1. Lex
      1. Flex
      1. Alex
      1. Jflex
      1. RE/flex
      1. re2c
      1. Quex
      1. Gardens Point LEX
      1. DFAlex
      1. Annoflex
      1. Golex
  • Toy Example
  • Other Uses of the Lexical Analyzer

What is Lexical Analysis

Lexical Analysis is the first phase of compiler which is also known as scanner. It converts the High-level input

program into a sequence of Tokens. The lexical analyzer breaks the syntaxes into a series of tokens, by

removing any whitespace or comments in the source code. Programs that perform lexical analysis are called

lexical analyzers or lexers. A lexer contains tokenizer or scanner. If the lexical analyzer detects that the token is

invalid, it generates an error. It reads character streams from the source code, checks for legal tokens, and

pass the data to the syntax analyzer when it requests. Developing and debugging lexers and its token

descriptions need more effort. Some tools were introduced in order to auto generate these lexers. They are

usually known as lexer generators/scanner generators.

Figure 1 : Process of a lexical Analyzer

Functionalities of Lexical Analyzer

1. Read the input characters and produce as output a sequence of tokens that the parser uses for syntax

analysis.

Decomposes source into tokens : words (identifiers, reserved words), numbers (123), symbols(+, <=)

according to a matching pattern .It typically “skips” whitespace and comments). The matching tokens in

the source programme is called as lexemes

Source

/source programme/

if (x <= 123) {

/* a comment */

sum = sum + x;

/* Token Stream */

if ( x <= 123 ) { sum = sum + x ; }

2. Eliminating the following from the source program:

2.1. Comments

/*** This is multiline comment ***/ //This is single Line comment

2.2. whitespace

2.2.1. Tab

Lorem ipsum dolor sit amet Consectetur adipisicing

2.2.2. Newline characters

public class AddTwoIntegers { public static void main(String[] args) { int first = 10 ; int second = 20 ; int sum = first + second; System.out.println("The sum is: " + sum); } }

Different tools used in Lexical Analysis

  1. Lex

Lex is a program generator designed for lexical processing of character input streams. It accepts a high-

level, problem-oriented specification for character string matching, and produces a program in a general-

purpose language which recognizes regular expressions. The regular expressions are specified by the user

in the source specifications given to Lex. The Lex written code recognizes these expressions in an input

stream and partitions the input stream into strings matching the expressions. At the boundaries between

strings program sections provided by the user are executed. The Lex source file associates the regular

expressions and the program fragments. As each expression appears in the input to the program written

by Lex, the corresponding fragment is executed. Lex can generate analyzers in either C or Ratfor, a

language which can be translated automatically to portable Fortran (in old versions).

http://dinosaur.compilertools.net/lex/index.html

/*** Definition section ***/ %{ /* C code to be copied verbatim */ #include <stdio.h> %} /* This tells flex to read only one input file */ %option noyywrap %% /*** Rules section **/ / [0-9]+ matches a string of one or more digits */ [ 0 - 9 ]+ { /* yytext is a string containing the matched text. */ printf("Saw an integer: %s \n ", yytext); } .|\n { /* Ignore all other characters. */ } %% /*** C Code section ***/ int main(void) { /* Call the lexer, then quit. */ yylex(); return 0 ; }

  1. Flex

FLEX (Fast LEXical analyzer generator) is a tool for generating scanners. Instead of writing a scanner from

scratch, we only need to identify the vocabulary of a certain language (e.g. Simple), write a specification of

patterns using regular expressions (e.g. DIGIT [0-9]), and FLEX will construct a scanner. It is used together

with Berkeley Yacc parser generator or GNU Bison parser generator. Flex and Bison both are more flexible

than Lex and Yacc and produces faster code.

https://github.com/westes/flex/

  1. Alex

Alex is a tool for generating lexical analysers in Haskell, given a description of the tokens to be recognised

in the form of regular expressions. It is similar to the tool lex or flex for C/C++. Alex is licensed under a BSD-

style license. It can be developed in all types of platforms.

https://github.com/simonmar/alex

  1. Jflex

JFlex is a lexical analyser generator for Java written in Java. It is also a rewrite of the tool JLex. It is more

sophisticated than JLex. JFlex lexers are based on deterministic finite automata (DFAs). They are fast,

without expensive backtracking. JFlex is designed to work together with the LALR parser generator CUP by

Scott Hudson, and the Java modification of Berkeley Yacc BYacc/J by Bob Jamison. It can also be used

together with other parser generators like ANTLR or as a standalone tool.

https://jflex.de/manual.html

/a small programme to count capital numbers in a document/ import java.util.*; %% %class CapitalCounter %standalone %{ int count= 0; %} %eof{ System.out.printf("\nNumber of Captial letters in the given input - %d\n",count); %eof} %% [A-Z] {System.out.printf("%s capital letter\n", yytext());count++;}

. {System.out.printf("%s not a capital letter\n", yytext());} \n { } /*** Definition section ***/ %{ int num_lines = 0, num_chars = 0; %} %% /*** Rules section ***/ \n ++num_lines; ++num_chars; . ++num_chars; end return 0; %% /*** C Code section ***/ ; main() { yylex(); printf( "# of lines = %d, # of chars = %d\n", num_lines, num_chars ); return 0; }

  1. Gardens Point LEX

GPLEX is a scanner generator which produces lexical scanners written in C# V2 or higher. The input

language is similar to the original LEX specification language, but allows full 21-bit Unicode scanners to be

specified. GPLEX generates scanners based around finite state automata. The generated automata have

the number of states minimized by default, and have a large number of options for table compression. The

default compression scheme is chosen depending on the input alphabet cardinality, and almost always

gives a reasonable result. However, a large number of options are available for the user to tune the

behavior if necessary.The tool implements many of the FLEX extensions, including such things as start-

state stacks. The generated scanners are designed to interface cleanly with bottom-up parsers generated

by Gardens Point Parser Generator. However, gplex-generated scanners have been successfully used with

both handwritten parsers and with parsers generated by COCO/R.

https://archive.codeplex.com/?p=gplex

  1. DFAlex

DFALex provides that powerful matching capability without all the fuss. It will build you a deterministic

finite automaton (DFA) for a matching/finding multiple patterns in strings simultaneously, which can then

use with various matcher classes to perform searching or scanning operations. Unlike other tools which

use DFAs internally, but only build scanners with them, DFALex provides with the actual DFA in an easy-to-

use form. Can use it in standard scanners, but can also use it in other ways that don't fit. DfAlex allows to

write specifications in a domain-specific language, often mixed with code, and then generate new java

code for a scanner that have to incorporate into build and use in pretty specific ways.

https://github.com/mtimmerm/dfalex

  1. Annoflex

AnnoFlex is an annotation-based code generator for lexical scanners. It uses Java as the main language for

the scanner definition and custom Javadoc tags to annotate methods with regular expressions. Javadoc

tags are used to circumvent double escaping as it occurs in common Java annotations. AnnoFlex is a fast

code generator which creates fast lexical scanners. It provides a lot of sophisticated features, is easy to use

and has significant advantages over classical code generators.

https://annoflex.github.io/

  1. Golex

golex is a flex-compatible lexical analyser generator, written for Go 1. golex is a tool for generating

scanners: programs which recognize lexical patterns in text. It reads the given input files for a description

of a scanner to generate. The description is in the form of pairs of regular expressions and Go code, called

rules. golex generates as output a Go source file, which defines a routine yylex(). When the routine is run,

it analyzes its input for occurrences of the regular expressions. Whenever it finds one, it executes the

corresponding Go code.

https://github.com/kivikakk/golex

Toy Example

/a small programme to parse chess record/ import java.util.; import java.io.; enum TokenType{MOVE,CAPTURE,PROMOTION,CHECK,CHECKMATE,CAPTUREWITHCHECK,CAPTUREWITHCHEC KMATE,KINGSIDECASTLE,QUEENSIDECASTLE,STALEMATE,BLACKWINS,WHITEWINS} %% %class Chess %standalone //means we dont need other dependancies like CUP %line %column %{ int whiteMarks = 0; int blackMarks = 0; double queen = 9; double rook = 5; double bishop = 3.5; double knight = 3; double pawn = 1; private int symbol(TokenType type) { System.out.println(type); return 0; // return new JavaSymbol(type, yyline+1, yycolumn+1); } private int symbol(TokenType type, String text, int line,int column) { System.out.println(type + " " +text+ " " + " " +line+" "+ column); return 0; /count marks for black and white/ // return new JavaSymbol(type, yyline+1, yycolumn+1, value); } %} piece = "K"|"Q"|"R"|"B"|"N" file = "a"|"b"|"c"|"d"|"e"|"f"|"g"|"h" rank = [1-8] whitespace = [ \n\t\r]+ capture = "x" check = "+" checkmate = # goodMove = "!" veryGoodMove = "!!" weakMove = ? blunder = "??"|"???" interestingMove = "!?" | * doubiousMove = "?!" move = {piece}?{file}{rank} captureAction = {piece}?{capture}{file}{rank} | {file}{capture}{file}{rank} pawnPromtion = {file}{rank}={piece} checkInAction = {move}{check} captureWithCheck = {captureAction}{check} checkmateInAction = {move}{checkmate} captureWithCheckmate = {captureAction}{checkmate}

Other Uses of the Lexical Analyzer

1. Used by web browsers to format and display a web page with the help of parsed data from JavsScript,

HTML, CSS.

2. Used by information retrieval systems for automatic indexing and query processing.

3. Used in text editors

4. Used in pattern recognition systems.