Compiler Compiler Tutorial
|
|
|
- Berenice Harrington
- 10 years ago
- Views:
Transcription
1 Compiler Compiler Tutorial CSA2010 Compiler Techniques Gordon Mangion
2 Introduction With so many Compilers around, do we need to write parsers/compilers in industry? FTP interface Translator from VB to Java EPS Reader NLP
3 Topics Prerequisites Compiler Architecture/Modules JavaCC Virtual Machines Semantic Analysis Code Generation and Execution Examples The assignment (SL Compiler)
4 Prerequisites Java Regular Expressions? + * Production rules and EBNF Semantics
5 Regular Expressions Repetitions + = 1 or more * = 0 or more? = 0 or 1 Alternative a b = a or b Examples a+ - a, aa, aaa b* -, b, bb c? -, c a b - a, b Ranges [a-z] [fls] [^cde] = a to z = f, l and s = not c,d,e - a,b,c,d,e,f,g,,y,z - f,l,s - a,b,f,g,,y,z
6 Compiler What is a compiler? Where to start from? Design / Architecture of a Compiler
7 Compiler Is essentially a complex function which maps a program in a source language onto a program in the target language. C o m p i l e r Source Code Lexical Analysis Syntax Analysis Semantic Analysis I-Code Optimiser Error Handler Target Code Symbol Table Code Execution Code Generator Optimiser Code Optimiser
8 Translation Source Code int Sqr( int x ) var int n = x; n = n * n; return n; push mov sub push push push lea mov mov rep stos mov mov mov imul mov mov pop pop pop mov pop ret Target Code ebp ebp,esp esp,0cch ebx esi edi edi,[ebp-0cch] ecx,33h eax,0cccccccch dword ptr es:[edi] eax,dword ptr [x] dword ptr [n],eax eax,dword ptr [n] eax,dword ptr [n] dword ptr [n],eax eax,dword ptr [n] edi esi ebx esp,ebp ebp
9 Translation Source Code int Sqr( int x ) var int n = x; n = n * n; return n; Compiler All possible translations of the source program
10 Translation Source Code Target Code p u s h ebp mov ebp,esp s u b e s p, 0 C C h p u s h ebx p u s h esi p u s h edi l e a edi, [ e b p - 0CCh] mov ecx,33h mov e a x, 0 C C C C C C C C h r e p stos dword p t r es:[e d i ] int Sqr( int x ) var int n = x; n = n * n; return n; mov mov mov imul mov mov eax,dword ptr [x] dword ptr [n],eax eax,dword ptr [n] eax,dword ptr [n] dword ptr [n],eax eax,dword ptr [n] p o p p o p p o p mov p o p ret edi esi ebx esp,ebp ebp
11 Production Rules Context Free Grammars A B c D BNF A ::= B c D EBNF A ::= B* c? D+
12 The Language game Source Language Target Language Implementation Language
13 Tombstone Diagram Source Target Language Language Implementation Language
14 Source Language Tokens Intermediate Code Compiler Architecture Error Handler Source Code Lexical Analysis Syntax Analysis Semantic Analysis Intermediate Code I-Code Optimiser Intermediate Code Symbol Table Code Execution Code Generator Optimiser Code Optimiser
15 Simplified Compiler Architecture Source Code Source Language Lexical Analysis Tokens Syntax Analysis Semantic Analysis Intermediate Code Symbol Table Intermediate Code Code Generator Target Code
16 Lexical Analysis Tokenises the source file Removes whitespace Tokens Keywords Source Code function Sqr( x : int ) : int let n : int = x; n <- n * n; return n; Function (Keyword) Sqr (Identifier) ( (Lparen) X (Identifier) : (Colon) Int (Keyword) ) (Rparen) : (Colon) Int (Keyword) (Lbrace) Let (Keyword) N (Identifier) : (Colon) Int (Keyword) = (Eq) X (Identifier) ; (Semicolon)
17 Syntax Analysis (Parser) Checks that the source file conforms to the language grammar E.g. FunctionDecl ::= function identifier ( Source Code Source Code function Sqr( x : int ) function 1.5( x : int ) Creates intermediate code ParseTree SimpleExpr 2 + 5
18 Semantic Analysis Checks that the meaning behind the syntax makes sense, according to the type-system E.g. var int x = 3; x:int, 3:int E.g. var int x = 3.2; x:int, 3.2:Real
19 Code Generation / Execution Traverses the Intermediate Code representation and generates or executes the code PlusNode.Generate() leftchild.generate() ; rightchild.generate(); EmitCode(Add); IntLiteralNode.Generate() EmitCode ( Push, Integer.parseInt(this.getValue()) );
20 Symbol Table Important Data Structure Keeps information about every identifier in the source Variables functions Labels Keeps the scope information Entry Properties Name Type Value Scope
21 Symbol Table A data structure that maps an Identifier s name onto a structure that contains the identifier s information Name ( Name, Type, Value, Scope )
22 Symbol Table Easiest way is to make use of a hash-table / hash-map Create a new Hash-map for each new scope
23 Java Interfaces Interface is a contract If a Class implements interface Honours the contract Implements the methods of the interface Interface type variable can hold instance of a class that implements that interface
24 Java Interfaces public interface IAdder int add(int n, int m); public interface IMinus int subtract(int n, int m);
25 Java Interfaces public interface IAdder int add(int n, int m); public interface IMinus int subtract(int n, int m); public class SimpleMath implements IAdder, IMinus public int add(int n, int m) public int subtract(int n, int m)
26 Java Interfaces public interface IAdder int add(int n, int m); public interface IMinus int subtract(int n, int m); public class SimpleMath implements IAdder, IMinus public int add(int n, int m) public static void main( ) IAdder a = new SimpleMath(); IMinus s = new SimpleMath(); public int subtract(int n, int m) a.add(1,2); s.subtract(4,2);
27 Java Interfaces public interface ICalculator int Calculate(int n, int m);
28 Java Interfaces public class Mul implements ICalculator public int Calculate(int n, int m) n * m public class Div implements ICalculator public int Calculate(int n, int m) n / m public interface ICalculator int Calculate(int n, int m);
29 Java Interfaces public class Mul implements ICalculator public int Calculate(int n, int m) n * m public class Div implements ICalculator public int Calculate(int n, int m) n / m public interface ICalculator int Calculate(int n, int m); public static void main( ) ICalculator c1 = new Mul(); ICalculator c2 = new Div(); c1.calculate(4,2); c2.calculate(4,2);
30 Simplified Compiler Architecture Source Code Source Language Lexical Analysis Tokens Front-End Syntax Analysis Semantic Analysis Intermediate Code Intermediate Code Symbol Table Back-End Code Generator Target Code
31 Visitor Interface Compiler Interface Visitor Interface Compiler Architecture Compiler Implementation Source Code Parser (Syntax Analysis) Lexical Analysis Parse Tree Symbol Table Call Visitor Type-Checker (Semantic Analysis) Call Visitor Code Execution
32 Program Generators? Source-to-Executable Compiler Reverse Polish Notation Source-to-Source Preprocessors
33 Javacc A program that creates parsers The source code(input) is a definition file Grammar definition Inline Java code The target(output) is java-based parser Recognizer?
34 Javacc langdef.jj Javacc *.java *.java *.java *.java
35 JJTree Preprocessor to Javacc Creates.jj files from.jjt files From a recognizer to a proper parser Produces Parse Tree building actions
36 JJTree langdef.jjt JJTree langdef.jj Javacc *.java *.java *.java *.java
37 JJTree langdef.jjt JJTree langdef.jj J J T T O O L Javacc *.java *.java *.java *.java
38 Installing Javacc Javacc.zip / Javacc.tar.gz Eclipse plugin Preferences->Install/Update->Add Help->New Software Newer versions Eclipse Marketplace
39 .jjt Grammar Files Four (4) sections Options Parser Tokens Production Rules
40 .jjt Options options BUILD_NODE_FILES=false; STATIC=false; MULTI=true;
41 .jjt Parser block PARSER_BEGIN(parser_name)... public class parser_name PARSER_END(parser_name)
42 .jjt Tokens Lexeme to ignore SKIP : \t \n \r <"//" (~["\n","\r"])* ("\n" "\r" "\r\n")>
43 .jjt Tokens Tokens that are to be returned TOKEN : <PLUS: + > <TRUE: "true" > <FALSE: "false" > <LETTER: (["A"-"Z"] ["a"-"z"]) > <STRING_LITERAL: "\"" (~["\"","\r","\n"])* "\"" > <#DIGIT: [ 0-9 ]>
44 .jjt Production Rules Assume the following: Header Script <STRING_LITERAL> or Header ::= Script <STRING_LITERAL>
45 .jjt Production Rules Assume the following: Header ::= Script <STRING_LITERAL> void Header(): <SCRIPT> <STRING_LITERAL>
46 .jjt Production Rules Header ::= Script <STRING_LITERAL> void Header(): int n = 0; n++; <SCRIPT> <STRING_LITERAL>
47 .jjt Production Rules Token matching - Actions void Header(): int n = 0; n++; <SCRIPT> n = 1; <STRING_LITERAL> n++;
48 .jjt Production Rules Calling Non-Terminals void Integer(): void Header(): <SCRIPT> Integer()
49 .jjt Production Rules Getting Token value void Number() Token t; int n = 0; t=<digit> n = integer.parseint(t.image);
50 Lookahead Consider the following java statements public int name; public int name[]; public int name()
51 Building the AST (Abstract Syntax Tree) options STATIC=false; MULTI=true; BUILD_NODE_FILES=true; NODE_USES_PARSER=false; NODE_PREFIX= ; // default AST
52 Building the AST SimpleNode Start() : Expression() ; <EOF> // Special Token return jjtthis;
53 Parsing PARSER_BEGIN(MyParser)... MyParser parser = new MyParser(System.in); try SimpleNode n = parser.start(); System.out.println( Parsed!"); catch (Exception e) System.out.println("Oops!"); System.out.println(e.getMessage());... PARSER_END(MyParser)
54 Example Digit ::= [ 0-9 ] Number ::= Digit+ Plus ::= + Minus ::= - Op ::= Plus Minus Expression ::= Number Op Number
55 Example TOKEN: < NUMBER: <DIGIT>+ > < Digit: [ 0-9 ] > < PLUS: + > < MINUS: - > Digit ::= [ 0-9 ] Number ::= Digit+ Plus ::= + Minus ::= -
56 Example void Op() : < PLUS > < MINUS > Op ::= Plus Minus void Expression(): < Number > (Op() < Number >)* Expression ::= Number Op Number
57 Example PARSER_BEGIN(MyParser)... MyParser parser = new MyParser(System.in); try parser.expression(); System.out.println( Parsed!"); catch (Exception e) System.out.println("Oops!"); System.out.println(e.getMessage());... PARSER_END(MyParser)
58 Generated Sources
59 Example Evaluating Token Op() : Token t; (t = < PLUS > t = < MINUS >) return t;
60 Example int Expression(): Token t, op; int n; t = < NUMBER > n = Integer.parseInt( t.image ); ( op=op() t = < NUMBER > if(op.image.equals("+")) n += Integer.parseInt( t.image ); else n -= Integer.parseInt( t.image ); )* return n;
61 Example PARSER_BEGIN(MyParser) public class MyParser... MyParser parser = new MyParser(System.in); try int n = parser.expression();... PARSER_END(MyParser)
62 Example - Building the AST options STATIC=false; MULTI=true; BUILD_NODE_FILES=true; NODE_USES_PARSER=false; NODE_PREFIX= AST ;
63 Generated Code
64 Example void Op() : < PLUS > < MINUS > SimpleNode Expression(): < Number > (Op() < Number >)* return jjtthis; Op ::= Plus Minus Expression ::= Number Op Number
65 Example PARSER_BEGIN(MyParser) public class MyParser... MyParser parser = new MyParser(System.in); try SimpleNode rootnode = parser.expression();... PARSER_END(MyParser)
66 Example Grammar 2 Digit ::= [ 0-9 ] Number ::= Digit+ Factor ::= Expression Number Term ::= Factor [ * / Factor ] Expression ::= Term + - Term Start ::= Expression
67 The Visitor Design Pattern The Problem + 2 * A 7 Number of operations to be performed on each node Options Implement each operation inside each node Make use of visitor pattern
68 The Visitor Design Pattern Consider one Node Printing Operation Plus PrintVisitor void PrettyPrint( Plus ) We can implement the operation in a separate class e.g. PrintVisitor This can be done for all type of nodes
69 The Visitor Design Pattern Modification on node Plus void Print( Visitor p_visitor) p_visitor.prettyprint( this ); Client Caller PrintVisitor pr = new PrintVisitor(); Plus plus plus.print(pr); PrintVisitor void PrettyPrint( Plus )
70 The Visitor Design Pattern Finally Plus void Accept( IVisitor p_visitor) p_visitor.visit( this ); Interface IVisitor void Visit( Plus ); Caller PrintVisitor pr = new PrintVisitor(); Plus plus plus.accept(pr); PrintVisitor implements IVisitor void Visit( Plus )
71 The Visitor Design Pattern Benefits Plus void Accept( IVisitor p_visitor) p_visitor.visit( this ); Interface IVisitor void Visit( Plus ); void Visit( Times ); PrintVisitor implements IVisitor void Visit( Plus ) void Visit( Times ) TypeCheckVisitor implements IVisitor void Visit( Plus ) void Visit( Times ) EvaluationVisitor implements IVisitor void Visit( Plus ) void Visit( Times )
72 Visitor Interface Compiler Interface Visitor Interface Compiler Architecture Compiler Implementation Source Code Parser (Syntax Analysis) Lexical Analysis Parse Tree Symbol Table Call Visitor Type-Checker (Semantic Analysis) Call Visitor Code Execution
73 JJTree and the Visitor Pattern Options VISITOR=true;
74 Visitor interface public interface MyParserVisitor public Object visit(simplenode node, Object data); public Object visit(astop node, Object data); public Object visit(astexpression node, Object data);
75 Visitor - Node modification Public class ASTExpression extends SimpleNode public ASTExpression(int id) super(id); public ASTExpression(MyParser p, int id) super(p, id); /** Accept the visitor. **/ public Object jjtaccept(myparservisitor visitor, Object data) return visitor.visit(this, data);
76 JJTree and the Visitor Pattern Options VISITOR=true; VISITOR_DATA_TYPE= SymbolTable ; VISITOR_RETURN_TYPE= Object ;
77 Visitor - return type We need a return-type generic enough to accommodate the results returned by all the visitor implementations By default jjt uses the Object class Can easily be used however class-casts instanceof A generic container can be designed to hold the results
78 Visitor - return type Types Create an enumeration containing the types of the language s type-system. This should always be created enum DataType None (/ Unknown), Error, Skip (/ Command), Bool, Int, Function,
79 Visitor - return type Result class Class Result DataType type; Object value; Getter & Setter Conversion
80 Visitor - return type We can make use of: Object Most generic return type Have to cast to proper instance DataType When the Type of the node suffices Result class When we need to return some data
81 SymbolTable Entry String Name DataType Type Value? Name Entry
82 SymbolTable Entry String Name DataType Type Int ScopeLevel Var / Param DataType ReturnType Int VarCount Int ParamCount (Entry Containter)
83 Type-Checking (Semantic Analysis) SemanticAnalyser (implements Visitor) Consider BooleanLiteral() public DataType visit( ASTBooleanLiteral node, SymbolTable data) return DataType.Bool;
84 Type-Checking (Semantic Analysis) Consider Identifier() public Object visit( ASTIdentifier node, SymbolTable data ) // Get name from the node String name = (String)node.jjtGetValue(); Consult symboltable, check if name exist if yes return its DataType println( Error ASTIdentifier : " + name); return DataType.Error;
85 Type-Checking (Semantic Analysis) Consider Assignment(): Identifier() <ASSIGN> Expression() Ident = Expr SimpleExpr 3 + 2
86 Type-Checking (Semantic Analysis) Consider Assignment(): Identifier() <ASSIGN> Expression() public Object visit(astassignment node, SymbolTable data ) // Check identifier DataType identtype = node.jjtgetchild(0).visit(this, data); if(identtype == DataType.Error) return DataType.Error;
87 Type-Checking (Semantic Analysis) Consider Assignment(): Identifier() <ASSIGN> Expression() // Check expresion DataType exprtype = node.jjtgetchild(1).visit(this, data); if(identtype!= exprtype) println( Error ASTAssignment ); return DataType.Error; return DataType.Skip;
88 Type-Checking (Semantic Analysis) Note the difference in the use of identifiers when they are: L-value [ a = ] R-value [ x = a + 4 ]
89 Type-Checking (Semantic Analysis) Consider the following decision rule IfStatement ::= if ( Expression ) if( ) Expression if Statement Block Statement Block
90 Type-Checking (Semantic Analysis) Use node.jjtgetnumchildren() to get the number of children the node has. This determines the shape of the tree examples are If Statement Variable Declaration Initialiser (var int n = 0;) Function Delaration Statement Block
91 Type-Checking (Semantic Analysis) Implement the call to the visitor: Public class MyParser... main... Try SimpleNode root = parser.expression(); MyParserVisitor visitor = new TypeChecker(); Result result = root.jjtaccept(visitor, null );... System.out.println("DataType is " + result.gettype().tostring());
92 Interpreter Code Execution In a similar way to Semantic Analysis, we can make use of the visitor pattern This time, we return values as well rather than type-information only We have to take special care about the difference in the semantics of the languages involved
93 Code Generation Once again we make use of the visitor pattern In this stage we traverse the parse-tree and emit target language code in our case S-Machine instructions In particular, we traverse nodes and emit code patterns
94 SymbolTable Entries require an Offset variable For data related nodes, Offset is the actual offset in the Stack. For flow control nodes, Offset holds the location in the Code Area
95 Code Generation Since we are emitting S-Machine instructions, it is wise to create an enum of the instructions public enum SMInstruction NOP, LDC, LD, STORE, DUP,
96 Code Generation At the end of the whole process we are writing a binary file which is the compiled program. It is a good idea to create a buffer and perhaps a class that takes care of it When the process finished, the buffer is then written to disk
97 CodeBuilder class CodeBuilder Byte[] codebuffer Int GetCodePosition() void AddInstruction(SMInstruction inst) void AddInstruction(SMInstruction inst, int nscope, int narg) void WriteCode(String p_strpath)
98 CodeGenerator Class CodeGenerator Implements Visitor CodeGenerator(CodeBuilder cb) Int GetCodeOffset() Void Emit( SMInstruction inst, int nscope, int narg) Void Emit( SMInstruction inst, int narg) Void Emit( SMInstruction inst )
99 CodeGenerator Endianess CodeBuffer[Offset+2] = (narg & 0xFF00)>>8 CodeBuffer[Offset+3] = (narg & 0xFF)
100 CodeGenerator Consider Literal public Object visit( ASTIntegerLiteral node, SymbolTable data) // LDC n Emit( SMInstruction.LDC, 0, (Integer)node.jjtGetValue() ); return SLType.Skip;
101 CodeGenerator Consider Identifier public DataType visit( ASTIdentifier node, SymbolTable data) //Get name from node //Get Entry from symboltable //If Param //Else if Var Emit( SMInstruction.LD, entry.scope, entry.offset ); return DataType.Skip;
102 CodeGenerator Consider Assignment public DataType visit( ASTAssignment node, SymbolTable data ) name = get name from node 0 entry = data.get(name); node.jjtgetchild(1).jjtaccept(this, data); Emit( SMInstruction.STORE, entry.scope, entry.offset); return DataType.Skip;
103 CodeGenerator Consider While Can you identify a potential problem? Location_of_Condition: 00 Code for Condition 01 JZ Out_Of_While 02 Code for While_Block 03 JMP Location_of_Condition Out_Of_While: 04
104 CodeGenerator Consider While public Object visit(astwhilestatement node, SymbolTable data) int addrcond = GetCodeOffset(); node.jjtgetchild(0).jjtaccept(this, data); int addrjump = GetCodeOffset(); Emit(SMInstruction.JZ, 0, 0); node.jjtgetchild(1).jjtaccept(this, data); Emit(SMInstruction.JMP, 0, addrcond); int addrend = m_codebuilder.getcodepos(); BackPatch(addrJump, addrend); return SLType.Skip;
105 CodeGenerator BackPatch( address of instruction, new address); Modifies the address argument of an instruction
106 CodeGenerator Consider While public Object visit(astwhilestatement node, SymbolTable data) int addrcond = GetCodeOffset(); node.jjtgetchild(0).jjtaccept(this, data); int addrjump = GetCodeOffset(); Emit(SMInstruction.JZ, 0, 0); node.jjtgetchild(1).jjtaccept(this, data); Emit(SMInstruction.JMP, 0, addrcond); int addrend = m_codebuilder.getcodepos(); BackPatch(addrJump, addrend); return SLType.Skip;
107 CodeGenerator Consider FunctionDecl public DataType visit(astfunctiondecl node, SymbolTable data) Get Entry from symboltable for node 0 Set symboltable Scope to that of entry; entry.offset = GetCodeOffset(); Emit(SMInstruction.ENTER, 0, entry.varnum); if(node.jjtgetnumchildren() == 4) node.jjtgetchild(3).jjtaccept(this, data); else node.jjtgetchild(2).jjtaccept(this, data); restore symboltable scope return DataType.Skip;
108 CodeGenerator Consider Program Function Declarations are generated first Start code with a jmp instruction Enter a new scope
109 Questions? The End
Compiler Construction
Compiler Construction Lecture 1 - An Overview 2003 Robert M. Siegfried All rights reserved A few basic definitions Translate - v, a.to turn into one s own language or another. b. to transform or turn from
How Compilers Work. by Walter Bright. Digital Mars
How Compilers Work by Walter Bright Digital Mars Compilers I've Built D programming language C++ C Javascript Java A.B.E.L Compiler Compilers Regex Lex Yacc Spirit Do only the easiest part Not very customizable
Compiler Construction
Compiler Construction Regular expressions Scanning Görel Hedin Reviderad 2013 01 23.a 2013 Compiler Construction 2013 F02-1 Compiler overview source code lexical analysis tokens intermediate code generation
CA4003 - Compiler Construction
CA4003 - Compiler Construction David Sinclair Overview This module will cover the compilation process, reading and parsing a structured language, storing it in an appropriate data structure, analysing
CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 20: Stack Frames 7 March 08
CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 20: Stack Frames 7 March 08 CS 412/413 Spring 2008 Introduction to Compilers 1 Where We Are Source code if (b == 0) a = b; Low-level IR code
Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)
Semantic Analysis Scoping (Readings 7.1,7.4,7.6) Static Dynamic Parameter passing methods (7.5) Building symbol tables (7.6) How to use them to find multiply-declared and undeclared variables Type checking
Intel Assembler. Project administration. Non-standard project. Project administration: Repository
Lecture 14 Project, Assembler and Exam Source code Compiler phases and program representations Frontend Lexical analysis (scanning) Backend Immediate code generation Today Project Emma Söderberg Revised
Compilers. Introduction to Compilers. Lecture 1. Spring term. Mick O Donnell: [email protected] Alfonso Ortega: alfonso.ortega@uam.
Compilers Spring term Mick O Donnell: [email protected] Alfonso Ortega: [email protected] Lecture 1 to Compilers 1 Topic 1: What is a Compiler? 3 What is a Compiler? A compiler is a computer
The previous chapter provided a definition of the semantics of a programming
Chapter 7 TRANSLATIONAL SEMANTICS The previous chapter provided a definition of the semantics of a programming language in terms of the programming language itself. The primary example was based on a Lisp
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 7 Scanner Parser Project Wednesday, September 7 DUE: Wednesday, September 21 This
ANTLR - Introduction. Overview of Lecture 4. ANTLR Introduction (1) ANTLR Introduction (2) Introduction
Overview of Lecture 4 www.antlr.org (ANother Tool for Language Recognition) Introduction VB HC4 Vertalerbouw HC4 http://fmt.cs.utwente.nl/courses/vertalerbouw/! 3.x by Example! Calc a simple calculator
COMP 356 Programming Language Structures Notes for Chapter 4 of Concepts of Programming Languages Scanning and Parsing
COMP 356 Programming Language Structures Notes for Chapter 4 of Concepts of Programming Languages Scanning and Parsing The scanner (or lexical analyzer) of a compiler processes the source program, recognizing
Lecture 9. Semantic Analysis Scoping and Symbol Table
Lecture 9. Semantic Analysis Scoping and Symbol Table Wei Le 2015.10 Outline Semantic analysis Scoping The Role of Symbol Table Implementing a Symbol Table Semantic Analysis Parser builds abstract syntax
Introduction. Compiler Design CSE 504. Overview. Programming problems are easier to solve in high-level languages
Introduction Compiler esign CSE 504 1 Overview 2 3 Phases of Translation ast modifled: Mon Jan 28 2013 at 17:19:57 EST Version: 1.5 23:45:54 2013/01/28 Compiled at 11:48 on 2015/01/28 Compiler esign Introduction
Programming Project 1: Lexical Analyzer (Scanner)
CS 331 Compilers Fall 2015 Programming Project 1: Lexical Analyzer (Scanner) Prof. Szajda Due Tuesday, September 15, 11:59:59 pm 1 Overview of the Programming Project Programming projects I IV will direct
Programming Languages CIS 443
Course Objectives Programming Languages CIS 443 0.1 Lexical analysis Syntax Semantics Functional programming Variable lifetime and scoping Parameter passing Object-oriented programming Continuations Exception
Programming Assignment II Due Date: See online CISC 672 schedule Individual Assignment
Programming Assignment II Due Date: See online CISC 672 schedule Individual Assignment 1 Overview Programming assignments II V will direct you to design and build a compiler for Cool. Each assignment will
Language Processing Systems
Language Processing Systems Evaluation Active sheets 10 % Exercise reports 30 % Midterm Exam 20 % Final Exam 40 % Contact Send e-mail to [email protected] Course materials at www.u-aizu.ac.jp/~hamada/education.html
Compiler I: Syntax Analysis Human Thought
Course map Compiler I: Syntax Analysis Human Thought Abstract design Chapters 9, 12 H.L. Language & Operating Sys. Compiler Chapters 10-11 Virtual Machine Software hierarchy Translator Chapters 7-8 Assembly
CSCI 3136 Principles of Programming Languages
CSCI 3136 Principles of Programming Languages Faculty of Computer Science Dalhousie University Winter 2013 CSCI 3136 Principles of Programming Languages Faculty of Computer Science Dalhousie University
Antlr ANother TutoRiaL
Antlr ANother TutoRiaL Karl Stroetmann March 29, 2007 Contents 1 Introduction 1 2 Implementing a Simple Scanner 1 A Parser for Arithmetic Expressions 4 Symbolic Differentiation 6 5 Conclusion 10 1 Introduction
X86-64 Architecture Guide
X86-64 Architecture Guide For the code-generation project, we shall expose you to a simplified version of the x86-64 platform. Example Consider the following Decaf program: class Program { int foo(int
Theory of Compilation
Theory of Compilation JLex, CUP tools CS Department, Haifa University Nov, 2010 By Bilal Saleh 1 Outlines JLex & CUP tutorials and Links JLex & CUP interoperability Structure of JLex specification JLex
1 Introduction. 2 An Interpreter. 2.1 Handling Source Code
1 Introduction The purpose of this assignment is to write an interpreter for a small subset of the Lisp programming language. The interpreter should be able to perform simple arithmetic and comparisons
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Semantic Analysis Project Tuesday, Feb 16 DUE: Monday, Mar 1 Extend your compiler
A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION
A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION Tao Chen 1, Tarek Sobh 2 Abstract -- In this paper, a software application that features the visualization of commonly used
Assembly Language: Function Calls" Jennifer Rexford!
Assembly Language: Function Calls" Jennifer Rexford! 1 Goals of this Lecture" Function call problems:! Calling and returning! Passing parameters! Storing local variables! Handling registers without interference!
C Compiler Targeting the Java Virtual Machine
C Compiler Targeting the Java Virtual Machine Jack Pien Senior Honors Thesis (Advisor: Javed A. Aslam) Dartmouth College Computer Science Technical Report PCS-TR98-334 May 30, 1998 Abstract One of the
How to make the computer understand? Lecture 15: Putting it all together. Example (Output assembly code) Example (input program) Anatomy of a Computer
How to make the computer understand? Fall 2005 Lecture 15: Putting it all together From parsing to code generation Write a program using a programming language Microprocessors talk in assembly language
Fighting malware on your own
Fighting malware on your own Vitaliy Kamlyuk Senior Virus Analyst Kaspersky Lab [email protected] Why fight malware on your own? 5 reasons: 1. Touch 100% of protection yourself 2. Be prepared
Hacking Techniques & Intrusion Detection. Ali Al-Shemery arabnix [at] gmail
Hacking Techniques & Intrusion Detection Ali Al-Shemery arabnix [at] gmail All materials is licensed under a Creative Commons Share Alike license http://creativecommonsorg/licenses/by-sa/30/ # whoami Ali
Textual Modeling Languages
Textual Modeling Languages Slides 4-31 and 38-40 of this lecture are reused from the Model Engineering course at TU Vienna with the kind permission of Prof. Gerti Kappel (head of the Business Informatics
Semantic Analysis: Types and Type Checking
Semantic Analysis Semantic Analysis: Types and Type Checking CS 471 October 10, 2007 Source code Lexical Analysis tokens Syntactic Analysis AST Semantic Analysis AST Intermediate Code Gen lexical errors
Programming Languages
Programming Languages In the beginning To use a computer, you needed to know how to program it. Today People no longer need to know how to program in order to use the computer. To see how this was accomplished,
Scanning and parsing. Topics. Announcements Pick a partner by Monday Makeup lecture will be on Monday August 29th at 3pm
Scanning and Parsing Announcements Pick a partner by Monday Makeup lecture will be on Monday August 29th at 3pm Today Outline of planned topics for course Overall structure of a compiler Lexical analysis
Introduction to Lex. General Description Input file Output file How matching is done Regular expressions Local names Using Lex
Introduction to Lex General Description Input file Output file How matching is done Regular expressions Local names Using Lex General Description Lex is a program that automatically generates code for
Software Vulnerabilities
Software Vulnerabilities -- stack overflow Code based security Code based security discusses typical vulnerabilities made by programmers that can be exploited by miscreants Implementing safe software in
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Scanner-Parser Project Thursday, Feb 7 DUE: Wednesday, Feb 20, 9:00 pm This project
TitanMist: Your First Step to Reversing Nirvana TitanMist. mist.reversinglabs.com
TitanMist: Your First Step to Reversing Nirvana TitanMist mist.reversinglabs.com Contents Introduction to TitanEngine.. 3 Introduction to TitanMist 4 Creating an unpacker for TitanMist.. 5 References and
csce4313 Programming Languages Scanner (pass/fail)
csce4313 Programming Languages Scanner (pass/fail) John C. Lusth Revision Date: January 18, 2005 This is your first pass/fail assignment. You may develop your code using any procedural language, but you
First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science
First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca
Static vs. Dynamic. Lecture 10: Static Semantics Overview 1. Typical Semantic Errors: Java, C++ Typical Tasks of the Semantic Analyzer
Lecture 10: Static Semantics Overview 1 Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing Produces trees Detects & eliminates ill-formed parse trees Static semantic analysis
03 - Lexical Analysis
03 - Lexical Analysis First, let s see a simplified overview of the compilation process: source code file (sequence of char) Step 2: parsing (syntax analysis) arse Tree Step 1: scanning (lexical analysis)
Analyse et Conception Formelle. Lesson 5. Crash Course on Scala
Analyse et Conception Formelle Lesson 5 Crash Course on Scala T. Genet (ISTIC/IRISA) ACF-5 1 / 36 Bibliography Simply Scala. Online tutorial: http://www.simply.com/fr http://www.simply.com/ Programming
A Tiny Guide to Programming in 32-bit x86 Assembly Language
CS308, Spring 1999 A Tiny Guide to Programming in 32-bit x86 Assembly Language by Adam Ferrari, [email protected] (with changes by Alan Batson, [email protected] and Mike Lack, [email protected])
Software Fingerprinting for Automated Malicious Code Analysis
Software Fingerprinting for Automated Malicious Code Analysis Philippe Charland Mission Critical Cyber Security Section October 25, 2012 Terms of Release: This document is approved for release to Defence
Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006. Final Examination. January 24 th, 2006
Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006 Final Examination January 24 th, 2006 NAME: Please read all instructions carefully before start answering. The exam will be
Where we are CS 4120 Introduction to Compilers Abstract Assembly Instruction selection mov e1 , e2 jmp e cmp e1 , e2 [jne je jgt ] l push e1 call e
0/5/03 Where we are CS 0 Introduction to Compilers Ross Tate Cornell University Lecture 8: Instruction Selection Intermediate code synta-directed translation reordering with traces Canonical intermediate
Pemrograman Dasar. Basic Elements Of Java
Pemrograman Dasar Basic Elements Of Java Compiling and Running a Java Application 2 Portable Java Application 3 Java Platform Platform: hardware or software environment in which a program runs. Oracle
Organization of DSLE part. Overview of DSLE. Model driven software engineering. Engineering. Tooling. Topics:
Organization of DSLE part Domain Specific Language Engineering Tooling Eclipse plus EMF Xtext, Xtend, Xpand, QVTo and ATL Prof.dr. Mark van den Brand GLT 2010/11 Topics: Meta-modeling Model transformations
Context free grammars and predictive parsing
Context free grammars and predictive parsing Programming Language Concepts and Implementation Fall 2012, Lecture 6 Context free grammars Next week: LR parsing Describing programming language syntax Ambiguities
University of Twente. A simulation of the Java Virtual Machine using graph grammars
University of Twente Department of Computer Science A simulation of the Java Virtual Machine using graph grammars Master of Science thesis M. R. Arends, November 2003 A simulation of the Java Virtual Machine
The C Programming Language course syllabus associate level
TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming
GENERIC and GIMPLE: A New Tree Representation for Entire Functions
GENERIC and GIMPLE: A New Tree Representation for Entire Functions Jason Merrill Red Hat, Inc. [email protected] 1 Abstract The tree SSA project requires a tree representation of functions for the optimizers
Lex et Yacc, exemples introductifs
Lex et Yacc, exemples introductifs D. Michelucci 1 LEX 1.1 Fichier makefile exemple1 : exemple1. l e x f l e x oexemple1. c exemple1. l e x gcc o exemple1 exemple1. c l f l l c exemple1 < exemple1. input
Getting Started with the Internet Communications Engine
Getting Started with the Internet Communications Engine David Vriezen April 7, 2014 Contents 1 Introduction 2 2 About Ice 2 2.1 Proxies................................. 2 3 Setting Up ICE 2 4 Slices 2
by LindaMay Patterson PartnerWorld for Developers, AS/400 January 2000
Home Products Consulting Industries News About IBM by LindaMay Patterson PartnerWorld for Developers, AS/400 January 2000 Copyright IBM Corporation, 1999. All Rights Reserved. All trademarks or registered
Lexical analysis FORMAL LANGUAGES AND COMPILERS. Floriano Scioscia. Formal Languages and Compilers A.Y. 2015/2016
Master s Degree Course in Computer Engineering Formal Languages FORMAL LANGUAGES AND COMPILERS Lexical analysis Floriano Scioscia 1 Introductive terminological distinction Lexical string or lexeme = meaningful
PL / SQL Basics. Chapter 3
PL / SQL Basics Chapter 3 PL / SQL Basics PL / SQL block Lexical units Variable declarations PL / SQL types Expressions and operators PL / SQL control structures PL / SQL style guide 2 PL / SQL Block Basic
Building a Multi-Threaded Web Server
Building a Multi-Threaded Web Server In this lab we will develop a Web server in two steps. In the end, you will have built a multi-threaded Web server that is capable of processing multiple simultaneous
Tutorial for Creating Resources in Java - Client
Tutorial for Creating Resources in Java - Client Overview Overview 1. Preparation 2. Creation of Eclipse Plug-ins 2.1 The flight plugin 2.2 The plugin fragment for unit tests 3. Create an integration test
Syntaktická analýza. Ján Šturc. Zima 208
Syntaktická analýza Ján Šturc Zima 208 Position of a Parser in the Compiler Model 2 The parser The task of the parser is to check syntax The syntax-directed translation stage in the compiler s front-end
Programming Languages and Compilers
PLaC-0.1 Programming Languages and Compilers Prof. Dr. Uwe Kastens WS 2013 / 2014 2013 bei Prof. Dr. Uwe Kastens 0. Introduction PLaC-0.2 The participants are taught to Objectives understand properties
How To Write A Program In Anieme Frontend 2.3.2.2 (For A Non-Programmable Language)
The Insieme Compiler Frontend: A Clang-based C/C++ Frontend Master Thesis in Computer Science by Bernhard Höckner submitted to the Faculty of Mathematics, Computer Science and Physics of the University
UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming
UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything
Stack Allocation. Run-Time Data Structures. Static Structures
Run-Time Data Structures Stack Allocation Static Structures For static structures, a fixed address is used throughout execution. This is the oldest and simplest memory organization. In current compilers,
Off-by-One exploitation tutorial
Off-by-One exploitation tutorial By Saif El-Sherei www.elsherei.com Introduction: I decided to get a bit more into Linux exploitation, so I thought it would be nice if I document this as a good friend
Flex/Bison Tutorial. Aaron Myles Landwehr [email protected] CAPSL 2/17/2012
Flex/Bison Tutorial Aaron Myles Landwehr [email protected] 1 GENERAL COMPILER OVERVIEW 2 Compiler Overview Frontend Middle-end Backend Lexer / Scanner Parser Semantic Analyzer Optimizers Code Generator
Compiler Design July 2004
irst Prev Next Last CS432/CSL 728: Compiler Design July 2004 S. Arun-Kumar [email protected] Department of Computer Science and ngineering I. I.. Delhi, Hauz Khas, New Delhi 110 016. July 30, 2004
Intermediate Code. Intermediate Code Generation
Intermediate Code CS 5300 - SJAllan Intermediate Code 1 Intermediate Code Generation The front end of a compiler translates a source program into an intermediate representation Details of the back end
About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Compiler Design
i About the Tutorial A compiler translates the codes written in one language to some other language without changing the meaning of the program. It is also expected that a compiler should make the target
Integrating Formal Models into the Programming Languages Course
Integrating Formal Models into the Programming Languages Course Allen B. Tucker Robert E. Noonan Computer Science Department Computer Science Department Bowdoin College College of William and Mary Brunswick,
MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.
Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java
If-Then-Else Problem (a motivating example for LR grammars)
If-Then-Else Problem (a motivating example for LR grammars) If x then y else z If a then if b then c else d this is analogous to a bracket notation when left brackets >= right brackets: [ [ ] ([ i ] j,
The Cool Reference Manual
The Cool Reference Manual Contents 1 Introduction 3 2 Getting Started 3 3 Classes 4 3.1 Features.............................................. 4 3.2 Inheritance............................................
Programming Languages
Programming Languages Programming languages bridge the gap between people and machines; for that matter, they also bridge the gap among people who would like to share algorithms in a way that immediately
Introduction. Figure 1 Schema of DarunGrim2
Reversing Microsoft patches to reveal vulnerable code Harsimran Walia Computer Security Enthusiast 2011 Abstract The paper would try to reveal the vulnerable code for a particular disclosed vulnerability,
Computer Programming. Course Details An Introduction to Computational Tools. Prof. Mauro Gaspari: [email protected]
Computer Programming Course Details An Introduction to Computational Tools Prof. Mauro Gaspari: [email protected] Road map for today The skills that we would like you to acquire: to think like a computer
Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.
Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to
02 B The Java Virtual Machine
02 B The Java Virtual Machine CS1102S: Data Structures and Algorithms Martin Henz January 22, 2010 Generated on Friday 22 nd January, 2010, 09:46 CS1102S: Data Structures and Algorithms 02 B The Java Virtual
Fast JavaScript in V8. The V8 JavaScript Engine. ...well almost all boats. Never use with. Never use with part 2.
Fast JavaScript in V8 Erik Corry Google The V8 JavaScript Engine A from-scratch reimplementation of the ECMAScript 3 language An Open Source project from Google, primarily developed here in Århus A real
An Introduction to Assembly Programming with the ARM 32-bit Processor Family
An Introduction to Assembly Programming with the ARM 32-bit Processor Family G. Agosta Politecnico di Milano December 3, 2011 Contents 1 Introduction 1 1.1 Prerequisites............................. 2
Design Patterns in Parsing
Abstract Axel T. Schreiner Department of Computer Science Rochester Institute of Technology 102 Lomb Memorial Drive Rochester NY 14623-5608 USA [email protected] Design Patterns in Parsing James E. Heliotis
Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:
Introduction to Programming and Algorithms Module 2 CS 146 Sam Houston State University Dr. Tim McGuire Introduction To Computers And Java Chapter Objectives To understand: the meaning and placement of
Moving from CS 61A Scheme to CS 61B Java
Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you
Return-oriented programming without returns
Faculty of Computer Science Institute for System Architecture, Operating Systems Group Return-oriented programming without urns S. Checkoway, L. Davi, A. Dmitrienko, A. Sadeghi, H. Shacham, M. Winandy
Applying Clang Static Analyzer to Linux Kernel
Applying Clang Static Analyzer to Linux Kernel 2012/6/7 FUJITSU COMPUTER TECHNOLOGIES LIMITED Hiroo MATSUMOTO 管 理 番 号 1154ka1 Copyright 2012 FUJITSU COMPUTER TECHNOLOGIES LIMITED Abstract Now there are
Comp151. Definitions & Declarations
Comp151 Definitions & Declarations Example: Definition /* reverse_printcpp */ #include #include using namespace std; int global_var = 23; // global variable definition void reverse_print(const
Parsing Technology and its role in Legacy Modernization. A Metaware White Paper
Parsing Technology and its role in Legacy Modernization A Metaware White Paper 1 INTRODUCTION In the two last decades there has been an explosion of interest in software tools that can automate key tasks
language 1 (source) compiler language 2 (target) Figure 1: Compiling a program
CS 2112 Lecture 27 Interpreters, compilers, and the Java Virtual Machine 1 May 2012 Lecturer: Andrew Myers 1 Interpreters vs. compilers There are two strategies for obtaining runnable code from a program
University of Toronto Department of Electrical and Computer Engineering. Midterm Examination. CSC467 Compilers and Interpreters Fall Semester, 2005
University of Toronto Department of Electrical and Computer Engineering Midterm Examination CSC467 Compilers and Interpreters Fall Semester, 2005 Time and date: TBA Location: TBA Print your name and ID
Stack machines The MIPS assembly language A simple source language Stack-machine implementation of the simple language Readings: 9.1-9.
Code Generation I Stack machines The MIPS assembly language A simple source language Stack-machine implementation of the simple language Readings: 9.1-9.7 Stack Machines A simple evaluation model No variables
JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4
JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 NOTE: SUN ONE Studio is almost identical with NetBeans. NetBeans is open source and can be downloaded from www.netbeans.org. I
Guile Present. version 0.3.0, updated 21 September 2014. Andy Wingo ([email protected])
Guile Present version 0.3.0, updated 21 September 2014 Andy Wingo ([email protected]) This manual is for Guile Present (version 0.3.0, updated 21 September 2014) Copyright 2014 Andy Wingo Permission is granted
Advanced compiler construction. General course information. Teacher & assistant. Course goals. Evaluation. Grading scheme. Michel Schinz 2007 03 16
Advanced compiler construction Michel Schinz 2007 03 16 General course information Teacher & assistant Course goals Teacher: Michel Schinz [email protected] Assistant: Iulian Dragos INR 321, 368 64
I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015
RESEARCH ARTICLE An Exception Monitoring Using Java Jyoti Kumari, Sanjula Singh, Ankur Saxena Amity University Sector 125 Noida Uttar Pradesh India OPEN ACCESS ABSTRACT Many programmers do not check for
