COMPILER DESIGN LECTURE NOTES - KopyKitab

2y ago
69 Views
5 Downloads
1.27 MB
16 Pages
Last View : 3d ago
Last Download : 3m ago
Upload by : Mya Leung
Transcription

COMPILER DESIGNLECTURE NOTES

UNIT -11.1 OVERVIEW OF LANGUAGE PROCESSING SYSTEM1.2 PreprocessorA preprocessor produce input to compilers. They may perform the following functions.1. Macro processing: A preprocessor may allow a user to define macros that are shorthands for longer constructs.2. File inclusion: A preprocessor may include header files into the program text.3. Rational preprocessor: these preprocessors augment older languages with moremodern flow-of-control and data structuring facilities.4. Language Extensions: These preprocessor attempts to add capabilities to the languageby certain amounts to build-in macro1.3 COMPILERCompiler is a translator program that translates a program written in (HLL) the sourceprogram and translate it into an equivalent program in (MLL) the target program. As animportant part of a compiler is error showing to the programmer.Source pgmCompilertarget pgmError msgDepartment of CSE-2-

Executing a program written n HLL programming language is basically of two parts. thesource program must first be compiled translated into a object program. Then the resultsobject program is loaded into a memory executed.Source pgmObj pgm inputCompilerObj pgmobj pgmopj pgm output1.4 ASSEMBLER: programmers found it difficult to write or read programs in machinelanguage. They begin to use a mnemonic (symbols) for each machine instruction, whichthey would subsequently translate into machine language. Such a mnemonic machinelanguage is now called an assembly language. Programs known as assembler werewritten to automate the translation of assembly language in to machine language. Theinput to an assembler program is called source program, the output is a machine languagetranslation (object program).1.5 INTERPRETER: An interpreter is a program that appears to execute a sourceprogram as if it were machine language.Languages such as BASIC, SNOBOL, LISP can be translated using interpreters. JAVA alsouses interpreter. The process of interpretation can be carried out in following phases.1. Lexical analysis2. Synatx analysis3. Semantic analysis4. Direct ExecutionAdvantages:Modification of user program can be easily made and implemented as executionproceeds.Type of object that denotes a various may change dynamically.Debugging a program and finding errors is simplified task for a program used forinterpretation.The interpreter for the language makes it machine independent.Department of CSE-3-

Disadvantages:The execution of the program is slower.Memory consumption is more.2Loader and Link-editor:Once the assembler procedures an object program, that program must be placed intomemory and executed. The assembler could place the object program directly in memoryand transfer control to it, thereby causing the machine language program to beexecute.This would waste core by leaving the assembler in memory while the user’sprogram was being executed. Also the programmer would have to retranslate his programwith each execution, thus wasting translation time. To over come this problems of wastedtranslation time and memory. System programmers developed another component calledloader“A loader is a program that places programs into memory and prepares them forexecution.” It would be more efficient if subroutines could be translated into object form theloader could”relocate” directly behind the user’s program. The task of adjusting programs othey may be placed in arbitrary core locations is called relocation. Relocation loadersperform four functions.1.6 TRANSLATORA translator is a program that takes as input a program written in one language andproduces as output a program in another language. Beside program translation, the translatorperforms another very important role, the error-detection. Any violation of d HLLspecification would be detected and reported to the programmers. Important role of translatorare:1 Translating the hll program input into an equivalent ml program.2 Providing diagnostic messages wherever the programmer violates specification ofthe hll.1.7 TYPE OF ment of CSE-4-

1.8 LIST OF COMPILERS1. Ada compilers2 .ALGOL compilers3 .BASIC compilers4 .C# compilers5 .C compilers6 .C compilers7 .COBOL compilers8 .D compilers9 .Common Lisp compilers10. ECMAScript interpreters11. Eiffel compilers12. Felix compilers13. Fortran compilers14. Haskell compilers15 .Java compilers16. Pascal compilers17. PL/I compilers18. Python compilers19. Scheme compilers20. Smalltalk compilers21. CIL compilers1.9 STRUCTURE OF THE COMPILER DESIGNPhases of a compiler: A compiler operates in phases. A phase is a logically interrelatedoperation that takes source program in one representation and produces output in anotherrepresentation. The phases of a compiler are shown in belowThere are two phases of compilation.a. Analysis (Machine Independent/Language Dependent)b. Synthesis(Machine Dependent/Language independent)Compilation process is partitioned into no-of-sub processes called ‘phases’.Department of CSE-5-

Lexical Analysis:LA or Scanners reads the source program one character at a time, carving thesource program into a sequence of automic units called tokens.Syntax Analysis:The second stage of translation is called Syntax analysis or parsing. In thisphase expressions, statements, declarations etc are identified by using the results of lexicalanalysis. Syntax analysis is aided by using techniques based on formal grammar of theprogramming language.Intermediate Code Generations:An intermediate representation of the final machine language code is produced.This phase bridges the analysis and synthesis phases of translation.Code Optimization :This is optional phase described to improve the intermediate code so that theoutput runs faster and takes less space.Code Generation:The last phase of translation is code generation. A number of optimizations toreduce the length of machine language program are carried out during this phase. Theoutput of the code generator is the machine language program of the specified computer.Table Management (or) Book-keeping:-Department of CSE-6-

This is the portion to keep the names used by the program and recordsessential information about each. The data structure used to record this information called a‘Symbol Table’.Error Handlers:It is invoked when a flaw error in the source program is detected.The output of LA is a stream of tokens, which is passed to the next phase, thesyntax analyzer or parser. The SA groups the tokens together into syntactic structure calledas expression. Expression may further be combined to form statements. The syntacticstructure can be regarded as a tree whose leaves are the token called as parse trees.The parser has two functions. It checks if the tokens from lexical analyzer,occur in pattern that are permitted by the specification for the source language. It alsoimposes on tokens a tree-like structure that is used by the sub-sequent phases of the compiler.Example, if a program contains the expression A /B after lexical analysis thisexpression might appear to the syntax analyzer as the token sequence id /id. On seeing the /,the syntax analyzer should detect an error situation, because the presence of these twoadjacent binary operators violates the formulations rule of an expression.Syntax analysis is to make explicit the hierarchical structure of the incomingtoken stream by identifying which parts of the token stream should be grouped.Example, (A/B*C has two possible interpretations.)1, divide A by B and then multiply by C or2, multiply B by C and then use the result to divide A.each of these two interpretations can be represented in terms of a parse tree.Intermediate Code Generation:The intermediate code generation uses the structure produced by the syntaxanalyzer to create a stream of simple instructions. Many styles of intermediate code arepossible. One common style uses instruction with one operator and a small number ofoperands.The output of the syntax analyzer is some representation of a parse tree. theintermediate code generation phase transforms this parse tree into an intermediate languagerepresentation of the source program.Code OptimizationThis is optional phase described to improve the intermediate code so that theoutput runs faster and takes less space. Its output is another intermediate code program thatdoes the some job as the original, but in a way that saves time and / or spaces.1, Local Optimization:There are local transformations that can be applied to a program tomake an improvement. For example,If A B goto L2Department of CSE-7-

Goto L3L2 :This can be replaced by a single statementIf A B goto L3Another important local optimization is the elimination of commonsub-expressionsA : B C DE : B C FMight be evaluated asT1 : B CA : T1 DE : T1 FTake this advantage of the common sub-expressions B C.2, Loop Optimization:Another important source of optimization concerns about increasingthe speed ofloops. A typical loop improvement is to move acomputation that produces the same result each time around the loopto a point, in the program just before the loop is entered.Code generator :Cg produces the object code by deciding on the memory locations for data,selecting code to access each datum and selecting the registers in which each computation isto be done. Many computers have only a few high speed registers in which computations canbe performed quickly. A good code generator would attempt to utilize registers as efficientlyas possible.Table Management OR Book-keeping :A compiler needs to collect information about all the data objects that appearin the source program. The information about data objects is collected by the early phases ofthe compiler-lexical and syntactic analyzers. The data structure used to record thisinformation is called as Symbol Table.Error Handing :One of the most important functions of a compiler is the detection andreporting of errors in the source program. The error message should allow the programmer todetermine exactly where the errors have occurred. Errors may occur in all or the phases of acompiler.Whenever a phase of the compiler discovers an error, it must report the error tothe error handler, which issues an appropriate diagnostic msg. Both of the table-managementand error-Handling routines interact with all phases of the compiler.Department of CSE-8-

Example:Position: initial rate *60Lexical AnalyzerTokensid1 id2 id3 * id4Syntsx Analyzer id1 id2*id3id4Semantic Analyzer id1 id2*id360int to realIntermediate Code Generatortemp1: int to real (60)temp2: id3 * temp1temp3: id2 temp2id1: temp3.Code OptimizerTemp1: id3 * 60.0Department of CSE-9-

Id1: id2 temp1Code GeneratorMOVFMULFMOVFADDFMOVFid3, r2*60.0, r2id2, r2r2, r1r1, id11.10 TOKENLA reads the source program one character at a time, carving the source program intoa sequence of automatic units called ‘Tokens’.1, Type of the token.2, Value of the token.Type : variable, operator, keyword, constantValue : N1ame of variable, current variable (or) pointer to symbol table.If the symbols given in the standard format the LA accepts and producestoken as output. Each token is a sub-string of the program that is to be treated as a singleunit. Token are two types.1, Specific strings such as IF (or) semicolon.2, Classes of string such as identifiers, label, constants.Department of CSE- 10 -

UNIT -2LEXICAL ANALYSIS2.1 OVER VIEW OF LEXICAL ANALYSISoTo identify the tokens we need some method of describing the possible tokensthat can appear in the input stream. For this purpose we introduce regular expression, anotation that can be used to describe essentially all the tokens of programminglanguage.oSecondly , having decided what the tokens are, we need some mechanism torecognize these in the input stream. This is done by the token recognizers, which aredesigned using transition diagrams and finite automata.2.2ROLE OF LEXICAL ANALYZERthe LA is the first phase of a compiler. It main task is to read the input characterand produce as output a sequence of tokens that the parser uses for syntax analysis.Upon receiving a ‘get next token’ command form the parser, the lexical analyzerreads the input character until it can identify the next token. The LA return to the parserrepresentation for the token it has found. The representation will be an integer code, if thetoken is a simple construct such as parenthesis, comma or colon.LA may also perform certain secondary tasks as the user interface. One such task isstriping out from the source program the commands and white spaces in the form of blank,tab and new line characters. Another is correlating error message from the compiler with thesource program.Department of CSE- 11 -

2.3 LEXICAL ANALYSIS VS PARSING:Lexical analysisParsingThe lexical analyzer (the "lexer") parsesindividual symbols from the source code fileinto tokens. From there, the "parser" properturns those whole tokens into sentences ofyour grammarA parser does not give the nodes anymeaning beyond structural cohesion. Thenext thing to do is extract meaning from thisstructure (sometimes called contextualanalysis).A Scanner simply turns an input String (say afile) into a list of tokens. These tokensrepresent things like identifiers, parentheses,operators etc.A parser converts this list of tokens into aTree-like object to represent how the tokensfit together to form a cohesive whole(sometimes referred to as a sentence).2.4 TOKEN, LEXEME, PATTERN:Token: Token is a sequence of characters that can be treated as a single logical entity.Typical tokens are,1) Identifiers 2) keywords 3) operators 4) special symbols 5)constantsPattern: A set of strings in the input for which the same token is produced as output. This setof strings is described by a rule called a pattern associated with the token.Lexeme: A lexeme is a sequence of characters in the source program that is matched by thepattern for a token.Example:Description of on , , , , , ipi or or or or or letterfollowed by letters & digitany numeric constantnun3.14any character b/w “and “except"literal"core"patternDepartment of CSE- 12 -

A patter is a rule describing the set of lexemes that can represent a particular token in sourceprogram.2.5 LEXICAL ERRORS:Lexical errors are the errors thrown by your lexer when unable to continue. Which meansthat there's no way to recognise a lexeme as a valid token for you lexer. Syntax errors, on theother side, will be thrown by your scanner when a given set of already recognised validtokens don't match any of the right sides of your grammar rules. simple panic-mode errorhandling system requires that we return to a high-level parsing function when a parsing orlexical error is detected.Error-recovery actions are:i. Delete one character from the remaining input.ii. Insert a missing character in to the remaining input.iii. Replace a character by another character.iv. Transpose two adjacent characters.2.6 DIFFERENCE BETWEEN COMPILER AND INTERPRETERA compiler converts the high level instruction into machine language while aninterpreter converts the high level instruction into an intermediate form.Before execution, entire program is executed by the compiler whereas aftertranslating the first line, an interpreter then executes it and so on.List of errors is created by the compiler after the compilation process while aninterpreter stops translating after the first error.An independent executable file is created by the compiler whereas interpreter isrequired by an interpreted program each time.The compiler produce object code whereas interpreter does not produce object code.In the process of compilation the program is analyzed only once and then the code isgenerated whereas source program is interpreted every time it is to be executed andevery time the source program is analyzed. hence interpreter is less efficient thancompiler.Examples of interpreter: A UPS Debugger is basically a graphical source leveldebugger but it contains built in C interpreter which can handle multiple source files.example of compiler: Borland c compiler or Turbo C compiler compiles the programswritten in C or C .Department of CSE- 13 -

2.7 REGULAR EXPRESSIONSRegular expression is a formula that describes a possible set of string.Component of regular expression.Xthe character x.any character, usually accept a new line[x y z]any of the characters x, y, z, .R?a R or nothing ( optionally as R)R*zero or more occurrences .R one or more occurrences R1R2an R1 followed by an R2R2R1either an R1 or an R2.A token is either a single string or one of a collection of strings of a certain type. If we viewthe set of strings in each token class as an language, we can use the regular-expressionnotation to describe tokens.Consider an identifier, which is defined to be a letter followed by zero or more lettersor digits. In regular expression notation we would write.Identifier letter (letter digit)*Here are the rules that define the regular expression over alphabet .o is a regular expression denoting { }, that is, the language containing only theempty string.o For each ‘a’ in , is a regular expression denoting { a }, the language with onlyone string consisting of the single symbol ‘a’ .o If R and S are regular expressions, then(R) (S) means LrULsR.S means Lr.LsR* denotes Lr*2.8 REGULAR DEFINITIONSFor notational convenience, we may wish to give names to regular expressions andto define regular expressions using these names as if they were symbols.Identifiers are the set or string of letters and digits beginning with a letter. Thefollowing regular definition provides a precise specification for this class of string.Example-1,Ab* cd? Is equivalent to (a(b*)) (c(d?))Pascal identifierLetter - A B Z a b z Digits - 0 1 2 . 9Id- letter (letter / digit)*Department of CSE- 14 -

JNTU Study Material For CompilerDesign (Computer ScienceEngineering)50%OFFPublisher : Faculty NotesAuthor : Panel Of ExpertsType the URL : http://www.kopykitab.com/product/10163Get this eBook

COMPILER DESIGN LECTURE NOTES . Department of CSE - 2 - UNIT -1 1.1 OVERVIEW OF LANGUAGE PROCESSING SYSTEM 1.2 Preprocessor A preprocessor produce input to compilers. They may perform the following functions. . 1.9 STRUCTURE OF THE COMPILER DESIGN Phases of a compiler: A compiler

Related Documents:

Introduction of Chemical Reaction Engineering Introduction about Chemical Engineering 0:31:15 0:31:09. Lecture 14 Lecture 15 Lecture 16 Lecture 17 Lecture 18 Lecture 19 Lecture 20 Lecture 21 Lecture 22 Lecture 23 Lecture 24 Lecture 25 Lecture 26 Lecture 27 Lecture 28 Lecture

Aug 24, 2009 · Lecture Notes on Compiler Design: Overview 15-411: Compiler Design Frank Pfenning Lecture 1 August 24, 2009 1 Introduction This course is a thorough introduction to compiler design, focusing on more low-level and systems aspects rather than high-level questions such as polymorphic type inference or separate compilation. You will be build-File Size: 255KB

GEOMETRY NOTES Lecture 1 Notes GEO001-01 GEO001-02 . 2 Lecture 2 Notes GEO002-01 GEO002-02 GEO002-03 GEO002-04 . 3 Lecture 3 Notes GEO003-01 GEO003-02 GEO003-03 GEO003-04 . 4 Lecture 4 Notes GEO004-01 GEO004-02 GEO004-03 GEO004-04 . 5 Lecture 4 Notes, Continued GEO004-05 . 6

COMPILER DESIGN Lecture 15 Zhendong Su Compiler Design. Announcements HW4: OAT v. 1.0 –Parsing & basic code generation Zhendong Su Compiler Design. Why Inference Rules? Allow a compact, precise way of specifying language pro

Compiler Design 10 A compiler can broadly be divided into two phases based on the way they compile. Analysis Phase Known as the front-end of the compiler, the analysis phase of the compiler reads the source program, divides it into core parts, and then checks for lexical, grammar, and syntax errors.

Compiler Design 10 A compiler can broadly be divided into two phases based on the way they compile. Analysis Phase Known as the front-end of the compiler, the analysis phase of the compiler reads the source program, divides it into core parts,

Lecture 1: A Beginner's Guide Lecture 2: Introduction to Programming Lecture 3: Introduction to C, structure of C programming Lecture 4: Elements of C Lecture 5: Variables, Statements, Expressions Lecture 6: Input-Output in C Lecture 7: Formatted Input-Output Lecture 8: Operators Lecture 9: Operators continued

development teams. In Agile Product Management with Scrum, you’ll see how a product owner differs from a traditional product manager having a greater level of responsibility for the success of the product. The book clearly outlines and contrasts the different behav-iors between the traditional and the agile role.