1 YACC File Format

Total Page:16

File Type:pdf, Size:1020Kb

1 YACC File Format Introduction History • What is YACC ? • Yacc original written by Stephen C. Johnson, 1975. – Tool which will produce a parser for a given grammar. •Variants: – – YACC (Yet Another Compiler Compiler) is a lex, yacc (AT&T) program designed to compile a LALR(1) – bison: a yacc replacement (GNU) grammar and to produce the source code of the – flex: fast lexical analyzer (GNU) syntactic analyzer of a language produced by this – BSD yacc grammar. – PCLEX, PCYACC (Abraxas Software) How YACC Works An YACC File Example y.tab.h %{ #include <stdio.h> YACC source (foo.y) yacc y.tab.c %} y.output %token NAME NUMBER %% (1) Parse statement: NAME '=' expression | expression { printf("= %d\n", $1); } ; a.out expression: expression '+' NUMBER { $$ = $1 + $3; } y.tab.c cc / gcc | expression '-' NUMBER { $$ = $1 - $3; } | NUMBER { $$ = $1; } ; %% (2) Compile int yyerror(char *s) { fprintf(stderr, "%s\n", s); Abstract return 0; } Token stream a.out Syntax int main(void) Tree { yyparse(); return 0; (3) Run } YACC File Format Definitions Section %{ C declarations %{ %} #include <stdio.h> yacc declarations #include <stdlib.h> %% Grammar rules %} It is a terminal %% %token ID NUM Additional C code %start expr start from expr – Comments in /* ... */ may appear in any of the sections. 1 Start Symbol Rules Section • The first non-terminal specified in the grammar • Is a grammar specification section. • Example • To overwrite it with %start declaraction. %start non-terminal expr : expr '+' term | term; term : term '*' factor | factor; factor : '(' expr ')' | ID | NUM; Rules Section The Position of Rules • Normally written like this expr : expr '+' term { $$ = $1 + $3; } • Example: | term { $$ = $1; } expr : expr '+' term ; | term term : term '*' factor { $$ = $1 * $3; } ; | factor { $$ = $1; } term : term '*' factor ; | factor factor : '(' expr ')' { $$ = $2; } ; | ID factor : '(' expr ')' | NUM | ID ; | NUM ; Works with LEX Communication between LEX and YACC [0-9]+ yacc -d gram.y call yylex() • Use enumeration / define Will produce: • YACC creates y.tab.h • LEX includes y.tab.h y.tab.h next token is NUM 12 + 26 NUM ‘+’ NUM LEX and YACC need a way to identify tokens 2 Communication between LEX and YACC YACC %{ scanner.l yacc -d xxx.y #include <stdio.h> produces #include "y.tab.h" • Rules may be recursive y.tab.h %} • Rules may be ambiguous* id [_a-zA-Z][_a-zA-Z0-9]* %% # define CHAR 258 • Uses bottom up Shift/Reduce parsing int { return INT; } # define FLOAT 259 – Get a token char { return CHAR; } # define ID 260 float { return FLOAT; } – Push onto stack # define INT 261 {id} { return ID;} – Can it reduced ? • yes: Reduce using a rule %{ parser.y #include <stdio.h> • no: Get another token #include <stdlib.h> • Yacc cannot look ahead more than one token %} %token CHAR, FLOAT, ID, INT %% Passing value of token Passing value of token • Every terminal-token (symbol) may represent a value or data type • Yacc allows symbols to have multiple types of value symbols – May be a numeric quantity in case of a number (42) %union { – May be a pointer to a string ("Hello, World!") double dval; int vblno; • When using lex, we put the value into yylval char* strval; – In complex situations yylval is a union } • Typical lex code: [0-9]+ {yylval = atoi(yytext); return NUM} Passing value of token Yacc Example %union { • Taken from Lex & Yacc double dval; yacc -d • Example: Simple calculator int vblno; y.tab.h a = 4 + 6 char* strval; … a } extern YYSTYPE yylval; a=10 b = 7 c = a + b [0-9]+ { yylval.vblno = atoi(yytext); c return NUM;} c = 17 [A-z]+ { yylval.strval = strdup(yytext); $ return STRING;} Lex file include “y.tab.h” 3 Grammar Symbol Table expression ::= expression '+' term | 0 expression '-' term | name value 1 name value term #define NSYMS 20 /* maximum number 2 name value of symbols */ 3 name value term ::= term '*' factor | 4 name value term '/' factor | struct symtab { 5 name value factor char *name; 6 name value double value; 7 name value factor ::= '(' expression ')' | } symtab[NSYMS]; 8 name value '-' factor | 9 name value NUMBER | struct symtab *symlook(); 10 name value NAME parser.h Parser Parser (cont’d) %{ statement_list: statement '\n' #include "parser.h" Terminal NAME and <symp>have | statement_list statement '\n' #include <string.h> the same data type. ; %} Nonterminal expression and statement: NAME '=' expression { $1->value = $3; } %union { | expression { printf("= %g\n", $1); } double dval; <dval> have the same data type. ; struct symtab *symp; } expression: expression '+' term { $$ = $1 + $3; } %token <symp> NAME | expression '-' term { $$ = $1 - $3; } %token <dval> NUMBER | term ; %type <dval> expression %type <dval> term %type <dval> factor %% parser.y parser.y Parser (cont’d) Scanner term: term '*' factor { $$ = $1 * $3; } %{ | term '/' factor { if ($3 == 0.0) #include "y.tab.h" yyerror("divide by zero"); #include "parser.h" else #include <math.h> $$ = $1 / $3; %} } %% | factor ; ([0-9]+|([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?) { yylval.dval = atof(yytext); factor: '(' expression ')' { $$ = $2; } return NUMBER; | '-' factor { $$ = -$2; } } | NUMBER { $$ = $1; } | NAME { $$ = $1->value; } [ \t] ; /* ignore white space */ ; %% parser.y scanner.l 4 Scanner (cont’d) Precedence / Association [A-Za-z][A-Za-z0-9]* { /* return symbol pointer */ yylval.symp = symlook(yytext); (1) 1 - 2 - 3 return NAME; } (2) 1 - 2 * 3 "$" { return 0; /* end of input */ } \n |”=“|”+”|”-”|”*”|”/” return yytext[0]; 1. 1-2-3 = (1-2)-3? or 1-(2-3)? %% 2. 1-2*3 = 1-(2*3) or (1-2)*3? Yacc: Shift/Reduce conflicts. Default is to shift. scanner.l Precedence / Association Precedence / Association %left '+' '-' %right ‘=‘ %left '*' '/' %noassoc UMINUS %left '<' '>' NE LE GE expr : expr ‘+’ expr { $$ = $1 + $3; } %left '+' '-‘ | expr ‘-’ expr { $$ = $1 - $3; } %left '*' '/' | expr ‘*’ expr { $$ = $1 * $3; } | expr ‘/’ expr highest precedence { if($3==0) yyerror(“divide 0”); else $$ = $1 / $3; } | ‘-’ expr %prec UMINUS {$$ = -$2; } IF-ELSE Ambiguity IF-ELSE Ambiguity • Consider following rule: • It is a shift/reduce conflict. stmt : IF expr stmt • Yacc will always choose to shift. | IF expr stmt ELSE stmt …… • A solution: stmt : matched | unmatched Following state ? ; matched: other_stmt | IF expr THEN matched ELSE matched IF expr IF expr stmt ELSE stmt ; unmatched: IF expr THEN stmt | IF expr THEN matched ELSE unmatched ; 5 Shift/Reduce Conflicts Reduce/Reduce Conflicts • Reduce/Reduce Conflicts: • shift/reduce conflict start : expr | stmt ; – occurs when a grammar is written in such a way expr : CONSTANT; that a decision between shifting and reducing can stmt : CONSTANT; not be made. • Yacc resolves the conflict by reducing using the rule that occurs – ex: IF-ELSE ambigious. earlier in the grammar. NOT GOOD!! • To resolve this conflict, yacc will choose to • So, modify grammar to eliminate them. shift. Error Messages Debug Your Parser 1. Use –t option or define YYDEBUG to 1. • Bad error message: 2. Set variable yydebug to 1 when you want to – Syntax error. trace parsing status. – Compiler needs to give programmer a good 3. If you want to trace the semantic values advice. z Define your YYPRINT function • It is better to track the line number in lex: void yyerror(char *s) { fprintf(stderr, "line %d: %s\n:", yylineno, s); } Shift and Reducing: Example Recursive Grammar • Left recursion stmt: stmt ‘;’ stmt list: stack: item | NAME ‘=‘ exp | list ',' item <empty> ; • Right recursion exp: exp ‘+’ exp list: item | item ',' list | exp ‘-’ exp input: ; a = 7; b = 3 + a + 2 | NAME • LR parser (e.g. yacc) prefers left recursion. | NUMBER • LL parser prefers right recursion. 6 YACC Declaration Summary YACC Declaration Summary `%start' `%right' Specify the grammar's start symbol Declare a terminal symbol (token type name) that is right-associative `%union' Declare the collection of data types that semantic values may have `%left' Declare a terminal symbol (token type name) that is left-associative `%token' Declare a terminal symbol (token type name) with no precedence or `%nonassoc' associativity specified Declare a terminal symbol (token type name) that is nonassociative (using it in a way that would be associative is a syntax error, `%type' ex: x op. y op. z is syntax error) Declare the type of semantic values for a nonterminal symbol 7.
Recommended publications
  • Chapter # 9 LEX and YACC
    Chapter # 9 LEX and YACC Dr. Shaukat Ali Department of Computer Science University of Peshawar Lex and Yacc Lex and yacc are a matched pair of tools. Lex breaks down files into sets of "tokens," roughly analogous to words. Yacc takes sets of tokens and assembles them into higher-level constructs, analogous to sentences. Lex's output is mostly designed to be fed into some kind of parser. Yacc is designed to work with the output of Lex. 2 Lex and Yacc Lex and yacc are tools for building programs. Their output is itself code – Which needs to be fed into a compiler – May be additional user code is added to use the code generated by lex and yacc 3 Lex : A lexical analyzer generator Lex is a program designed to generate scanners, also known as tokenizers, which recognize lexical patterns in text Lex is an acronym that stands for "lexical analyzer generator.“ The main purpose is to facilitate lexical analysis The processing of character sequences in source code to produce tokens for use as input to other programs such as parsers Another tool for lexical analyzer generation is Flex 4 Lex : A lexical analyzer generator lex.lex is an a input file written in a language which describes the generation of lexical analyzer. The lex compiler transforms lex.l to a C program known as lex.yy.c. lex.yy.c is compiled by the C compiler to a file called a.out. The output of C compiler is the working lexical analyzer which takes stream of input characters and produces a stream of tokens.
    [Show full text]
  • Text Editing in UNIX: an Introduction to Vi and Editing
    Text Editing in UNIX A short introduction to vi, pico, and gedit Copyright 20062009 Stewart Weiss About UNIX editors There are two types of text editors in UNIX: those that run in terminal windows, called text mode editors, and those that are graphical, with menus and mouse pointers. The latter require a windowing system, usually X Windows, to run. If you are remotely logged into UNIX, say through SSH, then you should use a text mode editor. It is possible to use a graphical editor, but it will be much slower to use. I will explain more about that later. 2 CSci 132 Practical UNIX with Perl Text mode editors The three text mode editors of choice in UNIX are vi, emacs, and pico (really nano, to be explained later.) vi is the original editor; it is very fast, easy to use, and available on virtually every UNIX system. The vi commands are the same as those of the sed filter as well as several other common UNIX tools. emacs is a very powerful editor, but it takes more effort to learn how to use it. pico is the easiest editor to learn, and the least powerful. pico was part of the Pine email client; nano is a clone of pico. 3 CSci 132 Practical UNIX with Perl What these slides contain These slides concentrate on vi because it is very fast and always available. Although the set of commands is very cryptic, by learning a small subset of the commands, you can edit text very quickly. What follows is an outline of the basic concepts that define vi.
    [Show full text]
  • Project1: Build a Small Scanner/Parser
    Project1: Build A Small Scanner/Parser Introducing Lex, Yacc, and POET cs5363 1 Project1: Building A Scanner/Parser Parse a subset of the C language Support two types of atomic values: int float Support one type of compound values: arrays Support a basic set of language concepts Variable declarations (int, float, and array variables) Expressions (arithmetic and boolean operations) Statements (assignments, conditionals, and loops) You can choose a different but equivalent language Need to make your own test cases Options of implementation (links available at class web site) Manual in C/C++/Java (or whatever other lang.) Lex and Yacc (together with C/C++) POET: a scripting compiler writing language Or any other approach you choose --- must document how to download/use any tools involved cs5363 2 This is just starting… There will be two other sub-projects Type checking Check the types of expressions in the input program Optimization/analysis/translation Do something with the input code, output the result The starting project is important because it determines which language you can use for the other projects Lex+Yacc ===> can work only with C/C++ POET ==> work with POET Manual ==> stick to whatever language you pick This class: introduce Lex/Yacc/POET to you cs5363 3 Using Lex to build scanners lex.yy.c MyLex.l lex/flex lex.yy.c a.out gcc/cc Input stream a.out tokens Write a lex specification Save it in a file (MyLex.l) Compile the lex specification file by invoking lex/flex lex MyLex.l A lex.yy.c file is generated
    [Show full text]
  • User Manual for Ox: an Attribute-Grammar Compiling System Based on Yacc, Lex, and C Kurt M
    Computer Science Technical Reports Computer Science 12-1992 User Manual for Ox: An Attribute-Grammar Compiling System based on Yacc, Lex, and C Kurt M. Bischoff Iowa State University Follow this and additional works at: http://lib.dr.iastate.edu/cs_techreports Part of the Programming Languages and Compilers Commons Recommended Citation Bischoff, Kurt M., "User Manual for Ox: An Attribute-Grammar Compiling System based on Yacc, Lex, and C" (1992). Computer Science Technical Reports. 21. http://lib.dr.iastate.edu/cs_techreports/21 This Article is brought to you for free and open access by the Computer Science at Iowa State University Digital Repository. It has been accepted for inclusion in Computer Science Technical Reports by an authorized administrator of Iowa State University Digital Repository. For more information, please contact [email protected]. User Manual for Ox: An Attribute-Grammar Compiling System based on Yacc, Lex, and C Abstract Ox generalizes the function of Yacc in the way that attribute grammars generalize context-free grammars. Ordinary Yacc and Lex specifications may be augmented with definitions of synthesized and inherited attributes written in C syntax. From these specifications, Ox generates a program that builds and decorates attributed parse trees. Ox accepts a most general class of attribute grammars. The user may specify postdecoration traversals for easy ordering of side effects such as code generation. Ox handles the tedious and error-prone details of writing code for parse-tree management, so its use eases problems of security and maintainability associated with that aspect of translator development. The translators generated by Ox use internal memory management that is often much faster than the common technique of calling malloc once for each parse-tree node.
    [Show full text]
  • Yacc a Tool for Syntactic Analysis
    1 Yacc a tool for Syntactic Analysis CS 315 – Programming Languages Pinar Duygulu Bilkent University CS315 Programming Languages © Pinar Duygulu Lex and Yacc 2 1) Lexical Analysis: Lexical analyzer: scans the input stream and converts sequences of characters into tokens. Lex is a tool for writing lexical analyzers. 2) Syntactic Analysis (Parsing): Parser: reads tokens and assembles them into language constructs using the grammar rules of the language. Yacc is a tool for constructing parsers. Yet Another Compiler to Compiler Reads a specification file that codifies the grammar of a language and generates a parsing routine CS315 Programming Languages © Pinar Duygulu 3 Yacc • Yacc specification describes a Context Free Grammar (CFG), that can be used to generate a parser. Elements of a CFG: 1. Terminals: tokens and literal characters, 2. Variables (nonterminals): syntactical elements, 3. Production rules, and 4. Start rule. CS315 Programming Languages © Pinar Duygulu 4 Yacc Format of a production rule: symbol: definition {action} ; Example: A → Bc is written in yacc as a: b 'c'; CS315 Programming Languages © Pinar Duygulu 5 Yacc Format of a yacc specification file: declarations %% grammar rules and associated actions %% C programs CS315 Programming Languages © Pinar Duygulu 6 Declarations To define tokens and their characteristics %token: declare names of tokens %left: define left-associative operators %right: define right-associative operators %nonassoc: define operators that may not associate with themselves %type: declare the type of variables %union: declare multiple data types for semantic values %start: declare the start symbol (default is the first variable in rules) %prec: assign precedence to a rule %{ C declarations directly copied to the resulting C program %} (E.g., variables, types, macros…) CS315 Programming Languages © Pinar Duygulu 7 A simple yacc specification to accept L={ anbn | n>1}.
    [Show full text]
  • Binpac: a Yacc for Writing Application Protocol Parsers
    binpac: A yacc for Writing Application Protocol Parsers Ruoming Pang∗ Vern Paxson Google, Inc. International Computer Science Institute and New York, NY, USA Lawrence Berkeley National Laboratory [email protected] Berkeley, CA, USA [email protected] Robin Sommer Larry Peterson International Computer Science Institute Princeton University Berkeley, CA, USA Princeton, NJ, USA [email protected] [email protected] ABSTRACT Similarly, studies of Email traffic [21, 46], peer-to-peer applica- A key step in the semantic analysis of network traffic is to parse the tions [37], online gaming, and Internet attacks [29] require under- traffic stream according to the high-level protocols it contains. This standing application-level traffic semantics. However, it is tedious, process transforms raw bytes into structured, typed, and semanti- error-prone, and sometimes prohibitively time-consuming to build cally meaningful data fields that provide a high-level representation application-level analysis tools from scratch, due to the complexity of the traffic. However, constructing protocol parsers by hand is a of dealing with low-level traffic data. tedious and error-prone affair due to the complexity and sheer num- We can significantly simplify the process if we can leverage a ber of application protocols. common platform for various kinds of application-level traffic anal- This paper presents binpac, a declarative language and com- ysis. A key element of such a platform is application-protocol piler designed to simplify the task of constructing robust and effi- parsers that translate packet streams into high-level representations cient semantic analyzers for complex network protocols. We dis- of the traffic, on top of which we can then use measurement scripts cuss the design of the binpac language and a range of issues that manipulate semantically meaningful data elements such as in generating efficient parsers from high-level specifications.
    [Show full text]
  • An Attribute- Grammar Compiling System Based on Yacc, Lex, and C Kurt M
    View metadata, citation and similar papers at core.ac.uk brought to you by CORE provided by Digital Repository @ Iowa State University Computer Science Technical Reports Computer Science 12-1992 Design, Implementation, Use, and Evaluation of Ox: An Attribute- Grammar Compiling System based on Yacc, Lex, and C Kurt M. Bischoff Iowa State University Follow this and additional works at: http://lib.dr.iastate.edu/cs_techreports Part of the Programming Languages and Compilers Commons Recommended Citation Bischoff, Kurt M., "Design, Implementation, Use, and Evaluation of Ox: An Attribute- Grammar Compiling System based on Yacc, Lex, and C" (1992). Computer Science Technical Reports. 23. http://lib.dr.iastate.edu/cs_techreports/23 This Article is brought to you for free and open access by the Computer Science at Iowa State University Digital Repository. It has been accepted for inclusion in Computer Science Technical Reports by an authorized administrator of Iowa State University Digital Repository. For more information, please contact [email protected]. Design, Implementation, Use, and Evaluation of Ox: An Attribute- Grammar Compiling System based on Yacc, Lex, and C Abstract Ox generalizes the function of Yacc in the way that attribute grammars generalize context-free grammars. Ordinary Yacc and Lex specifications may be augmented with definitions of synthesized and inherited attributes written in C syntax. From these specifications, Ox generates a program that builds and decorates attributed parse trees. Ox accepts a most general class of attribute grammars. The user may specify postdecoration traversals for easy ordering of side effects such as code generation. Ox handles the tedious and error-prone details of writing code for parse-tree management, so its use eases problems of security and maintainability associated with that aspect of translator development.
    [Show full text]
  • A Brief Introduction to Unix-2019-AMS
    A Brief Introduction to Linux/Unix – AMS 2019 Pete Pokrandt UW-Madison AOS Systems Administrator [email protected] Twitter @PTH1 Brief Intro to Linux/Unix o Brief History of Unix o Basics of a Unix session o The Unix File System o Working with Files and Directories o Your Environment o Common Commands Brief Intro to Unix (contd) o Compilers, Email, Text processing o Image Processing o The vi editor History of Unix o Created in 1969 by Kenneth Thompson and Dennis Ritchie at AT&T o Revised in-house until first public release 1977 o 1977 – UC-Berkeley – Berkeley Software Distribution (BSD) o 1983 – Sun Workstations produced a Unix Workstation o AT&T unix -> System V History of Unix o Today – two main variants, but blended o System V (Sun Solaris, SGI, Dec OSF1, AIX, linux) o BSD (Old SunOS, linux, Mac OSX/MacOS) History of Unix o It’s been around for a long time o It was written by computer programmers for computer programmers o Case sensitive, mostly lowercase abbreviations Basics of a Unix Login Session o The Shell – the command line interface, where you enter commands, etc n Some common shells Bourne Shell (sh) C Shell (csh) TC Shell (tcsh) Korn Shell (ksh) Bourne Again Shell (bash) [OSX terminal] Basics of a Unix Login Session o Features provided by the shell n Create an environment that meets your needs n Write shell scripts (batch files) n Define command aliases n Manipulate command history n Automatically complete the command line (tab) n Edit the command line (arrow keys in tcsh) Basics of a Unix Login Session o Logging in to a unix
    [Show full text]
  • UNIX (Solaris/Linux) Quick Reference Card Logging in Directory Commands at the Login: Prompt, Enter Your Username
    UNIX (Solaris/Linux) QUICK REFERENCE CARD Logging In Directory Commands At the Login: prompt, enter your username. At the Password: prompt, enter ls Lists files in current directory your system password. Linux is case-sensitive, so enter upper and lower case ls -l Long listing of files letters as required for your username, password and commands. ls -a List all files, including hidden files ls -lat Long listing of all files sorted by last Exiting or Logging Out modification time. ls wcp List all files matching the wildcard Enter logout and press <Enter> or type <Ctrl>-D. pattern Changing your Password ls dn List files in the directory dn tree List files in tree format Type passwd at the command prompt. Type in your old password, then your new cd dn Change current directory to dn password, then re-enter your new password for verification. If the new password cd pub Changes to subdirectory “pub” is verified, your password will be changed. Many systems age passwords; this cd .. Changes to next higher level directory forces users to change their passwords at predetermined intervals. (previous directory) cd / Changes to the root directory Changing your MS Network Password cd Changes to the users home directory cd /usr/xx Changes to the subdirectory “xx” in the Some servers maintain a second password exclusively for use with Microsoft windows directory “usr” networking, allowing you to mount your home directory as a Network Drive. mkdir dn Makes a new directory named dn Type smbpasswd at the command prompt. Type in your old SMB passwword, rmdir dn Removes the directory dn (the then your new password, then re-enter your new password for verification.
    [Show full text]
  • Lex and Yacc
    Lex and Yacc A Quick Tour HW8–Use Lex/Yacc to Turn this: Into this: <P> Here's a list: Here's a list: * This is item one of a list <UL> * This is item two. Lists should be <LI> This is item one of a list indented four spaces, with each item <LI>This is item two. Lists should be marked by a "*" two spaces left of indented four spaces, with each item four-space margin. Lists may contain marked by a "*" two spaces left of four- nested lists, like this: space margin. Lists may contain * Hi, I'm item one of an inner list. nested lists, like this:<UL><LI> Hi, I'm * Me two. item one of an inner list. <LI>Me two. * Item 3, inner. <LI> Item 3, inner. </UL><LI> Item 3, * Item 3, outer list. outer list.</UL> This is outside both lists; should be back This is outside both lists; should be to no indent. back to no indent. <P><P> Final suggestions: Final suggestions 2 if myVar == 6.02e23**2 then f( .. ! char stream LEX token stream if myVar == 6.02e23**2 then f( ! tokenstream YACC parse tree if-stmt == fun call var ** Arg 1 Arg 2 float-lit int-lit . ! 3 Lex / Yacc History Origin – early 1970’s at Bell Labs Many versions & many similar tools Lex, flex, jflex, posix, … Yacc, bison, byacc, CUP, posix, … Targets C, C++, C#, Python, Ruby, ML, … We’ll use jflex & byacc/j, targeting java (but for simplicity, I usually just say lex/yacc) 4 Uses “Front end” of many real compilers E.g., gcc “Little languages”: Many special purpose utilities evolve some clumsy, ad hoc, syntax Often easier, simpler, cleaner and more flexible to use lex/yacc or similar tools from the start 5 Lex: A Lexical Analyzer Generator Input: Regular exprs defining "tokens" my.flex Fragments of declarations & code Output: jflex A java program “yylex.java” Use: yylex.java Compile & link with your main() Calls to yylex() read chars & return successive tokens.
    [Show full text]
  • Differentiating Logarithm and Exponential Functions
    Differentiating logarithm and exponential functions mc-TY-logexp-2009-1 This unit gives details of how logarithmic functions and exponential functions are differentiated from first principles. In order to master the techniques explained here it is vital that you undertake plenty of practice exercises so that they become second nature. After reading this text, and/or viewing the video tutorial on this topic, you should be able to: • differentiate ln x from first principles • differentiate ex Contents 1. Introduction 2 2. Differentiation of a function f(x) 2 3. Differentiation of f(x)=ln x 3 4. Differentiation of f(x) = ex 4 www.mathcentre.ac.uk 1 c mathcentre 2009 1. Introduction In this unit we explain how to differentiate the functions ln x and ex from first principles. To understand what follows we need to use the result that the exponential constant e is defined 1 1 as the limit as t tends to zero of (1 + t) /t i.e. lim (1 + t) /t. t→0 1 To get a feel for why this is so, we have evaluated the expression (1 + t) /t for a number of decreasing values of t as shown in Table 1. Note that as t gets closer to zero, the value of the expression gets closer to the value of the exponential constant e≈ 2.718.... You should verify some of the values in the Table, and explore what happens as t reduces further. 1 t (1 + t) /t 1 (1+1)1/1 = 2 0.1 (1+0.1)1/0.1 = 2.594 0.01 (1+0.01)1/0.01 = 2.705 0.001 (1.001)1/0.001 = 2.717 0.0001 (1.0001)1/0.0001 = 2.718 We will also make frequent use of the laws of indices and the laws of logarithms, which should be revised if necessary.
    [Show full text]
  • Time-Sharing System
    UNIXTM TIME-SHARING SYSTEM: UNIX PROGRAMMER'S MANUAL Seventh Edition, Volume 2B January, 1979 Bell Telephone Laboratories, Incorporated Murray Hill, New Jersey Yacc: Yet Another Compiler-Compiler Stephen C. Johnson Bell Laboratories Murray Hill, New Jersey 07974 ABSTRACT Computer program input generally has some structure; in fact, every computer program that does input can be thought of as de®ning an ``input language'' which it accepts. An input language may be as complex as a programming language, or as sim- ple as a sequence of numbers. Unfortunately, usual input facilities are limited, dif®cult to use, and often are lax about checking their inputs for validity. Yacc provides a general tool for describing the input to a computer program. The Yacc user speci®es the structures of his input, together with code to be invoked as each such structure is recognized. Yacc turns such a speci®cation into a subroutine that handles the input process; frequently, it is convenient and appropriate to have most of the ¯ow 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 con- tinuation conventions, which typically defy easy grammatical speci®cation. Yacc is written in portable C. The class of speci®cations accepted is a very gen- eral one: LALR(1) grammars with disambiguating rules.
    [Show full text]