System Software Notes 10CS52
System Software Notes 10CS52
COPY
000000 001077
T
000000
1D17202D69202D
48101036
4B105D
3F2FEC
032010
T
00001D
13
0F2016
010003
0F200D
4B10105D
3E2003
454F46
T
001035
1D
B410
B400
B440
75101000
332008
57C003
B850
T
001053
1D
3B2FEA
134000
4F0000
F1
..
53C003
DF2008
B850
T
00070
07
3B2FEF
4F0000
05
M
000007
05+COPY
M
000014
05+COPY
M
000027
05+COPY
E
000000
The relocation bit method is used for simple machines. Relocation bit is 0: no
modification is necessary, and is 1: modification is needed. This is specified in the columns
10-12 of text record (T), the format of text record, along with relocation bits is as follows.
Text record:
col 1: T
col 2-7: starting address
col 8-9: length (byte)
col 10-12: relocation bits
col 13-72: object code
Twelve-bit mask is used in each Text record (col:10-12 relocation bits), since each
text record contains less than 12 words, unused words are set to 0, and, any value that is to be
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 77
modified during relocation must coincide with one of these 3-byte segments. For absolute
loader, there are no relocation bits column 10-69 contains object code. The object program
with relocation by bit mask is as shown below. Observe FFC - means all ten words are to be
modified and, E00 - means first three records are to be modified.
H
COPY
000000 00107A
T
000000
1E
FFC
140033
481039
000036
280030
300015
3C0003
00001E
15
E00
0C0036
481061
080033
4C0000
000003
000000
T
001039
1E
FFC
040030
000030
30103F
D8105D
280030
...
T
001057
0A
800
100036
4C0000
F1
001000
T
001061
19
FE0
040030
E01079
508039
DC1079
2C0036
...
E
000000
4.2.2 Program Linking
The Goal of program linking is to resolve the problems with external references
(EXTREF) and external definitions (EXTDEF) from different control sections.
EXTDEF (external definition) - The EXTDEF statement in a control section
names symbols, called external symbols, that are defined in this (present) control section and
may be used by other sections.
ex: EXTDEF BUFFER, BUFFEND, LENGTH
EXTDEF LISTA, ENDA
EXTREF (external reference) - The EXTREF statement names symbols used in
this (present) control section and are defined elsewhere.
ex: EXTREF RDREC, WRREC
EXTREF LISTB, ENDB, LISTC, ENDC
How to implement EXTDEF and EXTREF
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 78
The assembler must include information in the object program that will cause the loader to
insert proper values where they are required in the form of Define record (D) and, Refer
record(R).
Define record
The format of the Define record (D) along with examples is as shown here.
Col. 1 D
Col. 2-7 Name of external symbol defined in this control section
Col. 8-13 Relative address within this control section (hexadecimal)
Col.14-73 Repeat information in Col. 2-13 for other external symbols
Example records
D LISTA 000040 ENDA 000054
D LISTB 000060 ENDB 000070
Refer record
The format of the Refer record (R) along with examples is as shown here.
Col. 1 R
Col. 2-7 Name of external symbol referred to in this control section
Col. 8-73 Name of other external reference symbols
Example records
R LISTB ENDB LISTC ENDC
R LISTA ENDA LISTC ENDC
R LISTA ENDA LISTB ENDB
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 79
Here are the three programs named as PROGA, PROGB and PROGC, which are
separately assembled and each of which consists of a single control section. LISTA, ENDA
in PROGA, LISTB, ENDB in PROGB and LISTC, ENDC in PROGC are external
definitions in each of the control sections. Similarly LISTB, ENDB, LISTC, ENDC in
PROGA, LISTA, ENDA, LISTC, ENDC in PROGB, and LISTA, ENDA, LISTB, ENDB in
PROGC, are external references. These sample programs given here are used to illustrate
linking and relocation. The following figures give the sample programs and their
corresponding object programs. Observe the object programs, which contain D and R records
along with other records.
0000 PROGA START 0
EXTDEF LISTA, ENDA
EXTREF LISTB, ENDB, LISTC, ENDC
..
.
0020 REF1 LDA LISTA 03201D
0023 REF2 +LDT LISTB+4 77100004
0027 REF3 LDX #ENDA-LISTA 050014
.
.
0040 LISTA EQU *
0054 ENDA EQU *
0054 REF4 WORD ENDA-LISTA+LISTC 000014
0057 REF5 WORD ENDC-LISTC-10 FFFFF6
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 80
005A REF6 WORD ENDC-LISTC+LISTA-1 00003F
005D REF7 WORD ENDA-LISTA-(ENDB-LISTB) 000014
0060 REF8 WORD LISTB-LISTA FFFFC0
END REF1
0000 PROGB START 0
EXTDEF LISTB, ENDB
EXTREF LISTA, ENDA, LISTC, ENDC
..
.
0036 REF1 +LDA LISTA 03100000
003A REF2 LDT LISTB+4 772027
003D REF3 +LDX #ENDA-LISTA 05100000
.
.
0060 LISTB EQU *
0070 ENDB EQU *
0070 REF4 WORD ENDA-LISTA+LISTC 000000
0073 REF5 WORD ENDC-LISTC-10 FFFFF6
0076 REF6 WORD ENDC-LISTC+LISTA-1 FFFFFF
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 81
0079 REF7 WORD ENDA-LISTA-(ENDB-LISTB) FFFFF0
007C REF8 WORD LISTB-LISTA 000060
END
0000 PROGC START 0
EXTDEF LISTC, ENDC
EXTREF LISTA, ENDA, LISTB, ENDB
..
..
0018 REF1 +LDA LISTA 03100000
001C REF2 +LDT LISTB+4 77100004
0020 REF3 +LDX #ENDA-LISTA 05100000
.
.
0030 LISTC EQU *
0042 ENDC EQU *
0042 REF4 WORD ENDA-LISTA+LISTC 000030
0045 REF5 WORD ENDC-LISTC-10 000008
0045 REF6 WORD ENDC-LISTC+LISTA-1 000011
004B REF7 WORD ENDA-LISTA-(ENDB-LISTB) 000000
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 82
004E REF8 WORD LISTB-LISTA 000000
END
H PROGA 000000 000063
D LISTA 000040 ENDA 000054
R LISTB ENDB LISTC ENDC
.
.
T 000020 0A 03201D 77100004 050014
.
.
T 000054 0F 000014 FFFF6 00003F 000014 FFFFC0
M000024 05+LISTB
M000054 06+LISTC
M000057 06+ENDC
M000057 06 -LISTC
M00005A06+ENDC
M00005A06 -LISTC
M00005A06+PROGA
M00005D06-ENDB
M00005D06+LISTB
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 83
M00006006+LISTB
M00006006-PROGA
E000020
H PROGB 000000 00007F
D LISTB 000060 ENDB 000070
R LISTA ENDA LISTC ENDC
.
T 000036 0B 03100000 772027 05100000
.
T 000007 0F 000000 FFFFF6 FFFFFF FFFFF0 000060
M000037 05+LISTA
M00003E 06+ENDA
M00003E 06 -LISTA
M000070 06 +ENDA
M000070 06 -LISTA
M000070 06 +LISTC
M000073 06 +ENDC
M000073 06 -LISTC
M000073 06 +ENDC
M000076 06 -LISTC
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 84
M000076 06+LISTA
M000079 06+ENDA
M000079 06 -LISTA
M00007C 06+PROGB
M00007C 06-LISTA
E
H PROGC 000000 000051
D LISTC 000030 ENDC 000042
R LISTA ENDA LISTB ENDB
.
T 000018 0C 03100000 77100004 05100000
.
T 000042 0F 000030 000008 000011 000000 000000
M000019 05+LISTA
M00001D 06+LISTB
M000021 06+ENDA
M000021 06 -LISTA
M000042 06+ENDA
M000042 06 -LISTA
M000042 06+PROGC
M000048 06+LISTA
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 85
M00004B 06+ENDA
M00004B 006-LISTA
M00004B 06-ENDB
M00004B 06+LISTB
M00004E 06+LISTB
M00004E 06-LISTA
E
The following figure shows these three programs as they might appear in memory
after loading and linking. PROGA has been loaded starting at address 4000, with PROGB
and PROGC immediately following.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 86
For example, the value for REF4 in PROGA is located at address 4054 (the beginning
address of PROGA plus 0054, the relative address of REF4 within PROGA). The following
figure shows the details of how this value is computed.
The initial value from the Text record
T0000540F000014FFFFF600003F000014FFFFC0 is 000014. To this is added the
address assigned to LISTC, which is 4112 (the beginning address of PROGC plus 30). The
result is 004126.
That is REF4 in PROGA is ENDA-LISTA+LISTC=4054-4040+4112=4126.
Similarly the load address for symbols LISTA: PROGA+0040=4040, LISTB:
PROGB+0060=40C3 and LISTC: PROGC+0030=4112
Keeping these details work through the details of other references and values of these
references are the same in each of the three programs.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 87
4.3.3 Algorithm and Data structures for a Linking Loader
The algorithm for a linking loader is considerably more complicated than the absolute loader
program, which is already given. The concept given in the program linking section is used
for developing the algorithm for linking loader. The modification records are used for
relocation so that the linking and relocation functions are performed using the same
mechanism.
Linking Loader uses two-passes logic. ESTAB (external symbol table) is the main
data structure for a linking loader.
Pass 1: Assign addresses to all external symbols
Pass 2: Perform the actual loading, relocation, and linking
ESTAB - ESTAB for the example (refer three programs PROGA PROGB and
PROGC) given is as shown below. The ESTAB has four entries in it; they are name of the
control section, the symbol appearing in the control section, its address and length of the
control section.
Program Logic for Pass 1
Control section Symbol Address Length
PROGA 4000 63
LISTA 4040
ENDA 4054
PROGB 4063 7F
LISTB 40C3
ENDB 40D3
PROGC 40E2 51
LISTC 4112
ENDC 4124
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 88
Pass 1 assign addresses to all external symbols. The variables & Data structures used during
pass 1 are, PROGADDR (program load address) from OS, CSADDR (control section
address), CSLTH (control section length) and ESTAB. The pass 1 processes the Define
Record. The algorithm for Pass 1 of Linking Loader is given below.
Program Logic for Pass 2
Pass 2 of linking loader perform the actual loading, relocation, and linking. It uses
modification record and lookup the symbol in ESTAB to obtain its address. Finally it uses
end record of a main program to obtain transfer address, which is a starting address needed
for the execution of the program. The pass 2 process Text record and Modification record of
the object programs. The algorithm for Pass 2 of Linking Loader is given below.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 89
How to improve Efficiency?
The question here is can we improve the efficiency of the linking loader. Also observe that,
even though we have defined Refer record (R), we havent made use of it. The efficiency can
be improved by the use of local searching instead of multiple searches of ESTAB for the
same symbol. For implementing this we assign a reference number to each external symbol
in the Refer record. Then this reference number is used in Modification records instead of
external symbols.01 is assigned to control section name, and other numbers for external
reference symbols.
The object programs for PROGA, PROGB and PROGC are shown below, with above
modification to Refer record (Observe R records).
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 90
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 91
Symbol and Addresses in PROGA, PROGB and PROGC are as shown below. These
are the entries of ESTAB. The main advantage of reference number mechanism is that it
avoids multiple searches of ESTAB for the same symbol during the loading of a control
section
Ref No. Symbol Address
1 PROGA 4000
2 LISTB 40C3
3 ENDB 40D3
4 LISTC 4112
5 ENDC 4124
Ref No. Symbol Address
1 PROGB 4063
2 LISTA 4040
3 ENDA 4054
4 LISTC 4112
5 ENDC 4124
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 92
4.3. Machine-independent Loader Features
Here we discuss some loader features that are not directly related to machine architecture and
design. Automatic Library Search and Loader Options are such Machine-independent Loader
Features.
4.3.1Automatic Library Search
This feature allows a programmer to use standard subroutines without explicitly including
them in the program to be loaded. The routines are automatically retrieved from a library as
they are needed during linking. This allows programmer to use subroutines from one or more
libraries. The subroutines called by the program being loaded are automatically fetched from
the library, linked with the main program and loaded. The loader searches the library or
libraries specified for routines that contain the definitions of these symbols in the main
program.
4.3.2Loader Options
Loader options allow the user to specify options that modify the standard processing. The
options may be specified in three different ways. They are, specified using a command
language, specified as a part of job control language that is processed by the operating
system, and an be specified using loader control statements in the source program.
Here are the some examples of how option can be specified.
INCLUDE program-name (library-name) - read the designated object program from
a library
Ref No. Symbol Address
1 PROGC 4063
2 LISTA 4040
3 ENDA 4054
4 LISTB 40C3
5 ENDB 40D3
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 93
DELETE csect-name delete the named control section from the set pf programs
being loaded
CHANGE name1, name2 - external symbol name1 to be changed to name2
wherever it appears in the object programs
LIBRARY MYLIB search MYLIB library before standard libraries
NOCALL STDDEV, PLOT, CORREL no loading and linking of unneeded
routines
Here is one more example giving, how commands can be specified as a part of object
file, and the respective changes are carried out by the loader.
LIBRARY UTLIB
INCLUDE READ (UTLIB)
INCLUDE WRITE (UTLIB)
DELETE RDREC, WRREC
CHANGE RDREC, READ
CHANGE WRREC, WRITE
NOCALL SQRT, PLOT
The commands are, use UTLIB (say utility library), include READ and WRITE
control sections from the library, delete the control sections RDREC and WRREC from the
load, the change command causes all external references to the symbol RDREC to be
changed to the symbol READ, similarly references to WRREC is changed to WRITE,
finally, no call to the functions SQRT, PLOT, if they are used in the program.
4.4 Loader Design Options
There are some common alternatives for organizing the loading functions, including
relocation and linking. Linking Loaders Perform all linking and relocation at load time. The
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 94
Other Alternatives are Linkage editors, which perform linking prior to load time and,
dynamic linking, in which linking function is performed at execution time
Linking Loaders
The above diagram shows the processing of an object program using Linking Loader.
The source program is first assembled or compiled, producing an object program. A linking
loader performs all linking and loading operations, and loads the program into memory for
execution.
4.4.1 Linkage Editors
The figure below shows the processing of an object program using Linkage editor. A linkage
editor produces a linked version of the program often called a load module or an executable
image which is written to a file or library for later execution. The linked program produced
is generally in a form that is suitable for processing by a relocating loader.
Library
Object
Program(s)
Linking loader
Memory
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 95
Some useful functions of Linkage editor are, an absolute object program can be
created, if starting address is already known. New versions of the library can be included
without changing the source program. Linkage editors can also be used to build packages of
subroutines or other control sections that are generally used together. Linkage editors often
allow the user to specify that external references are not to be resolved by automatic library
search linking will be done later by linking loader linkage editor + linking loader
savings in space
4.4.2Dynamic Linking
The scheme that postpones the linking functions until execution. A subroutine is loaded and
linked to the rest of the program when it is first called usually called dynamic linking,
dynamic loading or load on call. The advantages of dynamic linking are, it allow several
executing programs to share one copy of a subroutine or library. In an object oriented system,
Library
Object
Program(s)
Linkage Editor
Linked
program
Memory
Relocating loader
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 96
dynamic linking makes it possible for one object to be shared by several programs. Dynamic
linking provides the ability to load the routines only when (and if) they are needed. The
actual loading and linking can be accomplished using operating system service request.
4.4.3 Bootstrap Loaders
If the question, how is the loader itself loaded into the memory? is asked, then the answer is,
when computer is started with no program in memory, a program present in ROM (
absolute address) can be made executed may be OS itself or A Bootstrap loader, which in
turn loads OS and prepares it for execution. The first record ( or records) is generally referred
to as a bootstrap loader makes the OS to be loaded. Such a loader is added to the beginning
of all object programs that are to be loaded into an empty and idle system.
4.5 Implementation Examples
This section contains brief description of loaders and linkers for actual computers. They are,
MS-DOS Linker - Pentium architecture, SunOS Linkers - SPARC architecture, and, Cray
MPP Linkers T3E architecture.
4.5.1MS-DOS Linker
This explains some of the features of Microsoft MS-DOS linker, which is a linker for
Pentium and other x86 systems. Most MS-DOS compilers and assemblers (MASM) produce
object modules, and they are stored in .OBJ files. MS-DOS LINK is a linkage editor that
combines one or more object modules to produce a complete executable program - .EXE file;
this file is later executed for results.
The following table illustrates the typical MS-DOS object module
Record Types Description
THEADR Translator Header
TYPDEF,PUBDEF, EXTDEF External symbols and references
LNAMES, SEGDEF, GRPDEF Segment definition and grouping
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 97
LEDATA, LIDATA Translated instructions and data
FIXUPP Relocation and linking information
MODEND End of object module
THEADR specifies the name of the object module. MODEND specifies the end of
the module. PUBDEF contains list of the external symbols (called public names). EXTDEF
contains list of external symbols referred in this module, but defined elsewhere. TYPDEF the
data types are defined here. SEGDEF describes segments in the object module ( includes
name, length, and alignment). GRPDEF includes how segments are combined into groups.
LNAMES contains all segment and class names. LEDATA contains translated instructions
and data. LIDATA has above in repeating pattern. Finally, FIXUPP is used to resolve
external references.
RECOMMENDED QUESTIONS:
1) Write an algorithm for an absolute loader ( 7)
2) Explain bootstrap loaders. (6)
3) Write an algorithm for Bootstrap loader. (7)
4) Explain relocation w.r.t. loader. (8)
5) Explain bitmask with an example.(5)
6) Explain program linking with an example. (7)
7) Write the algorithm for pass 1 of an linking loader. (8)
8) Write the algorithm for pass 2 of an linking loader. (8)
9) Explain CSADDR, PROGADDR, ESTAB.(6)
10) Explain linkage editors. (8)
11) Explain dynamic linking. (8)
12) Write shortnotes on (10)
a. MS-DOS Linker
b. Sun OS linker
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 98
Chapter 5
EDITORS AND DEBUGGING SYSTEMS
An Interactive text editor has become an important part of almost any computing
environment. Text editor acts as a primary interface to the computer for all type of
knowledge workers as they compose, organize, study, and manipulate computer-based
information.
An interactive debugging system provides programmers with facilities that aid in
testing and debugging of programs. Many such systems are available during these days. Our
discussion is broad in scope, giving the overview of interactive debugging systems not
specific to any particular existing system.
5.1 Text Editors:
An Interactive text editor has become an important part of almost any computing
environment. Text editor acts as a primary interface to the computer for all type of
knowledge workers as they compose, organize, study, and manipulate computer-
based information.
A text editor allows you to edit a text file (create, modify etc). For example the
Interactive text editors on Windows OS - Notepad, WordPad, Microsoft Word, and
text editors on UNIX OS - vi, emacs , jed, pico.
Normally, the common editing features associated with text editors are, Moving the
cursor, Deleting, Replacing, Pasting, Searching, Searching and replacing, Saving and
loading, and, Miscellaneous(e.g. quitting).
5.1.1 Overview of the editing process
An interactive editor is a computer program that allows a user to create and revise a target
document. Document includes objects such as computer diagrams, text, equations tables,
diagrams, line art, and photographs. In text editors, character strings are the primary elements
of the target text.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 99
Document-editing process in an interactive user-computer dialogue has four tasks:
- Select the part of the target document to be viewed and manipulated
- Determine how to format this view on-line and how to display it
- Specify and execute operations that modify the target document
- Update the view appropriately
The above task involves traveling, filtering and formatting. Editing phase involves insert,
delete, replace, move, copy, cut, paste, etc
o Traveling locate the area of interest
o Filtering - extracting the relevant subset
o Formatting visible representation on a display screen
There are two types of editors. Manuscript-oriented editor and program oriented
editors. Manuscript-oriented editor is associated with characters, words, lines, sentences and
paragraphs. Program-oriented editors are associated with identifiers, keywords, statements.
User wish what he wants formatted.
5.1.2 User Interface:
Conceptual model of the editing system provides an easily understood abstraction of the
target document and its elements. For example, Line editors simulated the world of the key
punch 80 characters, single line or an integral number of lines, Screen editors Document
is represented as a quarter-plane of text lines, unbounded both down and to the right.
The user interface is concerned with, the input devices, the output devices and, the
interaction language. The input devices are used to enter elements of text being edited, to
enter commands. The output devices, lets the user view the elements being edited and the
results of the editing operations and, the interaction language provides communication with
the editor.
Input Devices are divided into three categories:
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 100
o text devices
o button devices
o Locator devices.
1. Text Devices are keyboard. Button Devices are special function keys,
symbols on the screen. Locator Devices are mouse, data tablet. There are
voice input devices which translates spoken words to their textual
equivalents.
2. Output Devices are Teletypewriters(first output devices), Glass teletypes
(Cathode ray tube (CRT) technology), Advanced CRT terminals, TFT
Monitors and Printers (Hard-copy).
3. The interaction language could be, typing oriented or text command oriented
and menu-oriented user interface. Typing oriented or text command oriented
interaction was with oldest editors, in the form of use of commands, use of
function keys, control keys etc.
4. Menu-oriented user interface has menu with a multiple choice set of text
strings or icons. Display area for text is limited. Menus can be turned on or
off.
5.1.3 Editor Structure:
Most text editors have a structure similar to that shown in the following figure. That is most
text editors have a structure similar to shown in the figure regardless of features and the
computers
Command language Processor accepts command, uses semantic routines performs
functions such as editing and viewing. The semantic routines involve traveling, editing,
viewing and display functions.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 101
Editing operations are specified explicitly by the user and display operations are
specified implicitly by the editor. Traveling and viewing operations may be invoked
either explicitly by the user or implicitly by the editing operations.
In editing a document, the start of the area to be edited is determined by the current
editing pointer maintained by the editing component. Editing component is a
collection of modules dealing with editing tasks. Current editing pointer can be set or
reset due to next paragraph, next screen, cut paragraph, paste paragraph etc..,.
When editing command is issued, editing component invokes the editing filter
generates a new editing buffer contains part of the document to be edited from
current editing pointer. Filtering and editing may be interleaved, with no explicit
editor buffer being created.
In viewing a document, the start of the area to be viewed is determined by the current
viewing pointer maintained by the viewing component. Viewing component is a
collection of modules responsible for determining the next view. Current viewing
pointer can be set or reset as a result of previous editing operation.
Editing
component
Traveling
component
Viewing
component
Command
language
processor
Editing
filter
Viewing
filter
Viewing
buffer
Main
memory
File
system
Display
component
Output
devices
input
Typical Editor Structure
Paging
Routines
Control
Data
Editing
buffer
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 102
When display needs to be updated, viewing component invokes the viewing filter
generates a new viewing buffer contains part of the document to be viewed from
current viewing pointer. In case of line editors viewing buffer may contain the
current line, Screen editors - viewing buffer contains a rectangular cutout of the
quarter plane of the text.
Viewing buffer is then passed to the display component of the editor, which produces
a display by mapping the buffer to a rectangular subset of the screen called a
window. Identical user edits the text directly on the screen. Disjoint Find and
Replace (For example, there are 150 lines of text, user is in 100th line, decides to
change all occurrences of text editor with editor).
The editing and viewing buffers can also be partially overlapped, or one may be
completely contained in the other. Windows typically cover entire screen or a
rectangular portion of it. May show different portions of the same file or portions of
different file. Inter-file editing operations are possible.
The components of the editor deal with a user document on two levels: In main
memory and in the disk file system. Loading an entire document into main memory
may be infeasible only part is loaded demand paging is used uses editor paging
routines.
Documents may not be stored sequentially as a string of characters. Uses separate
editor data structure that allows addition, deletion, and modification with a minimum
of I/O and character movement.
Types of editors based on computing environment
Editors function in three basic types of computing environments:
1. Time sharing
2. Stand-alone
3. Distributed.
Each type of environment imposes some constraints on the design of an editor.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 103
In time sharing environment, editor must function swiftly within the context of the
load on the computers processor, memory and I/O devices.
In stand-alone environment, editors on stand-alone system are built with all the
functions to carry out editing and viewing operations The help of the OS may also
be taken to carry out some tasks like demand paging.
In distributed environment, editor has both functions of stand-alone editor; to run
independently on each users machine and like a time sharing editor, contend for
shared resources such as files.
5.2 Interactive Debugging Systems:
An interactive debugging system provides programmers with facilities that aid in testing and
debugging of programs. Many such systems are available during these days. Our discussion
is broad in scope, giving the overview of interactive debugging systems not specific to any
particular existing system.
Here we discuss
- Introducing important functions and capabilities of IDS
- Relationship of IDS to other parts of the system
- The nature of the user interface for IDS
5.2.1. Debugging Functions and Capabilities:
One important requirement of any IDS is the observation and control of the flow of program
execution. Setting break points execution is suspended, use debugging commands to
analyze the progress of the program, rsum execution of the program. Setting some
conditional expressions, evaluated during the debugging session, program execution is
suspended, when conditions are met, analysis is made, later execution is resumed.
A Debugging system should also provide functions such as tracing and trace back.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 104
Tracing can be used to track the flow of execution logic and data modifications. The
control flow can be traced at different levels of detail procedure, branch, individual
instruction, and so on
Trace back can show the path by which the current statement in the program was
reached. It can also show which statements have modified a given variable or
parameter. The statements are displayed rather than as hexadecimal displacements
Program-Display capabilities
A debugger should have good program-display capabilities.
Program being debugged should be displayed completely with statement numbers.
The program may be displayed as originally written or with macro expansion.
Keeping track of any changes made to the programs during the debugging session.
Support for symbolically displaying or modifying the contents of any of the variables
and constants in the program. Resume execution after these changes.
To provide these functions, a debugger should consider the language in which the
program being debugged is written. A single debugger many programming languages
language independent. The debugger- a specific programming language language
dependent. The debugger must be sensitive to the specific language being debugged.
The context being used has many different effects on the debugging interaction. The
statements are different depending on the language
Cobol - MOVE 6.5 TO X
Fortran - X = 6.5
C - X = 6.5
Examples of assignment statements
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 105
Similarly, the condition that X be unequal to Z may be expressed as
COBOL- IF X NOT EQUAL TO Z
FORTRAN- IF(X.NE.Z)
C - IF(X<> Z)
Similar differences exist with respect to the form of statement labels, keywords and so on
The notation used to specify certain debugging functions varies according to the
language of the program being debugged. Sometimes the language translator itself has
debugger interface modules that can respond to the request for debugging by the user. The
source code may be displayed by the debugger in the standard form or as specified by the
user or translator.
It is also important that a debugging system be able to deal with optimized code.
Many optimizations like
- Invariant expressions can be removed from loops
- Separate loops can be combined into a single loop
- Redundant expression may be eliminated
- Elimination of unnecessary branch instructions
Leads to rearrangement of segments of code in the program. All these optimizations
create problems for the debugger, and should be handled carefully.
5.2.2 Relationship with Other Parts of the System:
The important requirement for an interactive debugger is that it always be available.
Must appear as part of the run-time environment and an integral part of the system.
When an error is discovered, immediate debugging must be possible. The debugger
must communicate and cooperate with other operating system components such as
interactive subsystems.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 106
Debugging is more important at production time than it is at application-development
time. When an application fails during a production run, work dependent on that
application stops.
The debugger must also exist in a way that is consistent with the security and
integrity components of the system.
The debugger must coordinate its activities with those of existing and future
language compilers and interpreters.
5.2.3. User-Interface Criteria:
Debugging systems should be simple in its organization and familiar in its language,
closely reflect common user tasks.
The simple organization contribute greatly to ease of training and ease of use.
The user interaction should make use of full-screen displays and windowing-systems
as much as possible.
With menus and full-screen editors, the user has far less information to enter and
remember. There should be complete functional equivalence between commands and
menus user where unable to use full-screen IDSs may use commands.
The command language should have a clear, logical and simple syntax.
command formats should be as flexible as possible.
Any good IDSs should have an on-line HELP facility. HELP should be accessible
from any state of the debugging session.
RECOMMENDED QUESTIONS:
1. List out the four tasks to be accomplished by an interactive editor process. (4)
2. Explain user interface. (6)
3. With a diagram explain the structure of an editor. (10)
4. Explain user interface criteria. (6)
5. Explain debugging functions and its capabilities. (8)
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 107
Chapter 6
MACRO PROCESSOR
A Macro represents a commonly used group of statements in the source programming
language.
A macro instruction (macro) is a notational convenience for the programmer
o It allows the programmer to write shorthand version of a program (module
programming)
The macro processor replaces each macro instruction with the corresponding group of
source language statements (expanding)
o Normally, it performs no analysis of the text it handles.
o It does not concern the meaning of the involved statements during macro
expansion.
The design of a macro processor generally is machine independent!
Two new assembler directives are used in macro definition
o MACRO: identify the beginning of a macro definition
o MEND: identify the end of a macro definition
Prototype for the macro
o Each parameter begins with &
name MACRO parameters
:
body
:
MEND
o Body: the statements that will be generated as the expansion of the macro.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 108
6.1. Basic Macro Processor Functions:
Macro Definition and Expansion
Macro Processor Algorithms and Data structures
6.1.1Macro Definition and Expansion:
Figure shows the MACRO expansion. The left block shows the MACRO definition
and the right block shows the expanded macro replacing the MACRO call with its block of
executable instruction.
M1 is a macro with two parameters D1 and D2. The MACRO stores the contents of
register A in D1 and the contents of register B in D2. Later M1 is invoked with the
parameters DATA1 and DATA2, Second time with DATA4 and DATA3. Every call of
MACRO is expended with the executable statements.
Fig 6.1: macro call
The statement M1 DATA1, DATA2 is a macro invocation statements that gives the name of
the macro instruction being invoked and the arguments (M1 and M2) to be used in
expanding. A macro invocation is referred as a Macro Call or Invocation.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 109
Macro Expansion:
The program with macros is supplied to the macro processor. Each macro invocation
statement will be expanded into the statement s that form the body of the macro, with the
arguments from the macro invocation substituted for the parameters in the macro prototype.
During the expansion, the macro definition statements are deleted since they are no longer
needed.
The arguments and the parameters are associated with one another according to their
positions. The first argument in the macro matches with the first parameter in the macro
prototype and so on.
After macro processing the expanded file can become the input for the Assembler.
The Macro Invocation statement is considered as comments and the statement generated
from expansion is treated exactly as though they had been written directly by the
programmer.
he difference between Macros and Subroutines is that the statement s from the body
of the Macro is expanded the number of times the macro invocation is encountered, whereas
the statement of the subroutine appears only once no matter how many times the subroutine
is called. Macro instructions will be written so that the body of the macro contains no labels.
Problem of the label in the body of macro:
o If the same macro is expanded multiple times at different places in the
program
o There will be duplicate labels, which will be treated as errors by the
assembler.
Solutions:
o Do not use labels in the body of macro.
o Explicitly use PC-relative addressing instead.
Ex, in RDBUFF and WRBUFF macros,
o JEQ *+11
o JLT *-14
It is inconvenient and error-prone.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 110
The following program shows the concept of Macro Invocation and Macro
Expansion.
Fig 6.2: concept of Macro Invocation and Macro Expansion.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 111
6.1.2 Macro Processor Algorithm and Data Structure:
Design can be done as two-pass or a one-pass macro. In case of two-pass assembler.
Two-pass macro processor
You may design a two-pass macro processor
o Pass 1:
Process all macro definitions
o Pass 2:
Expand all macro invocation statements
However, one-pass may be enough
o Because all macros would have to be defined during the first pass before any
macro invocations were expanded.
The definition of a macro must appear before any statements that
invoke that macro.
Moreover, the body of one macro can contain definitions of the other macro
Consider the example of a Macro defining another Macro.
In the example below, the body of the first Macro (MACROS) contains statement that
define RDBUFF, WRBUFF and other macro instructions for SIC machine.
The body of the second Macro (MACROX) defines the se same macros for SIC/XE
machine.
A proper invocation would make the same program to perform macro invocation to
run on either SIC or SIC/XEmachine.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 112
MACROS for SIC machine
Fig 4.3(a)
MACROX for SIC/XE Machine
Fig 4.3(b)
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 113
A program that is to be run on SIC system could invoke MACROS whereas a
program to be run on SIC/XE can invoke MACROX.
However, defining MACROS or MACROX does not define RDBUFF and WRBUFF.
These definitions are processed only when an invocation of MACROS or MACROX
is expanded.
One-Pass Macro Processor:
A one-pass macro processor that alternate between macro definition and macro
expansion in a recursive way is able to handle recursive macro definition.
Restriction
o The definition of a macro must appear in the source program before any
statements that invoke that macro.
o This restriction does not create any real inconvenience.
The design considered is for one-pass assembler. The data structures required are:
DEFTAB (Definition Table)
o Stores the macro definition including macro prototype and macro body
o Comment lines are omitted.
o References to the macro instruction parameters are converted to a positional
notation for efficiency in substituting arguments.
NAMTAB (Name Table)
o Stores macro names
o Serves as an index to DEFTAB
Pointers to the beginning and the end of the macro definition (DEFTAB)
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 114
ARGTAB (Argument Table)
o Stores the arguments according to their positions in the argument list.
o As the macro is expanded the arguments from the Argument table are
substituted for the corresponding parameters in the macro body.
o The figure below shows the different data structures described and their
relationship.
Fig 6.4: data structures and their relationship.
The above figure shows the portion of the contents of the table during the processing of the
program in page no. 3. In fig 4.4(a) definition of RDBUFF is stored in DEFTAB, with an
entry in NAMTAB having the pointers to the beginning and the end of the definition. The
arguments referred by the instructions are denoted by the their positional notations. For
example,
TD =X?1
The above instruction is to test the availability of the device whose number is given by the
parameter &INDEV. In the instruction this is replaced by its positional value? 1.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 115
Figure 4.4(b) shows the ARTAB as it would appear during expansion of the RDBUFF
statement as given below:
CLOOP RDBUFF F1, BUFFER, LENGTH
For the invocation of the macro RDBUFF, the first parameter is F1 (input device code),
second is BUFFER (indicating the address where the characters read are stored), and the third
is LENGTH (which indicates total length of the record to be read). When the ?n notation is
encountered in a line fro DEFTAB, a simple indexing operation supplies the proper argument
from ARGTAB.
The algorithm of the Macro processor is given below. This has the procedure DEFINE to
make the entry of macro name in the NAMTAB, Macro Prototype in DEFTAB. EXPAND is
called to set up the argument values in ARGTAB and expand a Macro Invocation statement.
Procedure GETLINE is called to get the next line to be processed either from the DEFTAB or
from the file itself.
When a macro definition is encountered it is entered in the DEFTAB. The normal approach is
to continue entering till MEND is encountered. If there is a program having a Macro defined
within another Macro.
While defining in the DEFTAB the very first MEND is taken as the end of the Macro
definition. This does not complete the definition as there is another outer Macro which
completes the definition of Macro as a whole. Therefore the DEFINE procedure keeps a
counter variable LEVEL.
Every time a Macro directive is encountered this counter is incremented by 1. The
moment the innermost Macro ends indicated by the directive MEND it starts decreasing the
value of the counter variable by one. The last MEND should make the counter value set to
zero. So when LEVEL becomes zero, the MEND corresponds to the original MACRO
directive.
Most macro processors allow thr definitions of the commonly used instructions to
appear in a standard system library, rather than in the source program. This makes the use of
macros convenient; definitions are retrieved from the library as they are needed during macro
processing.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 116
Fig 6.5: Macro library
Algorithms
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 117
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 118
Comparison of Macro Processor Design
One-pass algorithm
o Every macro must be defined before it is called
o One-pass processor can alternate between macro definition and macro
expansion
o Nested macro definitions are allowed but nested calls are not allowed.
Two-pass algorithm
o Pass1: Recognize macro definitions
o Pass2: Recognize macro calls
o Nested macro definitions are not allowed
6.2. Machine-independent Macro-Processor Features.
The design of macro processor doesnt depend on the architecture of the machine. We will be
studying some extended feature for this macro processor. These features are:
Concatenation of Macro Parameters
Generation of unique labels
Conditional Macro Expansion
Keyword Macro Parameters
6.2.1. Concatenation of unique labels:
Most macro processor allows parameters to be concatenated with other character
strings. Suppose that a program contains a series of variables named by the symbols
XA1, XA2, XA3,, another series of variables named XB1, XB2, XB3,, etc. If
similar processing is to be performed on each series of labels, the programmer might
put this as a macro instruction.
The parameter to such a macro instruction could specify the series of variables to be
operated on (A, B, etc.). The macro processor would use this parameter to construct
the symbols required in the macro expansion (XA1, Xb1, etc.).
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 119
Suppose that the parameter to such a macro instruction is named &ID. The body of
the macro definition might contain a statement like
LDA X&ID1
& is the starting character of the macro instruction; but the end of the parameter is not
marked. So in the case of &ID1, the macro processor could deduce the meaning that was
intended.
If the macro definition contains contain &ID and &ID1 as parameters, the situation
would be unavoidably ambiguous.
Most of the macro processors deal with this problem by providing a special
concatenation operator. In the SIC macro language, this operator is the character .
Thus the statement LDA X&ID1 can be written as
LDA X&ID
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 120
The above figure shows a macro definition that uses the concatenation operator as
previously described. The statement SUM A and SUM BETA shows the invocation
statements and the corresponding macro expansion.
6.2.2. Generation of Unique Labels
it is not possible to use labels for the instructions in the macro definition, since
every expansion of macro would include the label repeatedly which is not
allowed by the assembler.
This in turn forces us to use relative addressing in the jump instructions.
Instead we can use the technique of generating unique labels for every macro
invocation and expansion.
During macro expansion each $ will be replaced with $XX, where xx is a two-
character alphanumeric counter of the number of macro instructions
expansion.
For example,
XX = AA, AB, AC
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 121
This allows 1296 macro expansions in a single program.
The following program shows the macro definition with labels to the instruction.
The following figure shows the macro invocation and expansion first time.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 122
If the macro is invoked second time the labels may be expanded as $ABLOOP
$ABEXIT.
6.2.3. Conditional Macro Expansion
There are applications of macro processors that are not related to assemblers or assembler
programming.
Conditional assembly depends on parameters provides
MACRO &COND
..
IF (&COND NE )
part I
ELSE
part II
ENDIF
ENDM
Part I is expanded if condition part is true, otherwise part II is expanded. Compare operators:
NE, EQ, LE, GT.
Macro-Time Variables:
Macro-time variables (often called as SET Symbol) can be used to store working
values during the macro expansion. Any symbol that begins with symbol & and not a macro
instruction parameter is considered as macro-time variable. All such variables are initialized
to zero.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 123
Figure 4.5(a) gives the definition of the macro RDBUFF with the parameters
&INDEV, &BUFADR, &RECLTH, &EOR, &MAXLTH. According to the above program
if &EOR has any value, then &EORCK is set to 1 by using the directive SET, otherwise it
retains its default value 0.
Fig 6.9(b): Use of Macro-Time Variable with EOF being NOT NULL
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 124
Fig 6.9(c) Use of Macro-Time conditional statement with EOF being NULL
Fig 6.9(d) Use of Time-variable with EOF NOT NULL and MAXLENGTH being NULL
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 125
The above programs show the expansion of Macro invocation statements with different
values for the time variables. In figure 4.9(b) the &EOF value is NULL. When the macro
invocation is done, IF statement is executed, if it is true EORCK is set to 1, otherwise normal
execution of the other part of the program is continued.
The macro processor must maintain a symbol table that contains the value of all
macro-time variables used. Entries in this table are modified when SET statements are
processed. The table is used to look up the current value of the macro-time variable whenever
it is required.
When an IF statement is encountered during the expansion of a macro, the specified
Boolean expression is evaluated.
If the value of this expression TRUE,
The macro processor continues to process lines from the DEFTAB until it encounters
the ELSE or ENDIF statement.
If an ELSE is found, macro processor skips lines in DEFTAB until the next ENDIF.
Once it reaches ENDIF, it resumes expanding the macro in the usual way.
If the value of the expression is FALSE,
The macro processor skips ahead in DEFTAB until it encounters next ELSE or
ENDIF statement.
The macro processor then resumes normal macro expansion.
The macro-time IF-ELSE-ENDIF structure provides a mechanism for either generating(once)
or skipping selected statements in the macro body. There is another construct WHILE
statement which specifies that the following line until the next ENDW statement, are to be
generated repeatedly as long as a particular condition is true. The testing of this condition,
and the looping are done during the macro is under expansion. The example shown below
shows the usage of Macro-Time Looping statement.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 126
WHILE-ENDW structure
When an WHILE statement is encountered during the expansion of a macro, the
specified Boolean expression is evaluated.
TRUE
o The macro processor continues to process lines from DEFTAB until it
encounters the next ENDW statement.
o When ENDW is encountered, the macro processor returns to the preceding
WHILE, re-evaluates the Boolean expression, and takes action based on
the new value.
FALSE
o The macro processor skips ahead in DEFTAB until it finds the next ENDW
statement and then resumes normal macro expansion.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 127
6.2.4 Keyword Macro Parameters
All the macro instruction definitions used positional parameters. Parameters
and arguments are matched according to their positions in the macro prototype
and the macro invocation statement.
The programmer needs to be careful while specifying the arguments. If an
argument is to be omitted the macro invocation statement must contain a null
argument mentioned with two commas.
Positional parameters are suitable for the macro invocation. But if the macro
invocation has large number of parameters, and if only few of the values need
to be used in a typical invocation, a different type of parameter specification is
required
Ex: XXX MACRO &P1, &P2, ., &P20, .
XXX A1, A2,,,,,,,,,,,,A20,..
Null arguments
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 128
Keyword parameters
Each argument value is written with a keyword that names the corresponding
parameter.
Arguments may appear in any order.
Null arguments no longer need to be used.
Ex: XXX P1=A1, P2=A2, P20=A20.
It is easier to read and much less error-prone than the positional method.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 129
Fig 6.10 Example showing the usage of Keyword Parameter
6.3 Macro Processor Design Options
6.3.1 Recursive Macro Expansion
We have seen an example of the definition of one macro instruction by another. But we have
not dealt with the invocation of one macro by another. The following example shows the
invocation of one macro by another macro.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 130
Problem of Recursive Expansion
Previous macro processor design cannot handle such kind of recursive macro
invocation and expansion
o The procedure EXPAND would be called recursively, thus the invocation
arguments in the ARGTAB will be overwritten.
o The Boolean variable EXPANDING would be set to FALSE when the inner
macro expansion is finished, i.e., the macro process would forget that it had
been in the middle of expanding an outer macro.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 131
Solutions
o Write the macro processor in a programming language that allows recursive
calls, thus local variables will be retained.
o If you are writing in a language without recursion support, use a stack to take
care of pushing and popping local variables and return addresses.
The procedure EXPAND would be called when the macro was recognized. The arguments
from the macro invocation would be entered into ARGTAB as follows:
Parameter Value
1 BUFFER
2 LENGTH
3 F1
4 (unused)
- -
The Boolean variable EXPANDING would be set to TRUE, and expansion of the macro
invocation statement would begin. The processing would proceed normally until statement
invoking RDCHAR is processed. This time, ARGTAB would look like
Parameter
Value
1 F1
2 (Unused)
-- --
At the expansion, when the end of RDCHAR is recognized, EXPANDING would be
set to FALSE. Thus the macro processor would forget that it had been in the middle of
expanding a macro when it encountered the RDCHAR statement. In addition, the arguments
from the original macro invocation (RDBUFF) would be lost because the value in ARGTAB
was overwritten with the arguments from the invocation of RDCHAR.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 132
6.3.2 General-Purpose Macro Processors
Macro processors that do not dependent on any particular programming language, but
can be used with a variety of different languages
Pros
o Programmers do not need to learn many macro languages.
o Although its development costs are somewhat greater than those for a
language specific macro processor, this expense does not need to be repeated
for each language, thus save substantial overall cost.
Cons
o Large number of details must be dealt with in a real programming language
Situations in which normal macro parameter substitution should not
occur, e.g., comments.
Facilities for grouping together terms, expressions, or statements
Tokens, e.g., identifiers, constants, operators, keywords
Syntax had better be consistent with the source programming language
6.3.3Macro Processing within Language Translators
The macro processors we discussed are called Preprocessors.
o Process macro definitions
o Expand macro invocations
o Produce an expanded version of the source program, which is then used as input
to an assembler or compiler
You may also combine the macro processing functions with the language translator:
o Line-by-line macro processor
o Integrated macro processor
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 133
6.4 Line-by-Line Macro Processor
Used as a sort of input routine for the assembler or compiler
o Read source program
o Process macro definitions and expand macro invocations
o Pass output lines to the assembler or compiler
Benefits
o Avoid making an extra pass over the source program.
o Data structures required by the macro processor and the language translator can
be combined (e.g., OPTAB and NAMTAB)
o Utility subroutines can be used by both macro processor and the language
translator.
Scanning input lines
Searching tables
Data format conversion
o It is easier to give diagnostic messages related to the source statements
Integrated Macro Processor
An integrated macro processor can potentially make use of any information about the
source program that is extracted by the language translator.
o Ex (blanks are not significant in FORTRAN)
DO 100 I = 1,20
a DO statement
DO 100 I = 1
An assignment statement
DO100I: variable (blanks are not significant in FORTRAN)
An integrated macro processor can support macro instructions that depend upon the
context in which they occur.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 134
RECOMMENDED QUESTIONS:
1.explain the data structures of macroprocessors?(8)
2.Explain the following (6)
a. NAMTAB
b. DEFTAB
c. ARGTAB
3. Write the algorithm for a one pass macro processor. (8)
4.Explain the following (8)
a. Conditional macro expansion
b.Concatenation of macro parameters
c.Keyword macro parameters
d.Generation of unique labels.
5.Explain Recursive Macro Expansion. (7)
6.Explain general purpose macro processors. (6)
7.Explain the following (8)
a. MASM macro processor
b. ANSI C macro processor
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 135
Unit 7
LEX AND YACC-1
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.
7.1 Lex and Yacc
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 turns the user's expressions and actions (called source in this memo) into the host
general-purpose language; the generated program is named yylex. The yylex program will
recognize expressions in a stream (called input in this memo) and perform the specified
actions for each expression as it is detected. See Figure 1.
+-------+
Source -> | Lex | -> yylex
+-------+
+-------+
Input -> | yylex | -> Output
+-------+
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 136
7.2 A YACC Parser
The structure of a lex file is intentionally similar to that of a yacc file; files are divided up
into three sections, separated by lines that contain only two percent signs, as follows:
Definition section
%%
Rules section
%%
C code section
The definition section is the place to define macros and to import header files written
in C. It is also possible to write any C code here, which will be copied verbatim into
the generated source file.
The rules section is the most important section; it associates patterns with C
statements. Patterns are simply regular expressions. When the lexer sees some text in
the input matching a given pattern, it executes the associated C code. This is the basis
of how lex operates.
The C code section contains C statements and functions that are copied verbatim to
the generated source file. These statements presumably contain code called by the
rules in the rules section. In large programs it is more convenient to place this code in
a separate file and link it in at compile time.
Example:
/*** Definition section ***/
%{
/* C code to be copied verbatim */
#include <stdio.h>
%}
/* This tells lex to read only one input file */
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 137
%%
/*** 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);
}
. { /* Ignore all other characters. */ }
%%
/*** C Code section ***/
int main(void)
{
/* Call the lexer, then quit. */
yylex();
return 0;
REGULAR EXPRESSIONS:
Regular expression specifies a set of strings to be matched. It contains text characters and
operator characters The letters of the alphabet and the digits are always text characters; thus
the regular expression integer matches the string integer wherever it appears and the
expression
a57D
looks for the string a57D.
Operators:
The operator characters are
" \ [ ] ^ - ? . * + | ( ) $ / { } % <>
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 138
and if they are to be used as text characters, an escape should be used. The quotation mark
operator (") indicates that whatever is contained between a pair of quotes is to be taken as
text characters.
Thus
xyz"++"
matches the string xyz++ when it appears.
Note that a part of a string may be quoted. It is harmless but unnecessary to quote an
ordinary text character; the expression
"xyz++"
is the same as the one above. Thus by quoting every non-alphanumeric character being used
as a text character, the user can avoid remembering the list above of current operator
characters, and is safe should further extensions to Lex lengthen the list.
An operator character may also be turned into a text character by preceding it with
\ as in
xyz\+\+
which is another, less readable, equivalent of the above expressions.
Another use of the quoting mechanism is to get a blank into an expression; blanks or tabs end
a rule. Any blank character not contained within []must be quoted.
Several normal C escapes with \ are recognized: \n is newline, \t is tab, and \b is
backspace. To enter \ itself, use \\. Since newline is illegal in an expression, \n must
be used; it is not required to escape tab and backspace. Every character but blank,
tab, newline and the list above is always a text character.
Character classes. Classes of characters can be specified using the operator pair [].
The construction [abc] matches a single character, which may be a, b, or c. Within
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 139
square brackets, most operator meanings are ignored. Only three characters are
special: these are \ - and ^. The - character indicates ranges.
For example:
[a-z0-9<>_]indicates the character class containing all the lower case letters, the digits, the
angle brackets, and underline. Ranges may be given in either order.
Using - between any pair of characters which are not both upper case letters, both
lower case letters, or both digits is implementation dependent and will get a warning
message. If it is desired to include the character - in a character class, it should be first
or last; thus
[-+0-9]
matches all the digits and the two signs.
In character classes, the ^ operator must appear as the first character after the left bracket; it
indicates that the resulting string is to be complemented with respect to the computer
character set. Thus , [^abc] matches all characters except a, b, or c, including all special
or control characters
or [^a-zA-Z]
is any character which is not a letter. The \ character provides the usual escapes within
character class brackets.
Optional expressions.: The operator ? indicates an optional element of an expression.
Thus ab?c
matches either ac or abc.
Repeated expressions: Repetitions of classes are indicated by the operators * and +.
Ex: a*
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 140
is any number of consecutive a characters, including zero, while a+ is one or more instances
of a.
For example [a-z]+
is all strings of lower case letters.
Defining regular expressions in Lex :
Character Meaning
A-Z, 0-9, a-z Characters and numbers that form part of the pattern.
. Matches any character except \n.
- Used to denote range. Example: A-Z implies all characters from A to Z.
[ ] A character class. Matches any character in the brackets. If the first
character is ^ then it indicates a negation pattern. Example: [abC]
matches either of a, b, and C.
* Match zero or more occurrences of the preceding pattern.
+ Matches one or more occurrences of the preceding pattern.
? Matches zero or one occurrences of the preceding pattern.
$ Matches end of line as the last character of the pattern.
{ } Indicates how many times a pattern can be present. Example: A{1,3}
implies one or three occurrences of A may be present.
\ Used to escape meta characters. Also used to remove the special meaning
of characters as defined in this table.
^ Negation.
| Logical OR between expressions.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 141
"<some symbols>" Literal meanings of characters. Meta characters hold.
/ Look ahead. Matches the preceding pattern only if followed by the
succeeding expression. Example: A0/1 matches A0 only if A01 is the
input.
( ) Groups a series of regular expressions.
Examples of regular expressions:
Regular expression Meaning
joke[rs] Matches either jokes or joker.
A{1,2}shis+ Matches AAshis, Ashis, AAshi, Ashi.
(A[b-e])+ Matches zero or one occurrences of A followed by any character from
b to e.
Tokens in Lex are declared like variable names in C. Every token has an associated expression.
(Examples of tokens and expression are given in the following table.) Using the examples in our
tables, we'll build a word-counting program. Our first task will be to show how tokens are declared.
Examples of token declarations
Token Associated expression Meaning
number ([0-9])+ 1 or more occurrences of a digit
chars [A-Za-z] Any character
blank " " A blank space
word (chars)+ 1 or more occurrences of chars
variable (chars)+(number)*(chars)*( number)*
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 142
7.3. USING LEX:
If lex.l is the file containing the lex specification, the C source for the lexical analyzer is
produced by running lex with the following command:
lex lex.l
lex produces a C file called lex.yy.c.
Options
There are several options available with the lex command. If you use one or more of them,
place them between the command name lex and the filename argument.
The -t option sends lex's output to the standard output rather than to the file lex.yy.c.
The -v option prints out a small set of statistics describing the so-called finite automata that
lex produces with the C program lex.yy.c.
WORD COUNTING PROGRAM
In this section we can add C variable declarations. We will declare an integer variable here
for our word-counting program that holds the number of words counted by the program.
We'll also perform token declarations of Lex.
Declarations for the word-counting program
%{
int wordCount = 0;
%}
chars [A-za-z\_\'\.\"]
numbers ([0-9])+
delim [" "\n\t]
whitespace {delim}+
words {chars}+
%%
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 143
The double percent sign implies the end of this section and the beginning of the second of the
three sections in Lex programming.
Lex rules for matching patterns
Let's look at the Lex rules for describing the token that we want to match. (We'll use C to
define what to do when a token is matched.) Continuing with our word-counting program,
here are the rules for matching tokens.
Lex rules for the word-counting program
{words} { wordCount++; /*
increase the word count by one*/ }
{whitespace} { /* do
nothing*/ }
{numbers} { /* one may
want to add some processing here*/ }
%%
C code
The third and final section of programming in Lex covers C function declarations (and
occasionally the main function) Note that this section has to include the yywrap() function.
Lex has a set of functions and variables that are available to the user. One of them is yywrap.
Typically, yywrap() is defined as shown in the example below.
C code section for the word-counting program
void main()
{
yylex(); /* start the analysis*/
printf(" No of words:
%d\n", wordCount);
}
int yywrap()
{
return 1;
}
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 144
LEXER
lexical analysis is the process of converting a sequence of characters into a sequence of
tokens. A program or function which performs lexical analysis is called a lexical analyzer,
lexer or scanner. A lexer often exists as a single function which is called by a parser or
another function
Token
A token is a string of characters, categorized according to the rules as a symbol (e.g.
IDENTIFIER, NUMBER, COMMA, etc.). The process of forming tokens from an input
stream of characters is called tokenization and the lexer categorizes them according to a
symbol type. A token can look like anything that is useful for processing an input text stream
or text file.
A lexical analyzer generally does nothing with combinations of tokens, a task left for a parser.
For example, a typical lexical analyzer recognizes parenthesis as tokens, but does nothing to
ensure that each '(' is matched with a ')'.
Consider this expression in the C programming language:
sum=3+2;
Tokenized in the following table:
lexeme token type
sum Identifier
= Assignment operator
3 Number
+ Addition operator
2 Number
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 145
; End of statement
Tokens are frequently defined by regular expressions, which are understood by a lexical
analyzer generator such as lex. The lexical analyzer (either generated automatically by a tool
like lex, or hand-crafted) reads in a stream of characters, identifies the lexemes in the stream,
and categorizes them into tokens. This is called "tokenizing." If the lexer finds an invalid
token, it will report an error.
Following tokenizing is parsing. From there, the interpreted data may be loaded into data
structures for general use, interpretation, or compiling.
Examples:
1. Write a Lex source program to copy an input file while adding 3 to every positive number
divisible by 7.
%%
int k;
[0-9]+ {
k = atoi(yytext);
if (k%7 == 0)
printf("%d", k+3);
else
printf("%d",k);
}
to do just that. The rule [0-9]+ recognizes strings of digits; atoi converts the digits to binary and
stores the result in k. The operator % (remainder) is used to check whether k is divisible by 7; if it is,
it is incremented by 3 as it is written out. It may be objected that this program will alter such input
items as 49.63 or X7. Furthermore, it increments the absolute value of all negative numbers divisible
by 7. To avoid this, just add a few more rules after the active one, as here:
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 146
%%
int k;
-?[0-9]+ {
k = atoi(yytext);
printf("%d",
k%7 == 0 ? k+3 : k);
}
-?[0-9.]+ ECHO;
[A-Za-z][A-Za-z0-9]+ ECHO;
Numerical strings containing a .'' or preceded by a letter will be picked up by one of the last
two rules, and not changed. The if-else has been replaced by a C conditional expression to save
space; the form a?b:c means if a then b else c''.
2. Write a Lex program that histograms the lengths of words, where a word is defined as a
string of letters.
int lengs[100];
%%
[a-z]+ lengs[yyleng]++;
. |
\n ;
%%
yywrap()
{
int i;
printf("Length No. words\n");
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 147
for(i=0; i<100; i++)
if (lengs[i] > 0)
printf("%5d%10d\n",i,lengs[i]);
return(1);
}
3.. Write a lex program to find the number of vowels and consonants.
%{
/* to find vowels and consonents*/
int vowels = 0;
int consonents = 0;
%}
%%
[ \t\n]+
[aeiouAEIOU] vowels++;
[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ] consonents++;
.
%%
main()
{
yylex();
printf(" The number of vowels = %d\n", vowels);
printf(" number of consonents = %d \n", consonents);
return(0);
}
The same program can be executed by giving alternative grammar. It is as follows:
Here a file is opened which is given as a argument and reads to text and counts the number of
vowels and consonants.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 148
%{
unsigned int vowelcount=0;
unsigned int consocount=0;
%}
vowel [aeiouAEIOU]
consonant [bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]
eol \n
%%
{vowel} { vowelcount++;}
{consonant} { consocount++; }
%%
main(int argc,char *argv[])
{
if(argc > 1)
{
FILE *fp;
fp=fopen(argv[1],"r");
if(!fp)
{
fprintf(stderr,"could not open %s\n",argv[1]);
exit(1);
}
yyin=fp;
}
yylex();
printf(" vowelcount=%u consonantcount=%u\n ",vowelcount,consocount);
return(0);
}
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 149
4. Write a Lex program to count the number of words, characters, blanks and lines in a
given text.
%{
unsigned int charcount=0;
int wordcount=0;
int linecount=0;
int blankcount =0;
%}
word[^ \t\n]+
eol \n
%%
[ ] blankcount++;
{word} { wordcount++; charcount+=yyleng;}
{eol} {charcount++; linecount++;}
. { ECHO; charcount++;}
%%
main(argc, argv)
int argc;
char **argv;
{
if(argc > 1)
{
FILE *file;
file = fopen(argv[1],"r");
if(!file)
{
fprintf(stderr, "could not open %s\n", argv[1]);
exit(1);
}
yyin = file;
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 150
yylex();
printf("\nThe number of characters = %u\n", charcount);
printf("The number of wordcount = %u\n", wordcount);
printf("The number of linecount = %u\n", linecount);
printf("The number of blankcount = %u\n", blankcount);
return(0);
}
else
printf(" Enter the file name along with the program \n");
}
5. Write a lex program to find the number of positive integer, negative integer, positive
floating positive number and negative floating point number.
%{
int posnum = 0;
int negnum = 0;
int posflo = 0;
int negflo = 0;
%}
%%
[\n\t ];
([0-9]+) {posnum++;}
-?([0-9]+) {negnum++; }
([0-9]*\.[0-9]+) { posflo++; }
-?([0-9]*\.[0-9]+) { negflo++; }
. ECHO;
%%
main()
{
yylex();
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 151
printf("Number of positive numbers = %d\n", posnum);
printf("number of negative numbers = %d\n", negnum);
printf("number of floting positive number = %d\n", posflo);
printf("number of floating negative number = %d\n", negflo);
}
6. Write a lex program to find the given c program has right number of brackets. Count
the number of comments. Check for while loop.
%{
/* find main, comments, {, (, ), } */
int comments=0;
int opbr=0;
int clbr=0;
int opfl=0;
int clfl=0;
int j=0;
int k=0;
%}
%%
"main()" j=1;
"/*"[ \t].*[ \t]"*/" comments++;
"while("[0-9a-zA-Z]*")"[ \t]*\n"{"[ \t]*.*"}" k=1;
^[ \t]*"{"[ \t]*\n
^[ \t]*"}" k=1;
"(" opbr++;
")" clbr++;
"{" opfl++;
"}" clfl++;
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 152
[^ \t\n]+
. ECHO;
%%
main(argc, argv)
int argc;
char *argv[];
{
if (argc > 1)
{
FILE *file;
file = fopen(argv[1], "r");
if (!file)
{
printf("error opeing a file \n");
exit(1);
}
yyin = file;
}
yylex();
if(opbr != clbr)
printf("open brackets is not equal to close brackets\n");
if(opfl != clfl)
printf("open flower brackets is not equal to close flower brackets\n");
printf(" the number of comments = %d\n",comments);
if (!j)
printf("there is no main function \n");
if (k)
printf("there is loop\n");
else printf("there is no valid for loop\n");
return(0);
}
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 153
6. Write a lex program to replace scanf with READ and printf with WRITE statement
also find the number of scanf and printf.
%{
int pc=0,sc=0;
%}
%%
printf fprintf(yyout,"WRITE");pc++;
scanf fprintf(yyout,"READ");sc++;
. ECHO;
%%
main(int argc,char* argv[])
{
if(argc!=3)
{
printf("\nUsage: %s <src><dest>\n",argv[0]);
return;
}
yyin=fopen(argv[1],"r");
yyout=fopen(argv[2],"w");
yylex();
printf("\nno. of printfs:%d\nno. of scanfs:%d\n",pc,sc);
}
7. Write a lex program to find whether the given expression is valid.
%{
#include <stdio.h>
int valid=0,ctr=0,oc = 0;
%}
NUM [0-9]+
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 154
OP [+*/-]
%%
{NUM}({OP}{NUM})+ {
valid = 1;
for(ctr = 0;yytext[ctr];ctr++)
{
switch(yytext[ctr])
{
case '+':
case '-':
case '*':
case '/': oc++;
}
}
}
{NUM}\n {printf("\nOnly a number.");}
\n { if(valid) printf("valid \n operatorcount = %d",oc);
else printf("Invalid");
valid = oc = 0;ctr=0;
}
%%
main()
{
yylex();
}
/* Another solution for the same problem */
%{
int oprc=0,digc=0,top=-1,flag=0;
char stack[20];
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 155
%}
digit [0-9]+
opr [+*/-]
%%
[ \n\t]+
['('] {stack[++top]='(';}
[')'] {flag=1;
if(stack[top]=='('&&(top!=-1))
top--;
else
{
printf("\n Invalid expression\n");
exit(0);
}
}
{digit} {digc++;}
{opr}/['('] { oprc++; printf("%s",yytext);}
{opr}/{digit} {oprc++; printf("%s",yytext);}
. {printf("Invalid "); exit(0);}
%%
main()
{
yylex();
if((digc==oprc+1||digc==oprc) && top==-1)
{
printf("VALID");
printf("\n oprc=%d\n digc=%d\n",oprc,digc);
}
else
printf("INVALID");
}
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 156
8.Write a lex program to find the given sentence is simple or compound.
%{
int flag=0;
%}
%%
(" "[aA][nN][dD]" ")|(" "[oO][rR]" ")|(" "[bB][uU][tT]" ") flag=1;
. ;
%%
main()
{yylex();
if (flag==1)
printf("COMPOUND SENTENCE \n");
else
printf("SIMPLE SENTENCE \n");
}
9. Write a lex program to find the number of valid identifiers.
%{
int count=0;
%}
%%
(" int ")|(" float ")|(" double ")|(" char ")
{
int ch; ch = input();
for(;;)
{
if (ch==',') {count++;}
else
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 157
if(ch==';') {break;}
ch = input();
}
count++;
}
%%
main(int argc,char *argv[])
{
yyin=fopen(argv[1],"r");
yylex();
printf("the no of identifiers used is %d\n",count);
}
RECOMMENDED QUESTIONS:
1. write the specification of lex with an example? (10)
2. what is regular expressions? With examples explain? (8)
3. write a lex program to count the no of words , lines , space, characters? (8)
4. write a lex program to count the no of vowels and consonants? (8)
5. what is lexer- parser communication? Explain? (5)
6. write a program to count no of words by the method of substitution? (7)
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 158
UNIT - 8
LEX AND YACC 2
8.1 USING YACC
Yacc provides a general tool for describing the input to a computer program. The Yacc user
specifies the structures of his input, together with code to be invoked as each such structure is
recognized. Yacc turns such a specification into a subroutine that handles the input process;
frequently, it is convenient and appropriate to have most of the flow of control in the user's
application handled by this subroutine.
The input subroutine produced by Yacc calls a user-supplied routine to return the next
basic input item. Thus, the user can specify his input in terms of individual input characters
or in terms of higher level constructs such as names and numbers. The user supplied routine
may also handle idiomatic features such as comment and continuation conventions, which
typically defy easy grammatical specification. Yacc is written in portable C.
Yacc provides a general tool for imposing structure on the input to a computer
program. User prepares a specification of the input process; this includes rules describing the
input structure, code to be invoked when these rules are recognized, and a low-level routine
to do the basic input.
Grammars:
The heart of the input specification is a collection of grammar rules. Each rule
describes an allowable structure and gives it a name. For example, one grammar rule might
be
date : month_name day ',' year
Here, date, month_name, day, and year represent structures of interest in the input
process; presumably, month_name, day, and year are defined elsewhere. The comma ``,'' is
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 159
enclosed in single quotes; this implies that the comma is to appear literally in the input. The
colon and semicolon merely serve as punctuation in the rule, and have no significance in
controlling the input. Thus, with proper definitions, the input
July 4, 1776
might be matched by the above rule.
An important part of the input process is carried out by the lexical analyzer. This
user routine reads the input stream, recognizing the lower level structures, and communicates
these tokens to the parser. For historical reasons, a structure recognized by the lexical
analyzer is called a terminal symbol, while the structure recognized by the parser is called a
nonterminal symbol. To avoid confusion, terminal symbols will usually be referred to as
tokens.
Basic Specifications:
Every specification file consists of three sections: the declarations, (grammar) rules,
and programs. The sections are separated by double percent ``%%'' marks. (The percent
``%'' is generally used in Yacc specifications as an escape character.)
In other words, a full specification file looks like
declarations
%%
rules
%%
programs
The declaration section may be empty. Moreover, if the programs section is omitted, the
second %% mark may be omitted also; thus, the smallest legal Yacc specification is
%%
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 160
rules
Blanks, tabs, and newlines are ignored except that they may not appear in names or
multi-character reserved symbols. Comments may appear wherever a name is legal; they are
enclosed in /* . . . */, as in C and PL/I.
The rules section is made up of one or more grammar rules.
A grammar rule has the form:
A:BODY;
A represents a non terminal name, and BODY represents a sequence of zero or more
names and literals. The colon and the semicolon are Yacc punctuation. Names may be of
arbitrary length, and may be made up of letters, dot ``.'', underscore ``_'', and non-initial
digits. Upper and lower case letters are distinct. The names used in the body of a grammar
rule may represent tokens or nonterminal symbols.
8.2 AYACC PARSER
A literal consists of a character enclosed in single quotes ``'''. As in C, the backslash ``\'' is
an escape character within literals, and all the C escapes are recognized. Thus
'\n' newline
'\r' return
'\'' single quote ``'''
'\\' backslash ``\''
'\t' tab
'\b' backspace
'\f' form feed
'\xxx' ``xxx'' in octal
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 161
For a number of technical reasons, the NUL character ('\0' or 0) should never be used in
grammar rules.
If there are several grammar rules with the same left hand side, the vertical bar ``|''
can be used to avoid rewriting the left hand side. In addition, the semicolon at the end of a
rule can be dropped before a vertical bar. Thus the grammar rules
A : B C D ;
A : E F ;
A : G ;
can be given to Yacc as
A : B C D
| E F
| G
;
It is not necessary that all grammar rules with the same left side appear together in
the grammar rules section, although it makes the input much more readable, and
easier to change.
If a nonterminal symbol matches the empty string, this can be indicated in the
obvious way:
empty : ;
Names representing tokens must be declared; this is most simply done by writing
%token name1, name2 . . .
In the declarations section, Every name not defined in the declarations section is
assumed to represent a non-terminal symbol. Every non-terminal symbol must appear on
the left side of at least one rule.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 162
Of all the nonterminal symbols, one, called the start symbol, has particular
importance. The parser is designed to recognize the start symbol; thus, this symbol
represents the largest, most general structure described by the grammar rules. By
default, the start symbol is taken to be the left hand side of the first grammar rule in
the rules section.
It is possible, and in fact desirable, to declare the start symbol explicitly in the
declarations section using the % start keyword:
%start symbol
The end of the input to the parser is signaled by a special token, called the endmarker.
If the tokens up to, but not including, the endmarker form a structure which matches
the start symbol, the parser function returns to its caller after the end-marker is seen;
it accepts the input. If the endmarker is seen in any other context, it is an error.
It is the job of the user-supplied lexical analyzer to return the endmarker when
appropriate; see section 3, below. Usually the endmarker represents some reasonably
obvious I/O status, such as ``end-of-file'' or ``end-of-record''.
Actions:
With each grammar rule, the user may associate actions to be Yacc: Yet Another
Compiler-Compiler performed each time the rule is recognized in the input process.
These actions may return values, and may obtain the values returned by previous
actions. Moreover, the lexical analyzer can return values for tokens, if desired.
An action is an arbitrary C statement, and as such can do input and output, call
subprograms, and alter external vectors and variables. An action is specified by one
or more statements, enclosed in curly braces ``{'' and ``}''. For example,
A : '(' B ')'
{ hello( 1, "abc" ); }
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 163
and
XXX : YYY ZZZ
{ printf("a message\n");
flag = 25; }
are grammar rules with actions.
To facilitate easy communication between the actions and the parser, the action
statements are altered slightly. The symbol ``dollar sign'' ``$'' is used as a signal to Yacc in
this context.
To return a value, the action normally sets the pseudo-variable ``$$'' to some value.
For example, an action that does nothing but return the value 1 is
{ $$ = 1; }
To obtain the values returned by previous actions and the lexical analyzer, the action
may use the pseudo-variables $1, $2, . . ., which refer to the values returned by the
components of the right side of a rule, reading from left to right. Thus, if the rule is
A : B C D ;
for example, then $2 has the value returned by C, and $3 the value returned by D.
As a more concrete example, consider the rule
expr : '(' expr ')' ;
The value returned by this rule is usually the value of the expr in parentheses. This
can be indicated by
expr : '(' expr ')' { $$ = $2 ; }
By default, the value of a rule is the value of the first element in it ($1). Thus, grammar
rules of the form
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 164
A : B ;
frequently need not have an explicit action.
In the examples above, all the actions came at the end of their rules. Sometimes, it is
desirable to get control before a rule is fully parsed. Yacc permits an action to be written in
the middle of a rule as well as at the end.
The user may define other variables to be used by the actions. Declarations and
definitions can appear in the declarations section, enclosed in the marks ``%{'' and ``%}''.
These declarations and definitions have global scope, so they are known to the action
statements and the lexical analyzer. For example,
%{ int variable = 0; %}
could be placed in the declarations section, making variable accessible to all of the
actions. The Yacc parser uses only names beginning in ``yy''; the user should avoid such
names.
In these examples, all the values are integers.
8.3 Lexer
The user must supply a lexical analyzer to read the input stream and communicate
tokens (with values, if desired) to the parser. The lexical analyzer is an integer-valued
function called yylex. The user must supply a lexical analyzer to read the input stream and
communicate tokens (with values, if desired) to the parser. The lexical analyzer is an
integer-valued function called yylex. The parser and the lexical analyzer must agree on these
token numbers in order for communication between them to take place. The numbers may be
chosen by Yacc, or chosen by the user. In either case, the ``# define'' mechanism of C is used
to allow the lexical analyzer to return these numbers symbolically. For example, suppose
that the token name DIGIT has been defined in the declarations section of the Yacc
specification file. The relevant portion of the lexical analyzer might look like:
yylex(){
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 165
extern int yylval;
int c;
. . .
c = getchar();
. . .
switch( c ) {
. . .
case '0':
case '1':
. . .
case '9':
yylval = c-'0';
return( DIGIT );
. . .
}
. . .
The intent is to return a token number of DIGIT, and a value equal to the numerical
value of the digit. Provided that the lexical analyzer code is placed in the programs
section of the specification file, the identifier DIGIT will be defined as the token
number associated with the token DIGIT.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 166
This mechanism leads to clear, easily modified lexical analyzers; the only pitfall
is the need to avoid using any token names in the grammar that are reserved or
significant in C or the parser;
For example, the use of token names if or while will almost certainly cause
severe difficulties when the lexical analyzer is compiled. The token name error is
reserved for error handling, and should not be used naively.
The token numbers may be chosen by Yacc or by the user. In the default situation,
the numbers are chosen by Yacc.
The default token number for a literal character is the numerical value of the character
in the local character set. Other names are assigned token numbers starting at 257.
8.4Compiling and running a SimpleParser:
Yacc turns the specification file into a C program, which parses the input according to the
specification given. The algorithm used to go from the specification to the parser is complex.
however, is relatively simple, and understanding how it works, while not strictly necessary,
will nevertheless make treatment of error recovery and ambiguities much more
comprehensible.
The parser produced by Yacc consists of a finite state machine with a stack. The
parser is also capable of reading and remembering the next input token (called the lookahead
token). The current state is always the one on the top of the stack. The states of the finite
state machine are given small integer labels; initially, the machine is in state 0, the stack
contains only state 0, and no lookahead token has been read.
The machine has only four actions available to it, called shift, reduce, accept, and
error. A move of the parser is done as follows:
1. Based on its current state, the parser decides whether it needs a lookahead token to
decide what action should be done; if it needs one, and does not have one, it calls yylex to
obtain the next token.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 167
2. Using the current state, and the lookahead token if needed, the parser decides on its next
action, and carries it out. This may result in states being pushed onto the stack, or popped off
the stack, and in the lookahead token being processed or left alone.
The shift action is the most common action the parser takes. Whenever a shift action is
taken, there is always a lookahead token. For example, in state 56 there may be an action:
IF shift 34
which says, in state 56, if the lookahead token is IF, the current state (56) is pushed
down on the stack, and state 34 becomes the current state (on the top of the stack). The look
ahead token is cleared.
The reduce action keeps the stack from growing without bounds. Reduce actions are
appropriate when the parser has seen the right hand side of a grammar rule, and is
prepared to announce that it has seen an instance of the rule, replacing the right hand side by
the left hand side. It may be necessary to consult the lookahead token to decide whether to
reduce, but usually it is not; in fact, the default action (represented by a ``.'') is often a
reduce action.
Reduce actions are associated with individual grammar rules. Grammar rules are
also given small integer numbers, leading to some confusion. The action
reduce 18
refers to grammar rule 18, while the action
IF shift 34
refers to state 34. Suppose the rule being reduced is
A : x y z ;
The reduce action depends on the left hand symbol (A in this case), and the number
of symbols on the right hand side (three in this case). To reduce, first pop off the top three
states from the stack (In general, the number of states popped equals the number of symbols
on the right side of the rule).
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 168
In effect, these states were the ones put on the stack while recognizing x, y, and z, and no
longer serve any useful purpose. After popping these states, a state is uncovered which was
the state the parser was in before beginning to process the rule. Using thisuncovered state,
and the symbol on the left side of the rule, perform what is in effect a shift of A. A new state
is obtained, pushed onto the stack, and parsing continues.
The reduce action is also important in the treatment of user-supplied actions and values.
When a rule is reduced, the code supplied with the rule is executed before the stack is
adjusted. In addition to the stack holding the states, another stack, running in parallel
with it, holds the values returnedfrom the lexical analyzer and the actions. When a shift
takes place, the external variable yylval is copied onto the value stack. After the
return from the user code, the reduction is carried out. When the goto action is done, the
external variable yyval is copied onto the value stack. The pseudo-variables $1, $2,
etc., refer to the value stack.
8.5 Arithmetic Expressions and Ambiguity:
A set of grammar rules is ambiguous if there is some input string that can be structured in
two or more different ways. For example, the grammar rule
expr : expr '-' expr
is a natural way of expressing the fact that one way of forming an arithmetic expression is
to put two other expressions together with a minus sign between them. Unfortunately, this
grammar rule does not completely specify the way that all complex inputs should be
structured. For example, if the input is
expr - expr - expr
the rule allows this input to be structured as either
( expr - expr ) - expr
or as
expr - ( expr - expr )
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 169
(The first is called left association, the second right association).
Yacc detects such ambiguities when it is attempting to build the parser. It is instructive to
consider the problem that confronts the parser when it is given an input such as
expr - expr - expr
When the parser has read the second expr, the input that it has seen:
expr - expr
matches the right side of the grammar rule above. The parser could reduce the input by
applying this rule; after applying the rule; the input is reduced to expr (the left side of the
rule). The parser would then read the final part of the input:
- expr
and again reduce. The effect of this is to take the left associative interpretation.
Alternatively, when the parser has seen
expr - expr
it could defer the immediate application of the rule, and continue reading the input until it
had seen
expr - expr - expr
It could then apply the rule to the rightmost three symbols, reducing them to expr and leaving
expr - expr
Now the rule can be reduced once more; the effect is to take the right associative
interpretation. Thus, having read
expr - expr
The parser can do two legal things, a shift or a reduction, and has no way of
deciding between them. This is called a shift / reduce conflict. It may also happen that the
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 170
parser has a choice of two legal reductions; this is called a reduce / reduce conflict. Note that
there are never any ``Shift/shift'' conflicts.
When there are shift/reduce or reduce/reduce conflicts, Yacc still produces a parser.
It does this by selecting one of the valid steps wherever it has a choice. A rule describing
which choice to make in a given situation is called a disambiguating rule.
Yacc invokes two disambiguating rules by default:
1. In a shift/reduce conflict, the default is to do the shift.
2. In a reduce/reduce conflict, the default is to reduce by the earlier grammar rule (in the
input sequence).
Rule 1 implies that reductions are deferred whenever there is a choice, in favor of
shifts. Rule 2 gives the user rather crude control over the behavior of the parser in this
situation, but reduce/reduce conflicts should be avoided whenever possible.
Yacc always reports the number of shift/reduce and reduce/reduce conflicts resolved
by Rule 1 and Rule 2.
As an example of the power of disambiguating rules, consider a fragment from a
programming language involving an ``if-then-else'' construction:
stat : IF '(' cond ')' stat
| IF '(' cond ')' stat ELSE stat
;
In these rules, IF and ELSE are tokens, cond is a nonterminal symbol describing
conditional (logical) expressions, and stat is a nonterminal symbol describing statements.
The first rule will be called the simple-if rule, and the second the if-else rule.
These two rules form an ambiguous construction, since input of the form
EXAMPLE:
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 171
IF ( C1 ) IF ( C2 ) S1 ELSE S2
can be structured according to these rules in two ways:
IF ( C1 ) {
IF ( C2 ) S1
}
ELSE S2
or
IF ( C1 ) {
IF ( C2 ) S1
ELSE S2
}
The second interpretation is the one given in most programming languages having
this construct. Each ELSE is associated with the last preceding ``un-ELSE'd'' IF. In
this example, consider the situation where the parser has seen
IF ( C1 ) IF ( C2 ) S1
and is looking at the ELSE. It can immediately reduce by the simple-if rule to get
IF ( C1 ) stat
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 172
and then read the remaining input,
ELSE S2
and reduce
IF ( C1 ) stat ELSE S2
by the if-else rule. This leads to the first of the above groupings of the input.
On the other hand, the ELSE may be shifted, S2 read, and then the right hand
portion of
IF ( C1 ) IF ( C2 ) S1 ELSE S2
can be reduced by the if-else rule to get
IF ( C1 ) stat
which can be reduced by the simple-if rule.
Once again the parser can do two valid things - there is a shift/reduce conflict. The
application of disambiguating rule 1 tells the parser to shift in this case, which
leads to the desired grouping.
This shift/reduce conflict arises only when there is a particular current input symbol,
ELSE, and particular inputs already seen, such as
IF ( C1 ) IF ( C2 ) S1
In general, there may be many conflicts, and each one will be associated with an
input symbol and a set of previously read inputs. The previously read inputs are
characterized by the state of the parser.
stat : IF '(' cond ')' stat
Once again, notice that the numbers following ``shift'' commands refer to other
states, while the numbers following ``reduce'' commands refer to grammar rule
numbers. In the y.output file, the rule numbers are printed after those rules
which can be reduced.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 173
8.6 Variables and Typed Tokens
There is one common situation where the rules given above for resolving conflicts are
not sufficient; this is in the parsing of arithmetic expressions. Most of the commonly used
constructions for arithmetic expressions can be naturally described by the notion of
precedence levels for operators, together with information about left or right associatively.
It turns out that ambiguous grammars with appropriate disambiguating rules can be used to
create parsers that are faster and easier to write than parsers constructed from unambiguous
grammars.
The basic notion is to write grammar rules of the form
expr : expr OP expr
and
expr : UNARY expr
for all binary and unary operators desired. This creates a very ambiguous
grammar, with many parsing conflicts. As disambiguating rules, the user specifies
the precedence, or binding strength, of all the operators, and the associativity of
the binary operators.
This information is sufficient to allow Yacc to resolve the parsing conflicts in
accordance with these rules, and construct a parser that realizes the desired
precedences and associativities.
The precedences and associativities are attached to tokens in the declarations
section. This is done by a series of lines beginning with a Yacc keyword: %left,
%right, or %nonassoc, followed by a list of tokens.
All of the tokens on the same line are assumed to have the same precedence level and
associativity; the lines are listed in order of increasing precedence or binding strength.
Thus,
%left '+' '-'
%left '*' '/'
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 174
describes the precedence and associativity of the four arithmetic operators. Plus and
minus are left associative, and have lower precedence than star and slash, which are
also left associative.
The keyword %right is used to describe right associative operators, and the keyword
%nonassoc is used to describe operators
%right '='
%left '+' '-'
%left '*' '/'
%%
expr : expr '=' expr
o | expr '+' expr
o | expr '-' expr
o | expr '*' expr
o | expr '/' expr
o | NAME
o ;
might be used to structure the input
a = b = c*d - e - f*g
as follows
a = ( b = ( ((c*d)-e) - (f*g) ) )
When this mechanism is used, unary operators must, in general, be given a
precedence. Sometimes a unary operator and a binary operator have the same
symbolic representation, but different precedences.
o An example is unary and binary '-'; unary minus may be given the same
strength as multiplication, or even higher, while binary minus has a lower
strength than multiplication. The keyword, %prec, changes the precedence
level associated with a particular grammar rule. %prec appears
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 175
immediately after the body of the grammar rule, before the action or closing
semicolon, and is followed by a token name or literal.
o It causes the precedence of the grammar rule to become that of the following
token name or literal. For example, to make unary minus have the same
precedence as multiplication the rules might resemble:
%left '+' '-'
%left '*' '/'
%%
expr : expr '+' expr
| expr '-' expr
| expr '*' expr
| expr '/' expr
| '-' expr %prec '*'
| NAME
;
A token declared by %left, %right, and %nonassoc need not be, but may be, declared by
%token as well.
The precedence and associatively are used by Yacc to resolve parsing conflicts; they
give rise to disambiguating rules. Formally, the rules work as follows:
1. The precedences and associativities are recorded for those tokens and literals that
have them.
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 176
2. A precedence and associativity is associated with each grammar rule; it is the
precedence and associativity of the last token or literal in the body of the rule. If
the %prec construction is used, it overrides this default. Some grammar rules
may have no precedence and associativity associated with them.
3. When there is a reduce/reduce conflict, or there is a shift/reduce conflict and
either the input symbol or the grammar rule has no precedence and associativity,
then the two disambiguating rules given at the beginning of the section are used,
and the conflicts are reported.
4. If there is a shift/reduce conflict, and both the grammar rule and the input
character have precedence and associativity associated with them, then the
conflict is resolved in favor of the action (shift or reduce) associated with the
higher precedence. If the precedences are the same, then the associativity is
used; left associative implies reduce, right associative implies shift, and
nonassociating implies error.
Conflicts resolved by precedence are not counted in the number of shift/reduce and
reduce/reduce conflicts reported by Yacc. This means that mistakes in the specification of
precedences may disguise errors in the input grammar; it is a good idea to be sparing with
precedences, and use them in an essentially ``cookbook'' fashion, until some experience
has been gained. The y.output file is very useful in deciding whether the parser is actually
doing what was intended.
Recursive rules:
The algorithm used by the Yacc parser encourages so called ``left recursive''
grammar rules: rules of the form
name : name rest_of_rule ;
These rules frequently arise when writing specifications of sequences and lists:
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 177
list : item
| list ',' item
;
and
seq : item
| seq item
;
In each of these cases, the first rule will be reduced for the first item only, and the
second rule will be reduced for the second and all succeeding items.
With right recursive rules, such as
seq : item
| item seq
;
the parser would be a bit bigger, and the items would be seen, and reduced, from right to
left. More seriously, an internal stack in the parser would be in danger of overflowing if a
very long sequence were read. Thus, the user should use left recursion wherever
reasonable.
It is worth considering whether a sequence with zero elements has any meaning, and if
so, consider writing the sequence specification with an empty rule:
seq : /* empty */
| seq item
;
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 178
Once again, the first rule would always be reduced exactly once, before the first item was
read, and then the second rule would be reduced once for each item read
RUNNING BOTH LEXER AND PARSER:
The yacc program gets the tokens from the lex program. Hence a lex program has be
written to pass the tokens to the yacc. That means we have to follow different procedure
to get the executable file.
i. The lex program <lexfile.l> is fist compiled using lex compiler to get lex.yy.c.
ii. The yacc program <yaccfile.y> is compiled using yacc compiler to get y.tab.c.
iii. Using c compiler b+oth the lex and yacc intermediate files are compiled with the
lex library function. cc y.tab.c lex.yy.c ll.
iv. If necessary out file name can be included during compiling with o option.
Examples
1. Write a Yacc program to test validity of a simple expression with +, - , /, and *.
/* Lex program that passes tokens */
%{
#include "y.tab.h"
extern int yyparse();
%}
%%
[0-9]+ { return NUM;}
[a-zA-Z_][a-zA-Z_0-9]* { return IDENTIFIER;}
[+-] {return ADDORSUB;}
[*/] {return PROORDIV;}
[)(] {return yytext[0];}
[\n] {return '\n';}
%%
int main()
{
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 179
yyparse();
}
/* Yacc program to check for valid expression */
%{
#include<stdlib.h>
extern int yyerror(char * s);
extern int yylex();
%}
%token NUM
%token ADDORSUB
%token PROORDIV
%token IDENTIFIER
%%
input :
| input line
;
line : '\n'
| exp '\n' { printf("valid"); }
| error '\n' { yyerrok; }
;
exp : exp ADDORSUB term
| term
;
term : term PROORDIV factor
| factor
;
factor : NUM
| IDENTIFIER
| '(' exp ')'
;
%%
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 180
int yyerror(char *s)
{
printf("%s","INVALID\n");
}
/* yacc program that gets token from the c porogram */
%{
#include <stdio.h>
#include <ctype.h>
%}
%token NUMBER LETTER
%left '+' '-'
%left '*' '/'
%%
line:line expr '\n' {printf("\nVALID\n");}
| line '\n'
|
|error '\n' { yyerror ("\n INVALID"); yyerrok;}
;
expr:expr '+' expr
|expr '-' expr
|expr '*'expr
|expr '/' expr
| NUMBER
| LETTER
;
%%
main()
{
yyparse();
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 181
}
yylex()
{
char c;
while((c=getchar())==' ');
if(isdigit(c)) return NUMBER;
if(isalpha(c)) return LETTER;
return c;
}
yyerror(char *s)
{
printf("%s",s);
}
2. Write a Yacc program to recognize validity of a nested IF control statement and
display levels of nesting in the nested if.
/* Lex program to pass tokens */
%{
#include y.tab.h
%}
digit [0-9]
num {digit} + (. {digit}+)?
binopr [+-/*%^=><&|= =| != | >= | <=
unopr [~!]
char [a-zA-Z_]
id {char}({digit} | {char})*
space [ \t]
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 182
%%
{space} ;
{num} return num;
{ binopr } return binopr;
{ unopr } return unopr;
{ id} return id
if return if
. return yytext[0];
%%
NUMBER {DIGIT}+
/* Yacc program to check for the valid expression */
%{
#include<stdio.h>
int cnt;
%}
%token binopr
%token unop
%token num
%token id
%token if
%%
foo: if_stat { printf(valid: count = %d\n, cnt); cnt = 0;
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 183
exit(0);
}
| error { printf(Invalid \n); }
if_stat: token_if ( cond ) comp_stat {cnt++;}
cond: expr
;
expr: sim_exp
| ( expr )
| expr binop factor
| unop factor
;
factor: sim_exp
| ( expr )
;
sim_exp: num
| id
;
sim_stat: expr ;
| if
;
stat_list: sim_stat
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 184
| stat_list sim_stat
;
comp_stat: sim_stat
| { stat_list }
;
%%
main()
{
yyparse();
}
yyerror(char *s)
{
printf(%s\n, s);
exit(0);
}
3. Write a Yacc program to recognize a valid arithmetic expression that uses +, - , / , *.
%{
#include<stdio.h>
#include <type.h>
%}
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 185
% token num
% left '+' '-'
% left '*' '/'
%%
st : st expn '\n' {printf ("valid \n"); }
|
| st '\n'
| error '\n' { yyerror ("Invalid \n"); }
;
%%
void main()
{
yyparse (); return 0 ;
}
yylex()
{
char c;
while (c = getch () ) == ' ')
if (is digit (c))
return num;
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 186
return c;
}
yyerror (char *s)
{
printf("%s", s);
}
4. Write a yacc program to recognize an valid variable which starts with letter followed
by a digit. The letter should be in lowercase only.
/* Lex program to send tokens to the yacc program */
%{
#include "y.tab.h"
%}
%%
[0-9] return digit;
[a-z] return letter;
[\n] return yytext[0];
. return 0;
%%
/* Yacc program to validate the given variable */
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 187
%{
#include<type.h>
%}
% token digit letter ;
%%
ident : expn '\n' { printf ("valid\n"); exit (0); }
;
expn : letter
| expn letter
| expn digit
| error { yyerror ("invalid \n"); exit (0); }
;
%%
main()
{
yyparse();
}
yyerror (char *s)
{
printf("%s", s);
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 188
}
/* Yacc program which has c program to pass tokens */
%{
#include <stdio.h>
#include <ctype.h>
%}
%token LETTER DIGIT
%%
st:st LETTER DIGIT '\n' {printf("\nVALID");}
| st '\n'
|
| error '\n' {yyerror("\nINVALID");yyerrok;}
;
%%
main()
{
yyparse();
}
yylex()
{
char c;
while((c=getchar())==' ');
if(islower(c)) return LETTER;
if(isdigit(c)) return DIGIT;
return c;
}
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 189
yyerror(char *s)
{
printf("%s",s);
}
5.Write a yacc program to evaluate an expression (simple calculator program).
/* Lex program to send tokens to the Yacc program */
%{
#include" y.tab.h"
expern int yylval;
%}
%%
[0-9] digit
char[_a-zA-Z]
id {char} ({ char } | {digit })*
%%
{digit}+ {yylval = atoi (yytext);
return num;
}
{id} return name
[ \t] ;
\n return 0;
. return yytext [0];
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 190
%%
/* Yacc Program to work as a calculator */
%{
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
%}
% token num name
% left '+' '-'
% left '*' '/'
% left unaryminus
%%
st : name '=' expn
| expn { printf ("%d\n" $1); }
;
expn : num { $$ = $1 ; }
| expn '+' num { $$ = $1 + $3; }
| expn '-' num { $$ = $1 - $3; }
| expn '*' num { $$ = $1 * $3; }
| expn '/' num { if (num == 0)
{ printf ("div by zero \n");
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 191
exit (0);
}
else
{ $$ = $1 / $3; }
| '(' expn ')' { $$ = $2; }
;
%%
main()
{
yyparse();
}
yyerror (char *s)
{
printf("%s", s);
}
5. Write a yacc program to recognize the grammar { a
n
b for n >= 0}.
/* Lex program to pass tokens to yacc program */
%{
#include "y.tab.h"
%}
[a] { return a ; printf("returning A to yacc \n"); }
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 192
[b] return b
[\n] return yytex[0];
. return error;
%%
/* Yacc program to check the given expression */
%{
#include<stdio.h>
%}
% token a b error
%%
input : line
| error
;
line : expn '\n' { printf(" valid new line char \n"); }
;
expn : aa expn bb
| aa
;
aa : aa a
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 193
| a
;
bb : bb b
| b
;
error : error { yyerror ( " " ) ; }
%%
main()
{
yyparse();
}
yyerror (char *s)
{
printf("%s", s);
}
/* Yacc to evaluate the expression and has c program for tokens */
%{
/* 6b.y {A^NB N >=0} */
#include <stdio.h>
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 194
%}
%token A B
%%
st:st reca endb '\n' {printf("String belongs to grammar\n");}
| st endb '\n' {printf("String belongs to grammar\n");}
| st '\n'
| error '\n' {yyerror ("\nDoes not belong to grammar\n");yyerrok;}
|
;
reca: reca enda | enda;
enda:A;
endb:B;
%%
main()
{
yyparse();
}
yylex()
{
char c;
while((c=getchar())==' ');
if(c=='a')
return A;
if(c=='b')
return B;
return c;
}
yyerror(char *s)
{
fprintf(stdout,"%s",s);
}
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 195
7. Write a program to recognize the grammar { a
n
b
n
| n >= 0 }
/* Lex program to send tokens to yacc program */
%{
#include "y.tab.h"
%}
[a] {return A ; printf("returning A to yacc \n"); }
[b] return B
[\n] return yytex[0];
. return error;
%%
/* yacc program that evaluates the expression */
%{
#include<stdio.h>
%}
% token a b error
%%
input : line
| error
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 196
;
line : expn '\n' { printf(" valid new line char \n"); }
;
expn : aa expn bb
|
;
error : error { yyerror ( " " ) ; }
%%
main()
{
yyparse();
}
yyerror (char *s)
{
printf("%s", s);
}
/* Yacc program which has its own c program to send tokens */
%{
/* 7b.y {A^NB^N N >=0} */
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 197
#include <stdio.h>
%}
%token A B
%%
st:st reca endb '\n' {printf("String belongs to grammar\n");}
| st '\n' {printf("N value is 0,belongs to grammar\n");}
|
| error '\n'
{yyerror ("\nDoes not belong to grammar\n");yyerrok;}
;
reca: enda reca endb | enda;
enda:A;
endb:B;
%%
main()
{
yyparse();
}
yylex()
{
char c;
while((c=getchar())==' ');
if(c=='a')
return A;
if(c=='b')
return B;
return c;
}
yyerror(char *s)
{
fprintf(stdout,"%s",s);
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 198
}
8. Write a Yacc program t identify a valid IF statement or IF-THEN-ELSE statement.
/* Lex program to send tokens to yacc program */
%{
#include "y.tab.h"
%}
CHAR [a-zA-Z0-9]
%x CONDSTART
%%
<*>[ ] ;
<*>[ \t\n]+ ;
<*><<EOF>> return 0;
if return(IF);
else return(ELSE);
then return(THEN);
\( {BEGIN(CONDSTART);return('(');}
<CONDSTART>{CHAR}+ return COND;
<CONDSTART>\) {BEGIN(INITIAL);return(')');}
{CHAR}+ return(STAT) ;
%%
/* Yacc program to check for If and IF Then Else statement */
%{
#include<stdio.h>
%}
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 199
%token IF COND THEN STAT ELSE
%%
Stat:IF '(' COND ')' THEN STAT {printf("\n VALId Statement");}
| IF '(' COND ')' THEN STAT ELSE STAT {printf("\n VALID Statement");}
|
;
%%
main()
{
printf("\n enter statement ");
yyparse();
}
yyerror (char *s)
{
printf("%s",s);
}
/* Yacc program that has c program to send tokens */
%{
#include <stdio.h>
#include <ctype.h>
%}
%token if simple
% noassoc reduce
% noassoc else
%%
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 200
start : start st \n
|
;
st : simple
| if_st
;
if_st : if st %prec reduce { printf (simple\n); }
| if st else st {printf (if_else \n); }
;
%%
int yylex()
{
int c;
c = getchar();
switch ( c )
{
case i : return if;
case s : return simple;
case e : return else;
default : return c;
}
SYSTEM SOFTWARE 10CS52
Dept. of ISE, SJBIT 201
}
main ()
{
yy parse();
}
yyerror (char *s)
{
printf("%s", s);
}
RECOMMENDED QUESTIONS:
1. give the specification of yacc program? give an example? (8)
2. what is grammar? How does yacc parse a tree? (5)
3. how do you compile a yacc file? (5)
4. explain the ambiguity occurring in an grammar with an example? (6)
5. explain shift/reduce and reduce/reduce parsing ? (8)
6. write a yacc program to test the validity of an arthimetic expressions? (8)
7. write a yacc program to accept strings of the form anbn , n>0? (8)